f218cc0e979db0c613d579b6ecf1a2319e4ff217
[dotfiles/.git] / typingsInstaller.js
1 /*! *****************************************************************************
2 Copyright (c) Microsoft Corporation. All rights reserved.
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 this file except in compliance with the License. You may obtain a copy of the
5 License at http://www.apache.org/licenses/LICENSE-2.0
6
7 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10 MERCHANTABLITY OR NON-INFRINGEMENT.
11
12 See the Apache Version 2.0 License for specific language governing permissions
13 and limitations under the License.
14 ***************************************************************************** */
15
16
17 "use strict";
18 var __spreadArrays = (this && this.__spreadArrays) || function () {
19     for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
20     for (var r = Array(s), k = 0, i = 0; i < il; i++)
21         for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
22             r[k] = a[j];
23     return r;
24 };
25 var __assign = (this && this.__assign) || function () {
26     __assign = Object.assign || function(t) {
27         for (var s, i = 1, n = arguments.length; i < n; i++) {
28             s = arguments[i];
29             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
30                 t[p] = s[p];
31         }
32         return t;
33     };
34     return __assign.apply(this, arguments);
35 };
36 var __generator = (this && this.__generator) || function (thisArg, body) {
37     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
38     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
39     function verb(n) { return function (v) { return step([n, v]); }; }
40     function step(op) {
41         if (f) throw new TypeError("Generator is already executing.");
42         while (_) try {
43             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;
44             if (y = 0, t) op = [op[0] & 2, t.value];
45             switch (op[0]) {
46                 case 0: case 1: t = op; break;
47                 case 4: _.label++; return { value: op[1], done: false };
48                 case 5: _.label++; y = op[1]; op = [0]; continue;
49                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
50                 default:
51                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
52                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
53                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
54                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
55                     if (t[2]) _.ops.pop();
56                     _.trys.pop(); continue;
57             }
58             op = body.call(thisArg, _);
59         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
60         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
61     }
62 };
63 var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
64     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
65     return cooked;
66 };
67 var __extends = (this && this.__extends) || (function () {
68     var extendStatics = function (d, b) {
69         extendStatics = Object.setPrototypeOf ||
70             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
71             function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
72         return extendStatics(d, b);
73     };
74     return function (d, b) {
75         extendStatics(d, b);
76         function __() { this.constructor = d; }
77         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
78     };
79 })();
80 var ts;
81 (function (ts) {
82     // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
83     // If changing the text in this section, be sure to test `configurePrerelease` too.
84     ts.versionMajorMinor = "3.9";
85     /** The version of the TypeScript compiler release */
86     ts.version = "3.9.6";
87     /**
88      * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
89      */
90     /* @internal */
91     function tryGetNativeMap() {
92         // eslint-disable-next-line no-in-operator
93         return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
94     }
95     ts.tryGetNativeMap = tryGetNativeMap;
96     /* @internal */
97     ts.Map = tryGetNativeMap() || (function () {
98         // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
99         if (typeof ts.createMapShim === "function") {
100             return ts.createMapShim();
101         }
102         throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
103     })();
104     /* @internal */
105     var Comparison;
106     (function (Comparison) {
107         Comparison[Comparison["LessThan"] = -1] = "LessThan";
108         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
109         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
110     })(Comparison = ts.Comparison || (ts.Comparison = {}));
111 })(ts || (ts = {}));
112 /* @internal */
113 var ts;
114 (function (ts) {
115     ts.emptyArray = [];
116     /** Create a new map. */
117     function createMap() {
118         return new ts.Map();
119     }
120     ts.createMap = createMap;
121     /** Create a new map from an array of entries. */
122     function createMapFromEntries(entries) {
123         var map = createMap();
124         for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
125             var _a = entries_1[_i], key = _a[0], value = _a[1];
126             map.set(key, value);
127         }
128         return map;
129     }
130     ts.createMapFromEntries = createMapFromEntries;
131     /** Create a new map from a template object is provided, the map will copy entries from it. */
132     function createMapFromTemplate(template) {
133         var map = new ts.Map();
134         // Copies keys/values from template. Note that for..in will not throw if
135         // template is undefined, and instead will just exit the loop.
136         for (var key in template) {
137             if (hasOwnProperty.call(template, key)) {
138                 map.set(key, template[key]);
139             }
140         }
141         return map;
142     }
143     ts.createMapFromTemplate = createMapFromTemplate;
144     function length(array) {
145         return array ? array.length : 0;
146     }
147     ts.length = length;
148     /**
149      * Iterates through 'array' by index and performs the callback on each element of array until the callback
150      * returns a truthy value, then returns that value.
151      * If no such value is found, the callback is applied to each element of array and undefined is returned.
152      */
153     function forEach(array, callback) {
154         if (array) {
155             for (var i = 0; i < array.length; i++) {
156                 var result = callback(array[i], i);
157                 if (result) {
158                     return result;
159                 }
160             }
161         }
162         return undefined;
163     }
164     ts.forEach = forEach;
165     /**
166      * Like `forEach`, but iterates in reverse order.
167      */
168     function forEachRight(array, callback) {
169         if (array) {
170             for (var i = array.length - 1; i >= 0; i--) {
171                 var result = callback(array[i], i);
172                 if (result) {
173                     return result;
174                 }
175             }
176         }
177         return undefined;
178     }
179     ts.forEachRight = forEachRight;
180     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
181     function firstDefined(array, callback) {
182         if (array === undefined) {
183             return undefined;
184         }
185         for (var i = 0; i < array.length; i++) {
186             var result = callback(array[i], i);
187             if (result !== undefined) {
188                 return result;
189             }
190         }
191         return undefined;
192     }
193     ts.firstDefined = firstDefined;
194     function firstDefinedIterator(iter, callback) {
195         while (true) {
196             var iterResult = iter.next();
197             if (iterResult.done) {
198                 return undefined;
199             }
200             var result = callback(iterResult.value);
201             if (result !== undefined) {
202                 return result;
203             }
204         }
205     }
206     ts.firstDefinedIterator = firstDefinedIterator;
207     function zipWith(arrayA, arrayB, callback) {
208         var result = [];
209         ts.Debug.assertEqual(arrayA.length, arrayB.length);
210         for (var i = 0; i < arrayA.length; i++) {
211             result.push(callback(arrayA[i], arrayB[i], i));
212         }
213         return result;
214     }
215     ts.zipWith = zipWith;
216     function zipToIterator(arrayA, arrayB) {
217         ts.Debug.assertEqual(arrayA.length, arrayB.length);
218         var i = 0;
219         return {
220             next: function () {
221                 if (i === arrayA.length) {
222                     return { value: undefined, done: true };
223                 }
224                 i++;
225                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
226             }
227         };
228     }
229     ts.zipToIterator = zipToIterator;
230     function zipToMap(keys, values) {
231         ts.Debug.assert(keys.length === values.length);
232         var map = createMap();
233         for (var i = 0; i < keys.length; ++i) {
234             map.set(keys[i], values[i]);
235         }
236         return map;
237     }
238     ts.zipToMap = zipToMap;
239     /**
240      * Iterates through `array` by index and performs the callback on each element of array until the callback
241      * returns a falsey value, then returns false.
242      * If no such value is found, the callback is applied to each element of array and `true` is returned.
243      */
244     function every(array, callback) {
245         if (array) {
246             for (var i = 0; i < array.length; i++) {
247                 if (!callback(array[i], i)) {
248                     return false;
249                 }
250             }
251         }
252         return true;
253     }
254     ts.every = every;
255     function find(array, predicate) {
256         for (var i = 0; i < array.length; i++) {
257             var value = array[i];
258             if (predicate(value, i)) {
259                 return value;
260             }
261         }
262         return undefined;
263     }
264     ts.find = find;
265     function findLast(array, predicate) {
266         for (var i = array.length - 1; i >= 0; i--) {
267             var value = array[i];
268             if (predicate(value, i)) {
269                 return value;
270             }
271         }
272         return undefined;
273     }
274     ts.findLast = findLast;
275     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
276     function findIndex(array, predicate, startIndex) {
277         for (var i = startIndex || 0; i < array.length; i++) {
278             if (predicate(array[i], i)) {
279                 return i;
280             }
281         }
282         return -1;
283     }
284     ts.findIndex = findIndex;
285     function findLastIndex(array, predicate, startIndex) {
286         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
287             if (predicate(array[i], i)) {
288                 return i;
289             }
290         }
291         return -1;
292     }
293     ts.findLastIndex = findLastIndex;
294     /**
295      * Returns the first truthy result of `callback`, or else fails.
296      * This is like `forEach`, but never returns undefined.
297      */
298     function findMap(array, callback) {
299         for (var i = 0; i < array.length; i++) {
300             var result = callback(array[i], i);
301             if (result) {
302                 return result;
303             }
304         }
305         return ts.Debug.fail();
306     }
307     ts.findMap = findMap;
308     function contains(array, value, equalityComparer) {
309         if (equalityComparer === void 0) { equalityComparer = equateValues; }
310         if (array) {
311             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
312                 var v = array_1[_i];
313                 if (equalityComparer(v, value)) {
314                     return true;
315                 }
316             }
317         }
318         return false;
319     }
320     ts.contains = contains;
321     function arraysEqual(a, b, equalityComparer) {
322         if (equalityComparer === void 0) { equalityComparer = equateValues; }
323         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
324     }
325     ts.arraysEqual = arraysEqual;
326     function indexOfAnyCharCode(text, charCodes, start) {
327         for (var i = start || 0; i < text.length; i++) {
328             if (contains(charCodes, text.charCodeAt(i))) {
329                 return i;
330             }
331         }
332         return -1;
333     }
334     ts.indexOfAnyCharCode = indexOfAnyCharCode;
335     function countWhere(array, predicate) {
336         var count = 0;
337         if (array) {
338             for (var i = 0; i < array.length; i++) {
339                 var v = array[i];
340                 if (predicate(v, i)) {
341                     count++;
342                 }
343             }
344         }
345         return count;
346     }
347     ts.countWhere = countWhere;
348     function filter(array, f) {
349         if (array) {
350             var len = array.length;
351             var i = 0;
352             while (i < len && f(array[i]))
353                 i++;
354             if (i < len) {
355                 var result = array.slice(0, i);
356                 i++;
357                 while (i < len) {
358                     var item = array[i];
359                     if (f(item)) {
360                         result.push(item);
361                     }
362                     i++;
363                 }
364                 return result;
365             }
366         }
367         return array;
368     }
369     ts.filter = filter;
370     function filterMutate(array, f) {
371         var outIndex = 0;
372         for (var i = 0; i < array.length; i++) {
373             if (f(array[i], i, array)) {
374                 array[outIndex] = array[i];
375                 outIndex++;
376             }
377         }
378         array.length = outIndex;
379     }
380     ts.filterMutate = filterMutate;
381     function clear(array) {
382         array.length = 0;
383     }
384     ts.clear = clear;
385     function map(array, f) {
386         var result;
387         if (array) {
388             result = [];
389             for (var i = 0; i < array.length; i++) {
390                 result.push(f(array[i], i));
391             }
392         }
393         return result;
394     }
395     ts.map = map;
396     function mapIterator(iter, mapFn) {
397         return {
398             next: function () {
399                 var iterRes = iter.next();
400                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
401             }
402         };
403     }
404     ts.mapIterator = mapIterator;
405     function sameMap(array, f) {
406         if (array) {
407             for (var i = 0; i < array.length; i++) {
408                 var item = array[i];
409                 var mapped = f(item, i);
410                 if (item !== mapped) {
411                     var result = array.slice(0, i);
412                     result.push(mapped);
413                     for (i++; i < array.length; i++) {
414                         result.push(f(array[i], i));
415                     }
416                     return result;
417                 }
418             }
419         }
420         return array;
421     }
422     ts.sameMap = sameMap;
423     /**
424      * Flattens an array containing a mix of array or non-array elements.
425      *
426      * @param array The array to flatten.
427      */
428     function flatten(array) {
429         var result = [];
430         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
431             var v = array_2[_i];
432             if (v) {
433                 if (isArray(v)) {
434                     addRange(result, v);
435                 }
436                 else {
437                     result.push(v);
438                 }
439             }
440         }
441         return result;
442     }
443     ts.flatten = flatten;
444     /**
445      * Maps an array. If the mapped value is an array, it is spread into the result.
446      *
447      * @param array The array to map.
448      * @param mapfn The callback used to map the result into one or more values.
449      */
450     function flatMap(array, mapfn) {
451         var result;
452         if (array) {
453             for (var i = 0; i < array.length; i++) {
454                 var v = mapfn(array[i], i);
455                 if (v) {
456                     if (isArray(v)) {
457                         result = addRange(result, v);
458                     }
459                     else {
460                         result = append(result, v);
461                     }
462                 }
463             }
464         }
465         return result || ts.emptyArray;
466     }
467     ts.flatMap = flatMap;
468     function flatMapToMutable(array, mapfn) {
469         var result = [];
470         if (array) {
471             for (var i = 0; i < array.length; i++) {
472                 var v = mapfn(array[i], i);
473                 if (v) {
474                     if (isArray(v)) {
475                         addRange(result, v);
476                     }
477                     else {
478                         result.push(v);
479                     }
480                 }
481             }
482         }
483         return result;
484     }
485     ts.flatMapToMutable = flatMapToMutable;
486     function flatMapIterator(iter, mapfn) {
487         var first = iter.next();
488         if (first.done) {
489             return ts.emptyIterator;
490         }
491         var currentIter = getIterator(first.value);
492         return {
493             next: function () {
494                 while (true) {
495                     var currentRes = currentIter.next();
496                     if (!currentRes.done) {
497                         return currentRes;
498                     }
499                     var iterRes = iter.next();
500                     if (iterRes.done) {
501                         return iterRes;
502                     }
503                     currentIter = getIterator(iterRes.value);
504                 }
505             },
506         };
507         function getIterator(x) {
508             var res = mapfn(x);
509             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
510         }
511     }
512     ts.flatMapIterator = flatMapIterator;
513     function sameFlatMap(array, mapfn) {
514         var result;
515         if (array) {
516             for (var i = 0; i < array.length; i++) {
517                 var item = array[i];
518                 var mapped = mapfn(item, i);
519                 if (result || item !== mapped || isArray(mapped)) {
520                     if (!result) {
521                         result = array.slice(0, i);
522                     }
523                     if (isArray(mapped)) {
524                         addRange(result, mapped);
525                     }
526                     else {
527                         result.push(mapped);
528                     }
529                 }
530             }
531         }
532         return result || array;
533     }
534     ts.sameFlatMap = sameFlatMap;
535     function mapAllOrFail(array, mapFn) {
536         var result = [];
537         for (var i = 0; i < array.length; i++) {
538             var mapped = mapFn(array[i], i);
539             if (mapped === undefined) {
540                 return undefined;
541             }
542             result.push(mapped);
543         }
544         return result;
545     }
546     ts.mapAllOrFail = mapAllOrFail;
547     function mapDefined(array, mapFn) {
548         var result = [];
549         if (array) {
550             for (var i = 0; i < array.length; i++) {
551                 var mapped = mapFn(array[i], i);
552                 if (mapped !== undefined) {
553                     result.push(mapped);
554                 }
555             }
556         }
557         return result;
558     }
559     ts.mapDefined = mapDefined;
560     function mapDefinedIterator(iter, mapFn) {
561         return {
562             next: function () {
563                 while (true) {
564                     var res = iter.next();
565                     if (res.done) {
566                         return res;
567                     }
568                     var value = mapFn(res.value);
569                     if (value !== undefined) {
570                         return { value: value, done: false };
571                     }
572                 }
573             }
574         };
575     }
576     ts.mapDefinedIterator = mapDefinedIterator;
577     function mapDefinedMap(map, mapValue, mapKey) {
578         if (mapKey === void 0) { mapKey = identity; }
579         var result = createMap();
580         map.forEach(function (value, key) {
581             var mapped = mapValue(value, key);
582             if (mapped !== undefined) {
583                 result.set(mapKey(key), mapped);
584             }
585         });
586         return result;
587     }
588     ts.mapDefinedMap = mapDefinedMap;
589     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
590     function singleIterator(value) {
591         var done = false;
592         return {
593             next: function () {
594                 var wasDone = done;
595                 done = true;
596                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
597             }
598         };
599     }
600     ts.singleIterator = singleIterator;
601     function spanMap(array, keyfn, mapfn) {
602         var result;
603         if (array) {
604             result = [];
605             var len = array.length;
606             var previousKey = void 0;
607             var key = void 0;
608             var start = 0;
609             var pos = 0;
610             while (start < len) {
611                 while (pos < len) {
612                     var value = array[pos];
613                     key = keyfn(value, pos);
614                     if (pos === 0) {
615                         previousKey = key;
616                     }
617                     else if (key !== previousKey) {
618                         break;
619                     }
620                     pos++;
621                 }
622                 if (start < pos) {
623                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
624                     if (v) {
625                         result.push(v);
626                     }
627                     start = pos;
628                 }
629                 previousKey = key;
630                 pos++;
631             }
632         }
633         return result;
634     }
635     ts.spanMap = spanMap;
636     function mapEntries(map, f) {
637         if (!map) {
638             return undefined;
639         }
640         var result = createMap();
641         map.forEach(function (value, key) {
642             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
643             result.set(newKey, newValue);
644         });
645         return result;
646     }
647     ts.mapEntries = mapEntries;
648     function some(array, predicate) {
649         if (array) {
650             if (predicate) {
651                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
652                     var v = array_3[_i];
653                     if (predicate(v)) {
654                         return true;
655                     }
656                 }
657             }
658             else {
659                 return array.length > 0;
660             }
661         }
662         return false;
663     }
664     ts.some = some;
665     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
666     function getRangesWhere(arr, pred, cb) {
667         var start;
668         for (var i = 0; i < arr.length; i++) {
669             if (pred(arr[i])) {
670                 start = start === undefined ? i : start;
671             }
672             else {
673                 if (start !== undefined) {
674                     cb(start, i);
675                     start = undefined;
676                 }
677             }
678         }
679         if (start !== undefined)
680             cb(start, arr.length);
681     }
682     ts.getRangesWhere = getRangesWhere;
683     function concatenate(array1, array2) {
684         if (!some(array2))
685             return array1;
686         if (!some(array1))
687             return array2;
688         return __spreadArrays(array1, array2);
689     }
690     ts.concatenate = concatenate;
691     function selectIndex(_, i) {
692         return i;
693     }
694     function indicesOf(array) {
695         return array.map(selectIndex);
696     }
697     ts.indicesOf = indicesOf;
698     function deduplicateRelational(array, equalityComparer, comparer) {
699         // Perform a stable sort of the array. This ensures the first entry in a list of
700         // duplicates remains the first entry in the result.
701         var indices = indicesOf(array);
702         stableSortIndices(array, indices, comparer);
703         var last = array[indices[0]];
704         var deduplicated = [indices[0]];
705         for (var i = 1; i < indices.length; i++) {
706             var index = indices[i];
707             var item = array[index];
708             if (!equalityComparer(last, item)) {
709                 deduplicated.push(index);
710                 last = item;
711             }
712         }
713         // restore original order
714         deduplicated.sort();
715         return deduplicated.map(function (i) { return array[i]; });
716     }
717     function deduplicateEquality(array, equalityComparer) {
718         var result = [];
719         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
720             var item = array_4[_i];
721             pushIfUnique(result, item, equalityComparer);
722         }
723         return result;
724     }
725     /**
726      * Deduplicates an unsorted array.
727      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
728      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
729      * result will remain in the original order in `array`.
730      */
731     function deduplicate(array, equalityComparer, comparer) {
732         return array.length === 0 ? [] :
733             array.length === 1 ? array.slice() :
734                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
735                     deduplicateEquality(array, equalityComparer);
736     }
737     ts.deduplicate = deduplicate;
738     /**
739      * Deduplicates an array that has already been sorted.
740      */
741     function deduplicateSorted(array, comparer) {
742         if (array.length === 0)
743             return ts.emptyArray;
744         var last = array[0];
745         var deduplicated = [last];
746         for (var i = 1; i < array.length; i++) {
747             var next = array[i];
748             switch (comparer(next, last)) {
749                 // equality comparison
750                 case true:
751                 // relational comparison
752                 // falls through
753                 case 0 /* EqualTo */:
754                     continue;
755                 case -1 /* LessThan */:
756                     // If `array` is sorted, `next` should **never** be less than `last`.
757                     return ts.Debug.fail("Array is unsorted.");
758             }
759             deduplicated.push(last = next);
760         }
761         return deduplicated;
762     }
763     function insertSorted(array, insert, compare) {
764         if (array.length === 0) {
765             array.push(insert);
766             return;
767         }
768         var insertIndex = binarySearch(array, insert, identity, compare);
769         if (insertIndex < 0) {
770             array.splice(~insertIndex, 0, insert);
771         }
772     }
773     ts.insertSorted = insertSorted;
774     function sortAndDeduplicate(array, comparer, equalityComparer) {
775         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
776     }
777     ts.sortAndDeduplicate = sortAndDeduplicate;
778     function arrayIsEqualTo(array1, array2, equalityComparer) {
779         if (equalityComparer === void 0) { equalityComparer = equateValues; }
780         if (!array1 || !array2) {
781             return array1 === array2;
782         }
783         if (array1.length !== array2.length) {
784             return false;
785         }
786         for (var i = 0; i < array1.length; i++) {
787             if (!equalityComparer(array1[i], array2[i], i)) {
788                 return false;
789             }
790         }
791         return true;
792     }
793     ts.arrayIsEqualTo = arrayIsEqualTo;
794     function compact(array) {
795         var result;
796         if (array) {
797             for (var i = 0; i < array.length; i++) {
798                 var v = array[i];
799                 if (result || !v) {
800                     if (!result) {
801                         result = array.slice(0, i);
802                     }
803                     if (v) {
804                         result.push(v);
805                     }
806                 }
807             }
808         }
809         return result || array;
810     }
811     ts.compact = compact;
812     /**
813      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
814      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
815      * based on the provided comparer.
816      */
817     function relativeComplement(arrayA, arrayB, comparer) {
818         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
819             return arrayB;
820         var result = [];
821         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
822             if (offsetB > 0) {
823                 // Ensure `arrayB` is properly sorted.
824                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
825             }
826             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
827                 if (offsetA > startA) {
828                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
829                     // `offsetA` has changed since we entered the loop.
830                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
831                 }
832                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
833                     case -1 /* LessThan */:
834                         // If B is less than A, B does not exist in arrayA. Add B to the result and
835                         // move to the next element in arrayB without changing the current position
836                         // in arrayA.
837                         result.push(arrayB[offsetB]);
838                         continue loopB;
839                     case 0 /* EqualTo */:
840                         // If B is equal to A, B exists in arrayA. Move to the next element in
841                         // arrayB without adding B to the result or changing the current position
842                         // in arrayA.
843                         continue loopB;
844                     case 1 /* GreaterThan */:
845                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
846                         // the next element in arrayA and recheck.
847                         continue loopA;
848                 }
849             }
850         }
851         return result;
852     }
853     ts.relativeComplement = relativeComplement;
854     function sum(array, prop) {
855         var result = 0;
856         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
857             var v = array_5[_i];
858             result += v[prop];
859         }
860         return result;
861     }
862     ts.sum = sum;
863     function append(to, value) {
864         if (value === undefined)
865             return to;
866         if (to === undefined)
867             return [value];
868         to.push(value);
869         return to;
870     }
871     ts.append = append;
872     function combine(xs, ys) {
873         if (xs === undefined)
874             return ys;
875         if (ys === undefined)
876             return xs;
877         if (isArray(xs))
878             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
879         if (isArray(ys))
880             return append(ys, xs);
881         return [xs, ys];
882     }
883     ts.combine = combine;
884     /**
885      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
886      * position offset from the end of the array.
887      */
888     function toOffset(array, offset) {
889         return offset < 0 ? array.length + offset : offset;
890     }
891     function addRange(to, from, start, end) {
892         if (from === undefined || from.length === 0)
893             return to;
894         if (to === undefined)
895             return from.slice(start, end);
896         start = start === undefined ? 0 : toOffset(from, start);
897         end = end === undefined ? from.length : toOffset(from, end);
898         for (var i = start; i < end && i < from.length; i++) {
899             if (from[i] !== undefined) {
900                 to.push(from[i]);
901             }
902         }
903         return to;
904     }
905     ts.addRange = addRange;
906     /**
907      * @return Whether the value was added.
908      */
909     function pushIfUnique(array, toAdd, equalityComparer) {
910         if (contains(array, toAdd, equalityComparer)) {
911             return false;
912         }
913         else {
914             array.push(toAdd);
915             return true;
916         }
917     }
918     ts.pushIfUnique = pushIfUnique;
919     /**
920      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
921      */
922     function appendIfUnique(array, toAdd, equalityComparer) {
923         if (array) {
924             pushIfUnique(array, toAdd, equalityComparer);
925             return array;
926         }
927         else {
928             return [toAdd];
929         }
930     }
931     ts.appendIfUnique = appendIfUnique;
932     function stableSortIndices(array, indices, comparer) {
933         // sort indices by value then position
934         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
935     }
936     /**
937      * Returns a new sorted array.
938      */
939     function sort(array, comparer) {
940         return (array.length === 0 ? array : array.slice().sort(comparer));
941     }
942     ts.sort = sort;
943     function arrayIterator(array) {
944         var i = 0;
945         return { next: function () {
946                 if (i === array.length) {
947                     return { value: undefined, done: true };
948                 }
949                 else {
950                     i++;
951                     return { value: array[i - 1], done: false };
952                 }
953             } };
954     }
955     ts.arrayIterator = arrayIterator;
956     function arrayReverseIterator(array) {
957         var i = array.length;
958         return {
959             next: function () {
960                 if (i === 0) {
961                     return { value: undefined, done: true };
962                 }
963                 else {
964                     i--;
965                     return { value: array[i], done: false };
966                 }
967             }
968         };
969     }
970     ts.arrayReverseIterator = arrayReverseIterator;
971     /**
972      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
973      */
974     function stableSort(array, comparer) {
975         var indices = indicesOf(array);
976         stableSortIndices(array, indices, comparer);
977         return indices.map(function (i) { return array[i]; });
978     }
979     ts.stableSort = stableSort;
980     function rangeEquals(array1, array2, pos, end) {
981         while (pos < end) {
982             if (array1[pos] !== array2[pos]) {
983                 return false;
984             }
985             pos++;
986         }
987         return true;
988     }
989     ts.rangeEquals = rangeEquals;
990     /**
991      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
992      * A negative offset indicates the element should be retrieved from the end of the array.
993      */
994     function elementAt(array, offset) {
995         if (array) {
996             offset = toOffset(array, offset);
997             if (offset < array.length) {
998                 return array[offset];
999             }
1000         }
1001         return undefined;
1002     }
1003     ts.elementAt = elementAt;
1004     /**
1005      * Returns the first element of an array if non-empty, `undefined` otherwise.
1006      */
1007     function firstOrUndefined(array) {
1008         return array.length === 0 ? undefined : array[0];
1009     }
1010     ts.firstOrUndefined = firstOrUndefined;
1011     function first(array) {
1012         ts.Debug.assert(array.length !== 0);
1013         return array[0];
1014     }
1015     ts.first = first;
1016     /**
1017      * Returns the last element of an array if non-empty, `undefined` otherwise.
1018      */
1019     function lastOrUndefined(array) {
1020         return array.length === 0 ? undefined : array[array.length - 1];
1021     }
1022     ts.lastOrUndefined = lastOrUndefined;
1023     function last(array) {
1024         ts.Debug.assert(array.length !== 0);
1025         return array[array.length - 1];
1026     }
1027     ts.last = last;
1028     /**
1029      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1030      */
1031     function singleOrUndefined(array) {
1032         return array && array.length === 1
1033             ? array[0]
1034             : undefined;
1035     }
1036     ts.singleOrUndefined = singleOrUndefined;
1037     function singleOrMany(array) {
1038         return array && array.length === 1
1039             ? array[0]
1040             : array;
1041     }
1042     ts.singleOrMany = singleOrMany;
1043     function replaceElement(array, index, value) {
1044         var result = array.slice(0);
1045         result[index] = value;
1046         return result;
1047     }
1048     ts.replaceElement = replaceElement;
1049     /**
1050      * Performs a binary search, finding the index at which `value` occurs in `array`.
1051      * If no such index is found, returns the 2's-complement of first index at which
1052      * `array[index]` exceeds `value`.
1053      * @param array A sorted array whose first element must be no larger than number
1054      * @param value The value to be searched for in the array.
1055      * @param keySelector A callback used to select the search key from `value` and each element of
1056      * `array`.
1057      * @param keyComparer A callback used to compare two keys in a sorted array.
1058      * @param offset An offset into `array` at which to start the search.
1059      */
1060     function binarySearch(array, value, keySelector, keyComparer, offset) {
1061         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1062     }
1063     ts.binarySearch = binarySearch;
1064     /**
1065      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1066      * If no such index is found, returns the 2's-complement of first index at which
1067      * `array[index]` exceeds `key`.
1068      * @param array A sorted array whose first element must be no larger than number
1069      * @param key The key to be searched for in the array.
1070      * @param keySelector A callback used to select the search key from each element of `array`.
1071      * @param keyComparer A callback used to compare two keys in a sorted array.
1072      * @param offset An offset into `array` at which to start the search.
1073      */
1074     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1075         if (!some(array)) {
1076             return -1;
1077         }
1078         var low = offset || 0;
1079         var high = array.length - 1;
1080         while (low <= high) {
1081             var middle = low + ((high - low) >> 1);
1082             var midKey = keySelector(array[middle]);
1083             switch (keyComparer(midKey, key)) {
1084                 case -1 /* LessThan */:
1085                     low = middle + 1;
1086                     break;
1087                 case 0 /* EqualTo */:
1088                     return middle;
1089                 case 1 /* GreaterThan */:
1090                     high = middle - 1;
1091                     break;
1092             }
1093         }
1094         return ~low;
1095     }
1096     ts.binarySearchKey = binarySearchKey;
1097     function reduceLeft(array, f, initial, start, count) {
1098         if (array && array.length > 0) {
1099             var size = array.length;
1100             if (size > 0) {
1101                 var pos = start === undefined || start < 0 ? 0 : start;
1102                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1103                 var result = void 0;
1104                 if (arguments.length <= 2) {
1105                     result = array[pos];
1106                     pos++;
1107                 }
1108                 else {
1109                     result = initial;
1110                 }
1111                 while (pos <= end) {
1112                     result = f(result, array[pos], pos);
1113                     pos++;
1114                 }
1115                 return result;
1116             }
1117         }
1118         return initial;
1119     }
1120     ts.reduceLeft = reduceLeft;
1121     var hasOwnProperty = Object.prototype.hasOwnProperty;
1122     /**
1123      * Indicates whether a map-like contains an own property with the specified key.
1124      *
1125      * @param map A map-like.
1126      * @param key A property key.
1127      */
1128     function hasProperty(map, key) {
1129         return hasOwnProperty.call(map, key);
1130     }
1131     ts.hasProperty = hasProperty;
1132     /**
1133      * Gets the value of an owned property in a map-like.
1134      *
1135      * @param map A map-like.
1136      * @param key A property key.
1137      */
1138     function getProperty(map, key) {
1139         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1140     }
1141     ts.getProperty = getProperty;
1142     /**
1143      * Gets the owned, enumerable property keys of a map-like.
1144      */
1145     function getOwnKeys(map) {
1146         var keys = [];
1147         for (var key in map) {
1148             if (hasOwnProperty.call(map, key)) {
1149                 keys.push(key);
1150             }
1151         }
1152         return keys;
1153     }
1154     ts.getOwnKeys = getOwnKeys;
1155     function getAllKeys(obj) {
1156         var result = [];
1157         do {
1158             var names = Object.getOwnPropertyNames(obj);
1159             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1160                 var name = names_1[_i];
1161                 pushIfUnique(result, name);
1162             }
1163         } while (obj = Object.getPrototypeOf(obj));
1164         return result;
1165     }
1166     ts.getAllKeys = getAllKeys;
1167     function getOwnValues(sparseArray) {
1168         var values = [];
1169         for (var key in sparseArray) {
1170             if (hasOwnProperty.call(sparseArray, key)) {
1171                 values.push(sparseArray[key]);
1172             }
1173         }
1174         return values;
1175     }
1176     ts.getOwnValues = getOwnValues;
1177     function arrayFrom(iterator, map) {
1178         var result = [];
1179         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1180             result.push(map ? map(iterResult.value) : iterResult.value);
1181         }
1182         return result;
1183     }
1184     ts.arrayFrom = arrayFrom;
1185     function assign(t) {
1186         var args = [];
1187         for (var _i = 1; _i < arguments.length; _i++) {
1188             args[_i - 1] = arguments[_i];
1189         }
1190         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1191             var arg = args_1[_a];
1192             if (arg === undefined)
1193                 continue;
1194             for (var p in arg) {
1195                 if (hasProperty(arg, p)) {
1196                     t[p] = arg[p];
1197                 }
1198             }
1199         }
1200         return t;
1201     }
1202     ts.assign = assign;
1203     /**
1204      * Performs a shallow equality comparison of the contents of two map-likes.
1205      *
1206      * @param left A map-like whose properties should be compared.
1207      * @param right A map-like whose properties should be compared.
1208      */
1209     function equalOwnProperties(left, right, equalityComparer) {
1210         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1211         if (left === right)
1212             return true;
1213         if (!left || !right)
1214             return false;
1215         for (var key in left) {
1216             if (hasOwnProperty.call(left, key)) {
1217                 if (!hasOwnProperty.call(right, key))
1218                     return false;
1219                 if (!equalityComparer(left[key], right[key]))
1220                     return false;
1221             }
1222         }
1223         for (var key in right) {
1224             if (hasOwnProperty.call(right, key)) {
1225                 if (!hasOwnProperty.call(left, key))
1226                     return false;
1227             }
1228         }
1229         return true;
1230     }
1231     ts.equalOwnProperties = equalOwnProperties;
1232     function arrayToMap(array, makeKey, makeValue) {
1233         if (makeValue === void 0) { makeValue = identity; }
1234         var result = createMap();
1235         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1236             var value = array_6[_i];
1237             var key = makeKey(value);
1238             if (key !== undefined)
1239                 result.set(key, makeValue(value));
1240         }
1241         return result;
1242     }
1243     ts.arrayToMap = arrayToMap;
1244     function arrayToNumericMap(array, makeKey, makeValue) {
1245         if (makeValue === void 0) { makeValue = identity; }
1246         var result = [];
1247         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1248             var value = array_7[_i];
1249             result[makeKey(value)] = makeValue(value);
1250         }
1251         return result;
1252     }
1253     ts.arrayToNumericMap = arrayToNumericMap;
1254     function arrayToMultiMap(values, makeKey, makeValue) {
1255         if (makeValue === void 0) { makeValue = identity; }
1256         var result = createMultiMap();
1257         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1258             var value = values_1[_i];
1259             result.add(makeKey(value), makeValue(value));
1260         }
1261         return result;
1262     }
1263     ts.arrayToMultiMap = arrayToMultiMap;
1264     function group(values, getGroupId, resultSelector) {
1265         if (resultSelector === void 0) { resultSelector = identity; }
1266         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1267     }
1268     ts.group = group;
1269     function clone(object) {
1270         var result = {};
1271         for (var id in object) {
1272             if (hasOwnProperty.call(object, id)) {
1273                 result[id] = object[id];
1274             }
1275         }
1276         return result;
1277     }
1278     ts.clone = clone;
1279     /**
1280      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1281      *
1282      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1283      */
1284     function extend(first, second) {
1285         var result = {};
1286         for (var id in second) {
1287             if (hasOwnProperty.call(second, id)) {
1288                 result[id] = second[id];
1289             }
1290         }
1291         for (var id in first) {
1292             if (hasOwnProperty.call(first, id)) {
1293                 result[id] = first[id];
1294             }
1295         }
1296         return result;
1297     }
1298     ts.extend = extend;
1299     function copyProperties(first, second) {
1300         for (var id in second) {
1301             if (hasOwnProperty.call(second, id)) {
1302                 first[id] = second[id];
1303             }
1304         }
1305     }
1306     ts.copyProperties = copyProperties;
1307     function maybeBind(obj, fn) {
1308         return fn ? fn.bind(obj) : undefined;
1309     }
1310     ts.maybeBind = maybeBind;
1311     function mapMap(map, f) {
1312         var result = createMap();
1313         map.forEach(function (t, key) { return result.set.apply(result, (f(t, key))); });
1314         return result;
1315     }
1316     ts.mapMap = mapMap;
1317     function createMultiMap() {
1318         var map = createMap();
1319         map.add = multiMapAdd;
1320         map.remove = multiMapRemove;
1321         return map;
1322     }
1323     ts.createMultiMap = createMultiMap;
1324     function multiMapAdd(key, value) {
1325         var values = this.get(key);
1326         if (values) {
1327             values.push(value);
1328         }
1329         else {
1330             this.set(key, values = [value]);
1331         }
1332         return values;
1333     }
1334     function multiMapRemove(key, value) {
1335         var values = this.get(key);
1336         if (values) {
1337             unorderedRemoveItem(values, value);
1338             if (!values.length) {
1339                 this.delete(key);
1340             }
1341         }
1342     }
1343     function createUnderscoreEscapedMultiMap() {
1344         return createMultiMap();
1345     }
1346     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1347     /**
1348      * Tests whether a value is an array.
1349      */
1350     function isArray(value) {
1351         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1352     }
1353     ts.isArray = isArray;
1354     function toArray(value) {
1355         return isArray(value) ? value : [value];
1356     }
1357     ts.toArray = toArray;
1358     /**
1359      * Tests whether a value is string
1360      */
1361     function isString(text) {
1362         return typeof text === "string";
1363     }
1364     ts.isString = isString;
1365     function isNumber(x) {
1366         return typeof x === "number";
1367     }
1368     ts.isNumber = isNumber;
1369     function tryCast(value, test) {
1370         return value !== undefined && test(value) ? value : undefined;
1371     }
1372     ts.tryCast = tryCast;
1373     function cast(value, test) {
1374         if (value !== undefined && test(value))
1375             return value;
1376         return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1377     }
1378     ts.cast = cast;
1379     /** Does nothing. */
1380     function noop(_) { }
1381     ts.noop = noop;
1382     /** Do nothing and return false */
1383     function returnFalse() { return false; }
1384     ts.returnFalse = returnFalse;
1385     /** Do nothing and return true */
1386     function returnTrue() { return true; }
1387     ts.returnTrue = returnTrue;
1388     /** Do nothing and return undefined */
1389     function returnUndefined() { return undefined; }
1390     ts.returnUndefined = returnUndefined;
1391     /** Returns its argument. */
1392     function identity(x) { return x; }
1393     ts.identity = identity;
1394     /** Returns lower case string */
1395     function toLowerCase(x) { return x.toLowerCase(); }
1396     ts.toLowerCase = toLowerCase;
1397     // We convert the file names to lower case as key for file name on case insensitive file system
1398     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1399     // it to lower case, fileName with its lowercase form can exist along side it.
1400     // Handle special characters and make those case sensitive instead
1401     //
1402     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1403     // | 1. | i        | 105       | Ascii i                                                                |
1404     // | 2. | I        | 73        | Ascii I                                                                |
1405     // |-------- Special characters ------------------------------------------------------------------------|
1406     // | 3. | \u0130   | 304       | Uppper case I with dot above                                           |
1407     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1408     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1409     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1410     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1411     //
1412     // Because item 3 is special where in its lowercase character has its own
1413     // upper case form we cant convert its case.
1414     // Rest special characters are either already in lower case format or
1415     // they have corresponding upper case character so they dont need special handling
1416     //
1417     // But to avoid having to do string building for most common cases, also ignore
1418     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1419     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1420     /**
1421      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1422      * This function is used in places where we want to make file name as a key on these systems
1423      * 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
1424      * 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
1425      * Technically we would want this function to be platform sepcific as well but
1426      * 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
1427      * We could use upper case and we would still need to deal with the descripencies but
1428      * 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
1429      * 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
1430      */
1431     function toFileNameLowerCase(x) {
1432         return fileNameLowerCaseRegExp.test(x) ?
1433             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1434             x;
1435     }
1436     ts.toFileNameLowerCase = toFileNameLowerCase;
1437     /** Throws an error because a function is not implemented. */
1438     function notImplemented() {
1439         throw new Error("Not implemented");
1440     }
1441     ts.notImplemented = notImplemented;
1442     function memoize(callback) {
1443         var value;
1444         return function () {
1445             if (callback) {
1446                 value = callback();
1447                 callback = undefined;
1448             }
1449             return value;
1450         };
1451     }
1452     ts.memoize = memoize;
1453     function compose(a, b, c, d, e) {
1454         if (!!e) {
1455             var args_2 = [];
1456             for (var i = 0; i < arguments.length; i++) {
1457                 args_2[i] = arguments[i];
1458             }
1459             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1460         }
1461         else if (d) {
1462             return function (t) { return d(c(b(a(t)))); };
1463         }
1464         else if (c) {
1465             return function (t) { return c(b(a(t))); };
1466         }
1467         else if (b) {
1468             return function (t) { return b(a(t)); };
1469         }
1470         else if (a) {
1471             return function (t) { return a(t); };
1472         }
1473         else {
1474             return function (t) { return t; };
1475         }
1476     }
1477     ts.compose = compose;
1478     var AssertionLevel;
1479     (function (AssertionLevel) {
1480         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1481         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1482         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1483         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1484     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1485     function equateValues(a, b) {
1486         return a === b;
1487     }
1488     ts.equateValues = equateValues;
1489     /**
1490      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1491      *
1492      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1493      * value of each code-point after applying `toUpperCase` to each string. We always map both
1494      * strings to their upper-case form as some unicode characters do not properly round-trip to
1495      * lowercase (such as `ẞ` (German sharp capital s)).
1496      */
1497     function equateStringsCaseInsensitive(a, b) {
1498         return a === b
1499             || a !== undefined
1500                 && b !== undefined
1501                 && a.toUpperCase() === b.toUpperCase();
1502     }
1503     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1504     /**
1505      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1506      *
1507      * Case-sensitive comparisons compare both strings one code-point at a time using the
1508      * integer value of each code-point.
1509      */
1510     function equateStringsCaseSensitive(a, b) {
1511         return equateValues(a, b);
1512     }
1513     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1514     function compareComparableValues(a, b) {
1515         return a === b ? 0 /* EqualTo */ :
1516             a === undefined ? -1 /* LessThan */ :
1517                 b === undefined ? 1 /* GreaterThan */ :
1518                     a < b ? -1 /* LessThan */ :
1519                         1 /* GreaterThan */;
1520     }
1521     /**
1522      * Compare two numeric values for their order relative to each other.
1523      * To compare strings, use any of the `compareStrings` functions.
1524      */
1525     function compareValues(a, b) {
1526         return compareComparableValues(a, b);
1527     }
1528     ts.compareValues = compareValues;
1529     /**
1530      * Compare two TextSpans, first by `start`, then by `length`.
1531      */
1532     function compareTextSpans(a, b) {
1533         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);
1534     }
1535     ts.compareTextSpans = compareTextSpans;
1536     function min(a, b, compare) {
1537         return compare(a, b) === -1 /* LessThan */ ? a : b;
1538     }
1539     ts.min = min;
1540     /**
1541      * Compare two strings using a case-insensitive ordinal comparison.
1542      *
1543      * Ordinal comparisons are based on the difference between the unicode code points of both
1544      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1545      * comparisons provide predictable ordering, but place "a" after "B".
1546      *
1547      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1548      * value of each code-point after applying `toUpperCase` to each string. We always map both
1549      * strings to their upper-case form as some unicode characters do not properly round-trip to
1550      * lowercase (such as `ẞ` (German sharp capital s)).
1551      */
1552     function compareStringsCaseInsensitive(a, b) {
1553         if (a === b)
1554             return 0 /* EqualTo */;
1555         if (a === undefined)
1556             return -1 /* LessThan */;
1557         if (b === undefined)
1558             return 1 /* GreaterThan */;
1559         a = a.toUpperCase();
1560         b = b.toUpperCase();
1561         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1562     }
1563     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1564     /**
1565      * Compare two strings using a case-sensitive ordinal comparison.
1566      *
1567      * Ordinal comparisons are based on the difference between the unicode code points of both
1568      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1569      * comparisons provide predictable ordering, but place "a" after "B".
1570      *
1571      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1572      * value of each code-point.
1573      */
1574     function compareStringsCaseSensitive(a, b) {
1575         return compareComparableValues(a, b);
1576     }
1577     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1578     function getStringComparer(ignoreCase) {
1579         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1580     }
1581     ts.getStringComparer = getStringComparer;
1582     /**
1583      * Creates a string comparer for use with string collation in the UI.
1584      */
1585     var createUIStringComparer = (function () {
1586         var defaultComparer;
1587         var enUSComparer;
1588         var stringComparerFactory = getStringComparerFactory();
1589         return createStringComparer;
1590         function compareWithCallback(a, b, comparer) {
1591             if (a === b)
1592                 return 0 /* EqualTo */;
1593             if (a === undefined)
1594                 return -1 /* LessThan */;
1595             if (b === undefined)
1596                 return 1 /* GreaterThan */;
1597             var value = comparer(a, b);
1598             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1599         }
1600         function createIntlCollatorStringComparer(locale) {
1601             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1602             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1603             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1604             return function (a, b) { return compareWithCallback(a, b, comparer); };
1605         }
1606         function createLocaleCompareStringComparer(locale) {
1607             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1608             if (locale !== undefined)
1609                 return createFallbackStringComparer();
1610             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1611             function compareStrings(a, b) {
1612                 return a.localeCompare(b);
1613             }
1614         }
1615         function createFallbackStringComparer() {
1616             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1617             // We first sort case insensitively.  So "Aaa" will come before "baa".
1618             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1619             //
1620             // For case insensitive comparisons we always map both strings to their
1621             // upper-case form as some unicode characters do not properly round-trip to
1622             // lowercase (such as `ẞ` (German sharp capital s)).
1623             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1624             function compareDictionaryOrder(a, b) {
1625                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1626             }
1627             function compareStrings(a, b) {
1628                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1629             }
1630         }
1631         function getStringComparerFactory() {
1632             // If the host supports Intl, we use it for comparisons using the default locale.
1633             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1634                 return createIntlCollatorStringComparer;
1635             }
1636             // If the host does not support Intl, we fall back to localeCompare.
1637             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1638             if (typeof String.prototype.localeCompare === "function" &&
1639                 typeof String.prototype.toLocaleUpperCase === "function" &&
1640                 "a".localeCompare("B") < 0) {
1641                 return createLocaleCompareStringComparer;
1642             }
1643             // Otherwise, fall back to ordinal comparison:
1644             return createFallbackStringComparer;
1645         }
1646         function createStringComparer(locale) {
1647             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1648             // tests.
1649             if (locale === undefined) {
1650                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1651             }
1652             else if (locale === "en-US") {
1653                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1654             }
1655             else {
1656                 return stringComparerFactory(locale);
1657             }
1658         }
1659     })();
1660     var uiComparerCaseSensitive;
1661     var uiLocale;
1662     function getUILocale() {
1663         return uiLocale;
1664     }
1665     ts.getUILocale = getUILocale;
1666     function setUILocale(value) {
1667         if (uiLocale !== value) {
1668             uiLocale = value;
1669             uiComparerCaseSensitive = undefined;
1670         }
1671     }
1672     ts.setUILocale = setUILocale;
1673     /**
1674      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1675      *
1676      * Ordering is not predictable between different host locales, but is best for displaying
1677      * ordered data for UI presentation. Characters with multiple unicode representations may
1678      * be considered equal.
1679      *
1680      * Case-sensitive comparisons compare strings that differ in base characters, or
1681      * accents/diacritic marks, or case as unequal.
1682      */
1683     function compareStringsCaseSensitiveUI(a, b) {
1684         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1685         return comparer(a, b);
1686     }
1687     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1688     function compareProperties(a, b, key, comparer) {
1689         return a === b ? 0 /* EqualTo */ :
1690             a === undefined ? -1 /* LessThan */ :
1691                 b === undefined ? 1 /* GreaterThan */ :
1692                     comparer(a[key], b[key]);
1693     }
1694     ts.compareProperties = compareProperties;
1695     /** True is greater than false. */
1696     function compareBooleans(a, b) {
1697         return compareValues(a ? 1 : 0, b ? 1 : 0);
1698     }
1699     ts.compareBooleans = compareBooleans;
1700     /**
1701      * 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.
1702      * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1703      *
1704      * If there is a candidate that's the same except for case, return that.
1705      * If there is a candidate that's within one edit of the name, return that.
1706      * Otherwise, return the candidate with the smallest Levenshtein distance,
1707      *    except for candidates:
1708      *      * With no name
1709      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1710      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1711      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1712      *         and 1 insertion/deletion at 3 characters)
1713      */
1714     function getSpellingSuggestion(name, candidates, getName) {
1715         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1716         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1717         var bestCandidate;
1718         var justCheckExactMatches = false;
1719         var nameLowerCase = name.toLowerCase();
1720         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1721             var candidate = candidates_1[_i];
1722             var candidateName = getName(candidate);
1723             if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1724                 var candidateNameLowerCase = candidateName.toLowerCase();
1725                 if (candidateNameLowerCase === nameLowerCase) {
1726                     if (candidateName === name) {
1727                         continue;
1728                     }
1729                     return candidate;
1730                 }
1731                 if (justCheckExactMatches) {
1732                     continue;
1733                 }
1734                 if (candidateName.length < 3) {
1735                     // Don't bother, user would have noticed a 2-character name having an extra character
1736                     continue;
1737                 }
1738                 // Only care about a result better than the best so far.
1739                 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1740                 if (distance === undefined) {
1741                     continue;
1742                 }
1743                 if (distance < 3) {
1744                     justCheckExactMatches = true;
1745                     bestCandidate = candidate;
1746                 }
1747                 else {
1748                     ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1749                     bestDistance = distance;
1750                     bestCandidate = candidate;
1751                 }
1752             }
1753         }
1754         return bestCandidate;
1755     }
1756     ts.getSpellingSuggestion = getSpellingSuggestion;
1757     function levenshteinWithMax(s1, s2, max) {
1758         var previous = new Array(s2.length + 1);
1759         var current = new Array(s2.length + 1);
1760         /** Represents any value > max. We don't care about the particular value. */
1761         var big = max + 1;
1762         for (var i = 0; i <= s2.length; i++) {
1763             previous[i] = i;
1764         }
1765         for (var i = 1; i <= s1.length; i++) {
1766             var c1 = s1.charCodeAt(i - 1);
1767             var minJ = i > max ? i - max : 1;
1768             var maxJ = s2.length > max + i ? max + i : s2.length;
1769             current[0] = i;
1770             /** Smallest value of the matrix in the ith column. */
1771             var colMin = i;
1772             for (var j = 1; j < minJ; j++) {
1773                 current[j] = big;
1774             }
1775             for (var j = minJ; j <= maxJ; j++) {
1776                 var dist = c1 === s2.charCodeAt(j - 1)
1777                     ? previous[j - 1]
1778                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1779                 current[j] = dist;
1780                 colMin = Math.min(colMin, dist);
1781             }
1782             for (var j = maxJ + 1; j <= s2.length; j++) {
1783                 current[j] = big;
1784             }
1785             if (colMin > max) {
1786                 // Give up -- everything in this column is > max and it can't get better in future columns.
1787                 return undefined;
1788             }
1789             var temp = previous;
1790             previous = current;
1791             current = temp;
1792         }
1793         var res = previous[s2.length];
1794         return res > max ? undefined : res;
1795     }
1796     function endsWith(str, suffix) {
1797         var expectedPos = str.length - suffix.length;
1798         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1799     }
1800     ts.endsWith = endsWith;
1801     function removeSuffix(str, suffix) {
1802         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1803     }
1804     ts.removeSuffix = removeSuffix;
1805     function tryRemoveSuffix(str, suffix) {
1806         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1807     }
1808     ts.tryRemoveSuffix = tryRemoveSuffix;
1809     function stringContains(str, substring) {
1810         return str.indexOf(substring) !== -1;
1811     }
1812     ts.stringContains = stringContains;
1813     /**
1814      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1815      */
1816     function removeMinAndVersionNumbers(fileName) {
1817         // Match a "." or "-" followed by a version number or 'min' at the end of the name
1818         var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1819         // The "min" or version may both be present, in either order, so try applying the above twice.
1820         return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1821     }
1822     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1823     /** Remove an item from an array, moving everything to its right one space left. */
1824     function orderedRemoveItem(array, item) {
1825         for (var i = 0; i < array.length; i++) {
1826             if (array[i] === item) {
1827                 orderedRemoveItemAt(array, i);
1828                 return true;
1829             }
1830         }
1831         return false;
1832     }
1833     ts.orderedRemoveItem = orderedRemoveItem;
1834     /** Remove an item by index from an array, moving everything to its right one space left. */
1835     function orderedRemoveItemAt(array, index) {
1836         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1837         for (var i = index; i < array.length - 1; i++) {
1838             array[i] = array[i + 1];
1839         }
1840         array.pop();
1841     }
1842     ts.orderedRemoveItemAt = orderedRemoveItemAt;
1843     function unorderedRemoveItemAt(array, index) {
1844         // Fill in the "hole" left at `index`.
1845         array[index] = array[array.length - 1];
1846         array.pop();
1847     }
1848     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1849     /** Remove the *first* occurrence of `item` from the array. */
1850     function unorderedRemoveItem(array, item) {
1851         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1852     }
1853     ts.unorderedRemoveItem = unorderedRemoveItem;
1854     /** Remove the *first* element satisfying `predicate`. */
1855     function unorderedRemoveFirstItemWhere(array, predicate) {
1856         for (var i = 0; i < array.length; i++) {
1857             if (predicate(array[i])) {
1858                 unorderedRemoveItemAt(array, i);
1859                 return true;
1860             }
1861         }
1862         return false;
1863     }
1864     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1865         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
1866     }
1867     ts.createGetCanonicalFileName = createGetCanonicalFileName;
1868     function patternText(_a) {
1869         var prefix = _a.prefix, suffix = _a.suffix;
1870         return prefix + "*" + suffix;
1871     }
1872     ts.patternText = patternText;
1873     /**
1874      * Given that candidate matches pattern, returns the text matching the '*'.
1875      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
1876      */
1877     function matchedText(pattern, candidate) {
1878         ts.Debug.assert(isPatternMatch(pattern, candidate));
1879         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
1880     }
1881     ts.matchedText = matchedText;
1882     /** Return the object corresponding to the best pattern to match `candidate`. */
1883     function findBestPatternMatch(values, getPattern, candidate) {
1884         var matchedValue;
1885         // use length of prefix as betterness criteria
1886         var longestMatchPrefixLength = -1;
1887         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
1888             var v = values_2[_i];
1889             var pattern = getPattern(v);
1890             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
1891                 longestMatchPrefixLength = pattern.prefix.length;
1892                 matchedValue = v;
1893             }
1894         }
1895         return matchedValue;
1896     }
1897     ts.findBestPatternMatch = findBestPatternMatch;
1898     function startsWith(str, prefix) {
1899         return str.lastIndexOf(prefix, 0) === 0;
1900     }
1901     ts.startsWith = startsWith;
1902     function removePrefix(str, prefix) {
1903         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
1904     }
1905     ts.removePrefix = removePrefix;
1906     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
1907         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
1908         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
1909     }
1910     ts.tryRemovePrefix = tryRemovePrefix;
1911     function isPatternMatch(_a, candidate) {
1912         var prefix = _a.prefix, suffix = _a.suffix;
1913         return candidate.length >= prefix.length + suffix.length &&
1914             startsWith(candidate, prefix) &&
1915             endsWith(candidate, suffix);
1916     }
1917     function and(f, g) {
1918         return function (arg) { return f(arg) && g(arg); };
1919     }
1920     ts.and = and;
1921     function or() {
1922         var fs = [];
1923         for (var _i = 0; _i < arguments.length; _i++) {
1924             fs[_i] = arguments[_i];
1925         }
1926         return function () {
1927             var args = [];
1928             for (var _i = 0; _i < arguments.length; _i++) {
1929                 args[_i] = arguments[_i];
1930             }
1931             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
1932                 var f = fs_1[_a];
1933                 if (f.apply(void 0, args)) {
1934                     return true;
1935                 }
1936             }
1937             return false;
1938         };
1939     }
1940     ts.or = or;
1941     function not(fn) {
1942         return function () {
1943             var args = [];
1944             for (var _i = 0; _i < arguments.length; _i++) {
1945                 args[_i] = arguments[_i];
1946             }
1947             return !fn.apply(void 0, args);
1948         };
1949     }
1950     ts.not = not;
1951     function assertType(_) { }
1952     ts.assertType = assertType;
1953     function singleElementArray(t) {
1954         return t === undefined ? undefined : [t];
1955     }
1956     ts.singleElementArray = singleElementArray;
1957     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
1958         unchanged = unchanged || noop;
1959         var newIndex = 0;
1960         var oldIndex = 0;
1961         var newLen = newItems.length;
1962         var oldLen = oldItems.length;
1963         while (newIndex < newLen && oldIndex < oldLen) {
1964             var newItem = newItems[newIndex];
1965             var oldItem = oldItems[oldIndex];
1966             var compareResult = comparer(newItem, oldItem);
1967             if (compareResult === -1 /* LessThan */) {
1968                 inserted(newItem);
1969                 newIndex++;
1970             }
1971             else if (compareResult === 1 /* GreaterThan */) {
1972                 deleted(oldItem);
1973                 oldIndex++;
1974             }
1975             else {
1976                 unchanged(oldItem, newItem);
1977                 newIndex++;
1978                 oldIndex++;
1979             }
1980         }
1981         while (newIndex < newLen) {
1982             inserted(newItems[newIndex++]);
1983         }
1984         while (oldIndex < oldLen) {
1985             deleted(oldItems[oldIndex++]);
1986         }
1987     }
1988     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
1989     function fill(length, cb) {
1990         var result = Array(length);
1991         for (var i = 0; i < length; i++) {
1992             result[i] = cb(i);
1993         }
1994         return result;
1995     }
1996     ts.fill = fill;
1997     function cartesianProduct(arrays) {
1998         var result = [];
1999         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2000         return result;
2001     }
2002     ts.cartesianProduct = cartesianProduct;
2003     function cartesianProductWorker(arrays, result, outer, index) {
2004         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2005             var element = _a[_i];
2006             var inner = void 0;
2007             if (outer) {
2008                 inner = outer.slice();
2009                 inner.push(element);
2010             }
2011             else {
2012                 inner = [element];
2013             }
2014             if (index === arrays.length - 1) {
2015                 result.push(inner);
2016             }
2017             else {
2018                 cartesianProductWorker(arrays, result, inner, index + 1);
2019             }
2020         }
2021     }
2022     function padLeft(s, length) {
2023         while (s.length < length) {
2024             s = " " + s;
2025         }
2026         return s;
2027     }
2028     ts.padLeft = padLeft;
2029     function padRight(s, length) {
2030         while (s.length < length) {
2031             s = s + " ";
2032         }
2033         return s;
2034     }
2035     ts.padRight = padRight;
2036 })(ts || (ts = {}));
2037 /* @internal */
2038 var ts;
2039 (function (ts) {
2040     var Debug;
2041     (function (Debug) {
2042         var currentAssertionLevel = 0 /* None */;
2043         // eslint-disable-next-line prefer-const
2044         Debug.isDebugging = false;
2045         var assertionCache = {};
2046         function getAssertionLevel() {
2047             return currentAssertionLevel;
2048         }
2049         Debug.getAssertionLevel = getAssertionLevel;
2050         function setAssertionLevel(level) {
2051             var prevAssertionLevel = currentAssertionLevel;
2052             currentAssertionLevel = level;
2053             if (level > prevAssertionLevel) {
2054                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2055                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2056                     var key = _a[_i];
2057                     var cachedFunc = assertionCache[key];
2058                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2059                         Debug[key] = cachedFunc;
2060                         assertionCache[key] = undefined;
2061                     }
2062                 }
2063             }
2064         }
2065         Debug.setAssertionLevel = setAssertionLevel;
2066         function shouldAssert(level) {
2067             return currentAssertionLevel >= level;
2068         }
2069         Debug.shouldAssert = shouldAssert;
2070         /**
2071          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2072          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2073          * @param level The minimum assertion level required.
2074          * @param name The name of the current assertion function.
2075          */
2076         function shouldAssertFunction(level, name) {
2077             if (!shouldAssert(level)) {
2078                 assertionCache[name] = { level: level, assertion: Debug[name] };
2079                 Debug[name] = ts.noop;
2080                 return false;
2081             }
2082             return true;
2083         }
2084         function fail(message, stackCrawlMark) {
2085             debugger;
2086             var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2087             if (Error.captureStackTrace) {
2088                 Error.captureStackTrace(e, stackCrawlMark || fail);
2089             }
2090             throw e;
2091         }
2092         Debug.fail = fail;
2093         function failBadSyntaxKind(node, message, stackCrawlMark) {
2094             return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2095         }
2096         Debug.failBadSyntaxKind = failBadSyntaxKind;
2097         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2098             if (!expression) {
2099                 message = message ? "False expression: " + message : "False expression.";
2100                 if (verboseDebugInfo) {
2101                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2102                 }
2103                 fail(message, stackCrawlMark || assert);
2104             }
2105         }
2106         Debug.assert = assert;
2107         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2108             if (a !== b) {
2109                 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2110                 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2111             }
2112         }
2113         Debug.assertEqual = assertEqual;
2114         function assertLessThan(a, b, msg, stackCrawlMark) {
2115             if (a >= b) {
2116                 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2117             }
2118         }
2119         Debug.assertLessThan = assertLessThan;
2120         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2121             if (a > b) {
2122                 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2123             }
2124         }
2125         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2126         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2127             if (a < b) {
2128                 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2129             }
2130         }
2131         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2132         function assertIsDefined(value, message, stackCrawlMark) {
2133             // eslint-disable-next-line no-null/no-null
2134             if (value === undefined || value === null) {
2135                 fail(message, stackCrawlMark || assertIsDefined);
2136             }
2137         }
2138         Debug.assertIsDefined = assertIsDefined;
2139         function checkDefined(value, message, stackCrawlMark) {
2140             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2141             return value;
2142         }
2143         Debug.checkDefined = checkDefined;
2144         /**
2145          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2146          * a value is defined at the statement level.
2147          */
2148         Debug.assertDefined = checkDefined;
2149         function assertEachIsDefined(value, message, stackCrawlMark) {
2150             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2151                 var v = value_1[_i];
2152                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2153             }
2154         }
2155         Debug.assertEachIsDefined = assertEachIsDefined;
2156         function checkEachDefined(value, message, stackCrawlMark) {
2157             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2158             return value;
2159         }
2160         Debug.checkEachDefined = checkEachDefined;
2161         /**
2162          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2163          * the elements of an array are defined at the statement level.
2164          */
2165         Debug.assertEachDefined = checkEachDefined;
2166         function assertNever(member, message, stackCrawlMark) {
2167             if (message === void 0) { message = "Illegal value:"; }
2168             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2169             return fail(message + " " + detail, stackCrawlMark || assertNever);
2170         }
2171         Debug.assertNever = assertNever;
2172         function assertEachNode(nodes, test, message, stackCrawlMark) {
2173             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2174                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2175             }
2176         }
2177         Debug.assertEachNode = assertEachNode;
2178         function assertNode(node, test, message, stackCrawlMark) {
2179             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2180                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2181             }
2182         }
2183         Debug.assertNode = assertNode;
2184         function assertNotNode(node, test, message, stackCrawlMark) {
2185             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2186                 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);
2187             }
2188         }
2189         Debug.assertNotNode = assertNotNode;
2190         function assertOptionalNode(node, test, message, stackCrawlMark) {
2191             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2192                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2193             }
2194         }
2195         Debug.assertOptionalNode = assertOptionalNode;
2196         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2197             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2198                 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);
2199             }
2200         }
2201         Debug.assertOptionalToken = assertOptionalToken;
2202         function assertMissingNode(node, message, stackCrawlMark) {
2203             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2204                 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2205             }
2206         }
2207         Debug.assertMissingNode = assertMissingNode;
2208         function getFunctionName(func) {
2209             if (typeof func !== "function") {
2210                 return "";
2211             }
2212             else if (func.hasOwnProperty("name")) {
2213                 return func.name;
2214             }
2215             else {
2216                 var text = Function.prototype.toString.call(func);
2217                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2218                 return match ? match[1] : "";
2219             }
2220         }
2221         Debug.getFunctionName = getFunctionName;
2222         function formatSymbol(symbol) {
2223             return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2224         }
2225         Debug.formatSymbol = formatSymbol;
2226         /**
2227          * Formats an enum value as a string for debugging and debug assertions.
2228          */
2229         function formatEnum(value, enumObject, isFlags) {
2230             if (value === void 0) { value = 0; }
2231             var members = getEnumMembers(enumObject);
2232             if (value === 0) {
2233                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2234             }
2235             if (isFlags) {
2236                 var result = "";
2237                 var remainingFlags = value;
2238                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2239                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2240                     if (enumValue > value) {
2241                         break;
2242                     }
2243                     if (enumValue !== 0 && enumValue & value) {
2244                         result = "" + result + (result ? "|" : "") + enumName;
2245                         remainingFlags &= ~enumValue;
2246                     }
2247                 }
2248                 if (remainingFlags === 0) {
2249                     return result;
2250                 }
2251             }
2252             else {
2253                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2254                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2255                     if (enumValue === value) {
2256                         return enumName;
2257                     }
2258                 }
2259             }
2260             return value.toString();
2261         }
2262         Debug.formatEnum = formatEnum;
2263         function getEnumMembers(enumObject) {
2264             var result = [];
2265             for (var name in enumObject) {
2266                 var value = enumObject[name];
2267                 if (typeof value === "number") {
2268                     result.push([value, name]);
2269                 }
2270             }
2271             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2272         }
2273         function formatSyntaxKind(kind) {
2274             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2275         }
2276         Debug.formatSyntaxKind = formatSyntaxKind;
2277         function formatNodeFlags(flags) {
2278             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2279         }
2280         Debug.formatNodeFlags = formatNodeFlags;
2281         function formatModifierFlags(flags) {
2282             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2283         }
2284         Debug.formatModifierFlags = formatModifierFlags;
2285         function formatTransformFlags(flags) {
2286             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2287         }
2288         Debug.formatTransformFlags = formatTransformFlags;
2289         function formatEmitFlags(flags) {
2290             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2291         }
2292         Debug.formatEmitFlags = formatEmitFlags;
2293         function formatSymbolFlags(flags) {
2294             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2295         }
2296         Debug.formatSymbolFlags = formatSymbolFlags;
2297         function formatTypeFlags(flags) {
2298             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2299         }
2300         Debug.formatTypeFlags = formatTypeFlags;
2301         function formatObjectFlags(flags) {
2302             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2303         }
2304         Debug.formatObjectFlags = formatObjectFlags;
2305         var isDebugInfoEnabled = false;
2306         var extendedDebugModule;
2307         function extendedDebug() {
2308             enableDebugInfo();
2309             if (!extendedDebugModule) {
2310                 throw new Error("Debugging helpers could not be loaded.");
2311             }
2312             return extendedDebugModule;
2313         }
2314         function printControlFlowGraph(flowNode) {
2315             return console.log(formatControlFlowGraph(flowNode));
2316         }
2317         Debug.printControlFlowGraph = printControlFlowGraph;
2318         function formatControlFlowGraph(flowNode) {
2319             return extendedDebug().formatControlFlowGraph(flowNode);
2320         }
2321         Debug.formatControlFlowGraph = formatControlFlowGraph;
2322         function attachFlowNodeDebugInfo(flowNode) {
2323             if (isDebugInfoEnabled) {
2324                 if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2325                     Object.defineProperties(flowNode, {
2326                         __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2327                         __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2328                     });
2329                 }
2330             }
2331         }
2332         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2333         /**
2334          * Injects debug information into frequently used types.
2335          */
2336         function enableDebugInfo() {
2337             if (isDebugInfoEnabled)
2338                 return;
2339             // Add additional properties in debug mode to assist with debugging.
2340             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2341                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2342             });
2343             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2344                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2345                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2346                 __debugTypeToString: { value: function () { return this.checker.typeToString(this); } },
2347             });
2348             var nodeConstructors = [
2349                 ts.objectAllocator.getNodeConstructor(),
2350                 ts.objectAllocator.getIdentifierConstructor(),
2351                 ts.objectAllocator.getTokenConstructor(),
2352                 ts.objectAllocator.getSourceFileConstructor()
2353             ];
2354             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2355                 var ctor = nodeConstructors_1[_i];
2356                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2357                     Object.defineProperties(ctor.prototype, {
2358                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2359                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2360                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getModifierFlagsNoCache(this)); } },
2361                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2362                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2363                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2364                         __debugGetText: {
2365                             value: function (includeTrivia) {
2366                                 if (ts.nodeIsSynthesized(this))
2367                                     return "";
2368                                 var parseNode = ts.getParseTreeNode(this);
2369                                 var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2370                                 return sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2371                             }
2372                         }
2373                     });
2374                 }
2375             }
2376             // attempt to load extended debugging information
2377             try {
2378                 if (ts.sys && ts.sys.require) {
2379                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2380                     var result = ts.sys.require(basePath, "./compiler-debug");
2381                     if (!result.error) {
2382                         result.module.init(ts);
2383                         extendedDebugModule = result.module;
2384                     }
2385                 }
2386             }
2387             catch (_a) {
2388                 // do nothing
2389             }
2390             isDebugInfoEnabled = true;
2391         }
2392         Debug.enableDebugInfo = enableDebugInfo;
2393     })(Debug = ts.Debug || (ts.Debug = {}));
2394 })(ts || (ts = {}));
2395 /*@internal*/
2396 var ts;
2397 (function (ts) {
2398     /** Gets a timestamp with (at least) ms resolution */
2399     ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); };
2400 })(ts || (ts = {}));
2401 /*@internal*/
2402 /** Performance measurements for the compiler. */
2403 var ts;
2404 (function (ts) {
2405     var performance;
2406     (function (performance) {
2407         // NOTE: cannot use ts.noop as core.ts loads after this
2408         var profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true ? onProfilerEvent : function () { };
2409         var enabled = false;
2410         var profilerStart = 0;
2411         var counts;
2412         var marks;
2413         var measures;
2414         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
2415             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
2416         }
2417         performance.createTimerIf = createTimerIf;
2418         function createTimer(measureName, startMarkName, endMarkName) {
2419             var enterCount = 0;
2420             return {
2421                 enter: enter,
2422                 exit: exit
2423             };
2424             function enter() {
2425                 if (++enterCount === 1) {
2426                     mark(startMarkName);
2427                 }
2428             }
2429             function exit() {
2430                 if (--enterCount === 0) {
2431                     mark(endMarkName);
2432                     measure(measureName, startMarkName, endMarkName);
2433                 }
2434                 else if (enterCount < 0) {
2435                     ts.Debug.fail("enter/exit count does not match.");
2436                 }
2437             }
2438         }
2439         performance.createTimer = createTimer;
2440         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
2441         /**
2442          * Marks a performance event.
2443          *
2444          * @param markName The name of the mark.
2445          */
2446         function mark(markName) {
2447             if (enabled) {
2448                 marks.set(markName, ts.timestamp());
2449                 counts.set(markName, (counts.get(markName) || 0) + 1);
2450                 profilerEvent(markName);
2451             }
2452         }
2453         performance.mark = mark;
2454         /**
2455          * Adds a performance measurement with the specified name.
2456          *
2457          * @param measureName The name of the performance measurement.
2458          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
2459          *      profiler was enabled is used.
2460          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
2461          *      used.
2462          */
2463         function measure(measureName, startMarkName, endMarkName) {
2464             if (enabled) {
2465                 var end = endMarkName && marks.get(endMarkName) || ts.timestamp();
2466                 var start = startMarkName && marks.get(startMarkName) || profilerStart;
2467                 measures.set(measureName, (measures.get(measureName) || 0) + (end - start));
2468             }
2469         }
2470         performance.measure = measure;
2471         /**
2472          * Gets the number of times a marker was encountered.
2473          *
2474          * @param markName The name of the mark.
2475          */
2476         function getCount(markName) {
2477             return counts && counts.get(markName) || 0;
2478         }
2479         performance.getCount = getCount;
2480         /**
2481          * Gets the total duration of all measurements with the supplied name.
2482          *
2483          * @param measureName The name of the measure whose durations should be accumulated.
2484          */
2485         function getDuration(measureName) {
2486             return measures && measures.get(measureName) || 0;
2487         }
2488         performance.getDuration = getDuration;
2489         /**
2490          * Iterate over each measure, performing some action
2491          *
2492          * @param cb The action to perform for each measure
2493          */
2494         function forEachMeasure(cb) {
2495             measures.forEach(function (measure, key) {
2496                 cb(key, measure);
2497             });
2498         }
2499         performance.forEachMeasure = forEachMeasure;
2500         /** Enables (and resets) performance measurements for the compiler. */
2501         function enable() {
2502             counts = ts.createMap();
2503             marks = ts.createMap();
2504             measures = ts.createMap();
2505             enabled = true;
2506             profilerStart = ts.timestamp();
2507         }
2508         performance.enable = enable;
2509         /** Disables performance measurements for the compiler. */
2510         function disable() {
2511             enabled = false;
2512         }
2513         performance.disable = disable;
2514     })(performance = ts.performance || (ts.performance = {}));
2515 })(ts || (ts = {}));
2516 /* @internal */
2517 var ts;
2518 (function (ts) {
2519     var nullLogger = {
2520         logEvent: ts.noop,
2521         logErrEvent: ts.noop,
2522         logPerfEvent: ts.noop,
2523         logInfoEvent: ts.noop,
2524         logStartCommand: ts.noop,
2525         logStopCommand: ts.noop,
2526         logStartUpdateProgram: ts.noop,
2527         logStopUpdateProgram: ts.noop,
2528         logStartUpdateGraph: ts.noop,
2529         logStopUpdateGraph: ts.noop,
2530         logStartResolveModule: ts.noop,
2531         logStopResolveModule: ts.noop,
2532         logStartParseSourceFile: ts.noop,
2533         logStopParseSourceFile: ts.noop,
2534         logStartReadFile: ts.noop,
2535         logStopReadFile: ts.noop,
2536         logStartBindFile: ts.noop,
2537         logStopBindFile: ts.noop,
2538         logStartScheduledOperation: ts.noop,
2539         logStopScheduledOperation: ts.noop,
2540     };
2541     // Load optional module to enable Event Tracing for Windows
2542     // See https://github.com/microsoft/typescript-etw for more information
2543     var etwModule;
2544     try {
2545         // require() will throw an exception if the module is not installed
2546         // It may also return undefined if not installed properly
2547         etwModule = require("@microsoft/typescript-etw");
2548     }
2549     catch (e) {
2550         etwModule = undefined;
2551     }
2552     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
2553     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
2554 })(ts || (ts = {}));
2555 /* @internal */
2556 var ts;
2557 (function (ts) {
2558     // https://semver.org/#spec-item-2
2559     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2560     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2561     // > version, and Z is the patch version. Each element MUST increase numerically.
2562     //
2563     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2564     // value of `0`.
2565     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2566     // https://semver.org/#spec-item-9
2567     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2568     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2569     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2570     // > MUST NOT include leading zeroes.
2571     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2572     // https://semver.org/#spec-item-10
2573     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2574     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2575     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2576     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2577     // https://semver.org/#spec-item-9
2578     // > Numeric identifiers MUST NOT include leading zeroes.
2579     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2580     /**
2581      * Describes a precise semantic version number, https://semver.org
2582      */
2583     var Version = /** @class */ (function () {
2584         function Version(major, minor, patch, prerelease, build) {
2585             if (minor === void 0) { minor = 0; }
2586             if (patch === void 0) { patch = 0; }
2587             if (prerelease === void 0) { prerelease = ""; }
2588             if (build === void 0) { build = ""; }
2589             if (typeof major === "string") {
2590                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2591                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2592             }
2593             ts.Debug.assert(major >= 0, "Invalid argument: major");
2594             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2595             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2596             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2597             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2598             this.major = major;
2599             this.minor = minor;
2600             this.patch = patch;
2601             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2602             this.build = build ? build.split(".") : ts.emptyArray;
2603         }
2604         Version.tryParse = function (text) {
2605             var result = tryParseComponents(text);
2606             if (!result)
2607                 return undefined;
2608             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2609             return new Version(major, minor, patch, prerelease, build);
2610         };
2611         Version.prototype.compareTo = function (other) {
2612             // https://semver.org/#spec-item-11
2613             // > Precedence is determined by the first difference when comparing each of these
2614             // > identifiers from left to right as follows: Major, minor, and patch versions are
2615             // > always compared numerically.
2616             //
2617             // https://semver.org/#spec-item-11
2618             // > Precedence for two pre-release versions with the same major, minor, and patch version
2619             // > MUST be determined by comparing each dot separated identifier from left to right until
2620             // > a difference is found [...]
2621             //
2622             // https://semver.org/#spec-item-11
2623             // > Build metadata does not figure into precedence
2624             if (this === other)
2625                 return 0 /* EqualTo */;
2626             if (other === undefined)
2627                 return 1 /* GreaterThan */;
2628             return ts.compareValues(this.major, other.major)
2629                 || ts.compareValues(this.minor, other.minor)
2630                 || ts.compareValues(this.patch, other.patch)
2631                 || comparePrerelaseIdentifiers(this.prerelease, other.prerelease);
2632         };
2633         Version.prototype.increment = function (field) {
2634             switch (field) {
2635                 case "major": return new Version(this.major + 1, 0, 0);
2636                 case "minor": return new Version(this.major, this.minor + 1, 0);
2637                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2638                 default: return ts.Debug.assertNever(field);
2639             }
2640         };
2641         Version.prototype.toString = function () {
2642             var result = this.major + "." + this.minor + "." + this.patch;
2643             if (ts.some(this.prerelease))
2644                 result += "-" + this.prerelease.join(".");
2645             if (ts.some(this.build))
2646                 result += "+" + this.build.join(".");
2647             return result;
2648         };
2649         Version.zero = new Version(0, 0, 0);
2650         return Version;
2651     }());
2652     ts.Version = Version;
2653     function tryParseComponents(text) {
2654         var match = versionRegExp.exec(text);
2655         if (!match)
2656             return undefined;
2657         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;
2658         if (prerelease && !prereleaseRegExp.test(prerelease))
2659             return undefined;
2660         if (build && !buildRegExp.test(build))
2661             return undefined;
2662         return {
2663             major: parseInt(major, 10),
2664             minor: parseInt(minor, 10),
2665             patch: parseInt(patch, 10),
2666             prerelease: prerelease,
2667             build: build
2668         };
2669     }
2670     function comparePrerelaseIdentifiers(left, right) {
2671         // https://semver.org/#spec-item-11
2672         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2673         // > than a normal version.
2674         if (left === right)
2675             return 0 /* EqualTo */;
2676         if (left.length === 0)
2677             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2678         if (right.length === 0)
2679             return -1 /* LessThan */;
2680         // https://semver.org/#spec-item-11
2681         // > Precedence for two pre-release versions with the same major, minor, and patch version
2682         // > MUST be determined by comparing each dot separated identifier from left to right until
2683         // > a difference is found [...]
2684         var length = Math.min(left.length, right.length);
2685         for (var i = 0; i < length; i++) {
2686             var leftIdentifier = left[i];
2687             var rightIdentifier = right[i];
2688             if (leftIdentifier === rightIdentifier)
2689                 continue;
2690             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2691             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2692             if (leftIsNumeric || rightIsNumeric) {
2693                 // https://semver.org/#spec-item-11
2694                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2695                 if (leftIsNumeric !== rightIsNumeric)
2696                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2697                 // https://semver.org/#spec-item-11
2698                 // > identifiers consisting of only digits are compared numerically
2699                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2700                 if (result)
2701                     return result;
2702             }
2703             else {
2704                 // https://semver.org/#spec-item-11
2705                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2706                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2707                 if (result)
2708                     return result;
2709             }
2710         }
2711         // https://semver.org/#spec-item-11
2712         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2713         // > of the preceding identifiers are equal.
2714         return ts.compareValues(left.length, right.length);
2715     }
2716     /**
2717      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2718      */
2719     var VersionRange = /** @class */ (function () {
2720         function VersionRange(spec) {
2721             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2722         }
2723         VersionRange.tryParse = function (text) {
2724             var sets = parseRange(text);
2725             if (sets) {
2726                 var range = new VersionRange("");
2727                 range._alternatives = sets;
2728                 return range;
2729             }
2730             return undefined;
2731         };
2732         VersionRange.prototype.test = function (version) {
2733             if (typeof version === "string")
2734                 version = new Version(version);
2735             return testDisjunction(version, this._alternatives);
2736         };
2737         VersionRange.prototype.toString = function () {
2738             return formatDisjunction(this._alternatives);
2739         };
2740         return VersionRange;
2741     }());
2742     ts.VersionRange = VersionRange;
2743     // https://github.com/npm/node-semver#range-grammar
2744     //
2745     // range-set    ::= range ( logical-or range ) *
2746     // range        ::= hyphen | simple ( ' ' simple ) * | ''
2747     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
2748     var logicalOrRegExp = /\s*\|\|\s*/g;
2749     var whitespaceRegExp = /\s+/g;
2750     // https://github.com/npm/node-semver#range-grammar
2751     //
2752     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
2753     // xr           ::= 'x' | 'X' | '*' | nr
2754     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
2755     // qualifier    ::= ( '-' pre )? ( '+' build )?
2756     // pre          ::= parts
2757     // build        ::= parts
2758     // parts        ::= part ( '.' part ) *
2759     // part         ::= nr | [-0-9A-Za-z]+
2760     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2761     // https://github.com/npm/node-semver#range-grammar
2762     //
2763     // hyphen       ::= partial ' - ' partial
2764     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
2765     // https://github.com/npm/node-semver#range-grammar
2766     //
2767     // simple       ::= primitive | partial | tilde | caret
2768     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
2769     // tilde        ::= '~' partial
2770     // caret        ::= '^' partial
2771     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
2772     function parseRange(text) {
2773         var alternatives = [];
2774         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
2775             var range = _a[_i];
2776             if (!range)
2777                 continue;
2778             var comparators = [];
2779             var match = hyphenRegExp.exec(range);
2780             if (match) {
2781                 if (!parseHyphen(match[1], match[2], comparators))
2782                     return undefined;
2783             }
2784             else {
2785                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
2786                     var simple = _c[_b];
2787                     var match_1 = rangeRegExp.exec(simple);
2788                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
2789                         return undefined;
2790                 }
2791             }
2792             alternatives.push(comparators);
2793         }
2794         return alternatives;
2795     }
2796     function parsePartial(text) {
2797         var match = partialRegExp.exec(text);
2798         if (!match)
2799             return undefined;
2800         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];
2801         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);
2802         return { version: version, major: major, minor: minor, patch: patch };
2803     }
2804     function parseHyphen(left, right, comparators) {
2805         var leftResult = parsePartial(left);
2806         if (!leftResult)
2807             return false;
2808         var rightResult = parsePartial(right);
2809         if (!rightResult)
2810             return false;
2811         if (!isWildcard(leftResult.major)) {
2812             comparators.push(createComparator(">=", leftResult.version));
2813         }
2814         if (!isWildcard(rightResult.major)) {
2815             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
2816                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
2817                     createComparator("<=", rightResult.version));
2818         }
2819         return true;
2820     }
2821     function parseComparator(operator, text, comparators) {
2822         var result = parsePartial(text);
2823         if (!result)
2824             return false;
2825         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
2826         if (!isWildcard(major)) {
2827             switch (operator) {
2828                 case "~":
2829                     comparators.push(createComparator(">=", version));
2830                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
2831                         "minor")));
2832                     break;
2833                 case "^":
2834                     comparators.push(createComparator(">=", version));
2835                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
2836                         version.minor > 0 || isWildcard(patch) ? "minor" :
2837                             "patch")));
2838                     break;
2839                 case "<":
2840                 case ">=":
2841                     comparators.push(createComparator(operator, version));
2842                     break;
2843                 case "<=":
2844                 case ">":
2845                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
2846                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
2847                             createComparator(operator, version));
2848                     break;
2849                 case "=":
2850                 case undefined:
2851                     if (isWildcard(minor) || isWildcard(patch)) {
2852                         comparators.push(createComparator(">=", version));
2853                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
2854                     }
2855                     else {
2856                         comparators.push(createComparator("=", version));
2857                     }
2858                     break;
2859                 default:
2860                     // unrecognized
2861                     return false;
2862             }
2863         }
2864         else if (operator === "<" || operator === ">") {
2865             comparators.push(createComparator("<", Version.zero));
2866         }
2867         return true;
2868     }
2869     function isWildcard(part) {
2870         return part === "*" || part === "x" || part === "X";
2871     }
2872     function createComparator(operator, operand) {
2873         return { operator: operator, operand: operand };
2874     }
2875     function testDisjunction(version, alternatives) {
2876         // an empty disjunction is treated as "*" (all versions)
2877         if (alternatives.length === 0)
2878             return true;
2879         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
2880             var alternative = alternatives_1[_i];
2881             if (testAlternative(version, alternative))
2882                 return true;
2883         }
2884         return false;
2885     }
2886     function testAlternative(version, comparators) {
2887         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
2888             var comparator = comparators_1[_i];
2889             if (!testComparator(version, comparator.operator, comparator.operand))
2890                 return false;
2891         }
2892         return true;
2893     }
2894     function testComparator(version, operator, operand) {
2895         var cmp = version.compareTo(operand);
2896         switch (operator) {
2897             case "<": return cmp < 0;
2898             case "<=": return cmp <= 0;
2899             case ">": return cmp > 0;
2900             case ">=": return cmp >= 0;
2901             case "=": return cmp === 0;
2902             default: return ts.Debug.assertNever(operator);
2903         }
2904     }
2905     function formatDisjunction(alternatives) {
2906         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
2907     }
2908     function formatAlternative(comparators) {
2909         return ts.map(comparators, formatComparator).join(" ");
2910     }
2911     function formatComparator(comparator) {
2912         return "" + comparator.operator + comparator.operand;
2913     }
2914 })(ts || (ts = {}));
2915 var ts;
2916 (function (ts) {
2917     // token > SyntaxKind.Identifier => token is a keyword
2918     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
2919     var SyntaxKind;
2920     (function (SyntaxKind) {
2921         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
2922         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
2923         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
2924         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
2925         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
2926         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
2927         // We detect and preserve #! on the first line
2928         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
2929         // We detect and provide better error recovery when we encounter a git merge marker.  This
2930         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
2931         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
2932         // Literals
2933         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
2934         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
2935         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
2936         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
2937         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
2938         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
2939         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
2940         // Pseudo-literals
2941         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
2942         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
2943         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
2944         // Punctuation
2945         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
2946         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
2947         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
2948         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
2949         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
2950         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
2951         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
2952         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
2953         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
2954         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
2955         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
2956         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
2957         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
2958         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
2959         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
2960         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
2961         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
2962         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
2963         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
2964         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
2965         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
2966         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
2967         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
2968         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
2969         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
2970         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
2971         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
2972         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
2973         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
2974         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
2975         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
2976         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
2977         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
2978         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
2979         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
2980         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
2981         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
2982         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
2983         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
2984         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
2985         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
2986         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
2987         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
2988         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
2989         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
2990         // Assignments
2991         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
2992         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
2993         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
2994         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
2995         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
2996         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
2997         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
2998         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
2999         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3000         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3001         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3002         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3003         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 74] = "CaretEqualsToken";
3004         // Identifiers and PrivateIdentifiers
3005         SyntaxKind[SyntaxKind["Identifier"] = 75] = "Identifier";
3006         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 76] = "PrivateIdentifier";
3007         // Reserved words
3008         SyntaxKind[SyntaxKind["BreakKeyword"] = 77] = "BreakKeyword";
3009         SyntaxKind[SyntaxKind["CaseKeyword"] = 78] = "CaseKeyword";
3010         SyntaxKind[SyntaxKind["CatchKeyword"] = 79] = "CatchKeyword";
3011         SyntaxKind[SyntaxKind["ClassKeyword"] = 80] = "ClassKeyword";
3012         SyntaxKind[SyntaxKind["ConstKeyword"] = 81] = "ConstKeyword";
3013         SyntaxKind[SyntaxKind["ContinueKeyword"] = 82] = "ContinueKeyword";
3014         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 83] = "DebuggerKeyword";
3015         SyntaxKind[SyntaxKind["DefaultKeyword"] = 84] = "DefaultKeyword";
3016         SyntaxKind[SyntaxKind["DeleteKeyword"] = 85] = "DeleteKeyword";
3017         SyntaxKind[SyntaxKind["DoKeyword"] = 86] = "DoKeyword";
3018         SyntaxKind[SyntaxKind["ElseKeyword"] = 87] = "ElseKeyword";
3019         SyntaxKind[SyntaxKind["EnumKeyword"] = 88] = "EnumKeyword";
3020         SyntaxKind[SyntaxKind["ExportKeyword"] = 89] = "ExportKeyword";
3021         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 90] = "ExtendsKeyword";
3022         SyntaxKind[SyntaxKind["FalseKeyword"] = 91] = "FalseKeyword";
3023         SyntaxKind[SyntaxKind["FinallyKeyword"] = 92] = "FinallyKeyword";
3024         SyntaxKind[SyntaxKind["ForKeyword"] = 93] = "ForKeyword";
3025         SyntaxKind[SyntaxKind["FunctionKeyword"] = 94] = "FunctionKeyword";
3026         SyntaxKind[SyntaxKind["IfKeyword"] = 95] = "IfKeyword";
3027         SyntaxKind[SyntaxKind["ImportKeyword"] = 96] = "ImportKeyword";
3028         SyntaxKind[SyntaxKind["InKeyword"] = 97] = "InKeyword";
3029         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 98] = "InstanceOfKeyword";
3030         SyntaxKind[SyntaxKind["NewKeyword"] = 99] = "NewKeyword";
3031         SyntaxKind[SyntaxKind["NullKeyword"] = 100] = "NullKeyword";
3032         SyntaxKind[SyntaxKind["ReturnKeyword"] = 101] = "ReturnKeyword";
3033         SyntaxKind[SyntaxKind["SuperKeyword"] = 102] = "SuperKeyword";
3034         SyntaxKind[SyntaxKind["SwitchKeyword"] = 103] = "SwitchKeyword";
3035         SyntaxKind[SyntaxKind["ThisKeyword"] = 104] = "ThisKeyword";
3036         SyntaxKind[SyntaxKind["ThrowKeyword"] = 105] = "ThrowKeyword";
3037         SyntaxKind[SyntaxKind["TrueKeyword"] = 106] = "TrueKeyword";
3038         SyntaxKind[SyntaxKind["TryKeyword"] = 107] = "TryKeyword";
3039         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 108] = "TypeOfKeyword";
3040         SyntaxKind[SyntaxKind["VarKeyword"] = 109] = "VarKeyword";
3041         SyntaxKind[SyntaxKind["VoidKeyword"] = 110] = "VoidKeyword";
3042         SyntaxKind[SyntaxKind["WhileKeyword"] = 111] = "WhileKeyword";
3043         SyntaxKind[SyntaxKind["WithKeyword"] = 112] = "WithKeyword";
3044         // Strict mode reserved words
3045         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 113] = "ImplementsKeyword";
3046         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 114] = "InterfaceKeyword";
3047         SyntaxKind[SyntaxKind["LetKeyword"] = 115] = "LetKeyword";
3048         SyntaxKind[SyntaxKind["PackageKeyword"] = 116] = "PackageKeyword";
3049         SyntaxKind[SyntaxKind["PrivateKeyword"] = 117] = "PrivateKeyword";
3050         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 118] = "ProtectedKeyword";
3051         SyntaxKind[SyntaxKind["PublicKeyword"] = 119] = "PublicKeyword";
3052         SyntaxKind[SyntaxKind["StaticKeyword"] = 120] = "StaticKeyword";
3053         SyntaxKind[SyntaxKind["YieldKeyword"] = 121] = "YieldKeyword";
3054         // Contextual keywords
3055         SyntaxKind[SyntaxKind["AbstractKeyword"] = 122] = "AbstractKeyword";
3056         SyntaxKind[SyntaxKind["AsKeyword"] = 123] = "AsKeyword";
3057         SyntaxKind[SyntaxKind["AssertsKeyword"] = 124] = "AssertsKeyword";
3058         SyntaxKind[SyntaxKind["AnyKeyword"] = 125] = "AnyKeyword";
3059         SyntaxKind[SyntaxKind["AsyncKeyword"] = 126] = "AsyncKeyword";
3060         SyntaxKind[SyntaxKind["AwaitKeyword"] = 127] = "AwaitKeyword";
3061         SyntaxKind[SyntaxKind["BooleanKeyword"] = 128] = "BooleanKeyword";
3062         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 129] = "ConstructorKeyword";
3063         SyntaxKind[SyntaxKind["DeclareKeyword"] = 130] = "DeclareKeyword";
3064         SyntaxKind[SyntaxKind["GetKeyword"] = 131] = "GetKeyword";
3065         SyntaxKind[SyntaxKind["InferKeyword"] = 132] = "InferKeyword";
3066         SyntaxKind[SyntaxKind["IsKeyword"] = 133] = "IsKeyword";
3067         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 134] = "KeyOfKeyword";
3068         SyntaxKind[SyntaxKind["ModuleKeyword"] = 135] = "ModuleKeyword";
3069         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 136] = "NamespaceKeyword";
3070         SyntaxKind[SyntaxKind["NeverKeyword"] = 137] = "NeverKeyword";
3071         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 138] = "ReadonlyKeyword";
3072         SyntaxKind[SyntaxKind["RequireKeyword"] = 139] = "RequireKeyword";
3073         SyntaxKind[SyntaxKind["NumberKeyword"] = 140] = "NumberKeyword";
3074         SyntaxKind[SyntaxKind["ObjectKeyword"] = 141] = "ObjectKeyword";
3075         SyntaxKind[SyntaxKind["SetKeyword"] = 142] = "SetKeyword";
3076         SyntaxKind[SyntaxKind["StringKeyword"] = 143] = "StringKeyword";
3077         SyntaxKind[SyntaxKind["SymbolKeyword"] = 144] = "SymbolKeyword";
3078         SyntaxKind[SyntaxKind["TypeKeyword"] = 145] = "TypeKeyword";
3079         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 146] = "UndefinedKeyword";
3080         SyntaxKind[SyntaxKind["UniqueKeyword"] = 147] = "UniqueKeyword";
3081         SyntaxKind[SyntaxKind["UnknownKeyword"] = 148] = "UnknownKeyword";
3082         SyntaxKind[SyntaxKind["FromKeyword"] = 149] = "FromKeyword";
3083         SyntaxKind[SyntaxKind["GlobalKeyword"] = 150] = "GlobalKeyword";
3084         SyntaxKind[SyntaxKind["BigIntKeyword"] = 151] = "BigIntKeyword";
3085         SyntaxKind[SyntaxKind["OfKeyword"] = 152] = "OfKeyword";
3086         // Parse tree nodes
3087         // Names
3088         SyntaxKind[SyntaxKind["QualifiedName"] = 153] = "QualifiedName";
3089         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 154] = "ComputedPropertyName";
3090         // Signature elements
3091         SyntaxKind[SyntaxKind["TypeParameter"] = 155] = "TypeParameter";
3092         SyntaxKind[SyntaxKind["Parameter"] = 156] = "Parameter";
3093         SyntaxKind[SyntaxKind["Decorator"] = 157] = "Decorator";
3094         // TypeMember
3095         SyntaxKind[SyntaxKind["PropertySignature"] = 158] = "PropertySignature";
3096         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 159] = "PropertyDeclaration";
3097         SyntaxKind[SyntaxKind["MethodSignature"] = 160] = "MethodSignature";
3098         SyntaxKind[SyntaxKind["MethodDeclaration"] = 161] = "MethodDeclaration";
3099         SyntaxKind[SyntaxKind["Constructor"] = 162] = "Constructor";
3100         SyntaxKind[SyntaxKind["GetAccessor"] = 163] = "GetAccessor";
3101         SyntaxKind[SyntaxKind["SetAccessor"] = 164] = "SetAccessor";
3102         SyntaxKind[SyntaxKind["CallSignature"] = 165] = "CallSignature";
3103         SyntaxKind[SyntaxKind["ConstructSignature"] = 166] = "ConstructSignature";
3104         SyntaxKind[SyntaxKind["IndexSignature"] = 167] = "IndexSignature";
3105         // Type
3106         SyntaxKind[SyntaxKind["TypePredicate"] = 168] = "TypePredicate";
3107         SyntaxKind[SyntaxKind["TypeReference"] = 169] = "TypeReference";
3108         SyntaxKind[SyntaxKind["FunctionType"] = 170] = "FunctionType";
3109         SyntaxKind[SyntaxKind["ConstructorType"] = 171] = "ConstructorType";
3110         SyntaxKind[SyntaxKind["TypeQuery"] = 172] = "TypeQuery";
3111         SyntaxKind[SyntaxKind["TypeLiteral"] = 173] = "TypeLiteral";
3112         SyntaxKind[SyntaxKind["ArrayType"] = 174] = "ArrayType";
3113         SyntaxKind[SyntaxKind["TupleType"] = 175] = "TupleType";
3114         SyntaxKind[SyntaxKind["OptionalType"] = 176] = "OptionalType";
3115         SyntaxKind[SyntaxKind["RestType"] = 177] = "RestType";
3116         SyntaxKind[SyntaxKind["UnionType"] = 178] = "UnionType";
3117         SyntaxKind[SyntaxKind["IntersectionType"] = 179] = "IntersectionType";
3118         SyntaxKind[SyntaxKind["ConditionalType"] = 180] = "ConditionalType";
3119         SyntaxKind[SyntaxKind["InferType"] = 181] = "InferType";
3120         SyntaxKind[SyntaxKind["ParenthesizedType"] = 182] = "ParenthesizedType";
3121         SyntaxKind[SyntaxKind["ThisType"] = 183] = "ThisType";
3122         SyntaxKind[SyntaxKind["TypeOperator"] = 184] = "TypeOperator";
3123         SyntaxKind[SyntaxKind["IndexedAccessType"] = 185] = "IndexedAccessType";
3124         SyntaxKind[SyntaxKind["MappedType"] = 186] = "MappedType";
3125         SyntaxKind[SyntaxKind["LiteralType"] = 187] = "LiteralType";
3126         SyntaxKind[SyntaxKind["ImportType"] = 188] = "ImportType";
3127         // Binding patterns
3128         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 189] = "ObjectBindingPattern";
3129         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 190] = "ArrayBindingPattern";
3130         SyntaxKind[SyntaxKind["BindingElement"] = 191] = "BindingElement";
3131         // Expression
3132         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 192] = "ArrayLiteralExpression";
3133         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 193] = "ObjectLiteralExpression";
3134         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 194] = "PropertyAccessExpression";
3135         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 195] = "ElementAccessExpression";
3136         SyntaxKind[SyntaxKind["CallExpression"] = 196] = "CallExpression";
3137         SyntaxKind[SyntaxKind["NewExpression"] = 197] = "NewExpression";
3138         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 198] = "TaggedTemplateExpression";
3139         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 199] = "TypeAssertionExpression";
3140         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 200] = "ParenthesizedExpression";
3141         SyntaxKind[SyntaxKind["FunctionExpression"] = 201] = "FunctionExpression";
3142         SyntaxKind[SyntaxKind["ArrowFunction"] = 202] = "ArrowFunction";
3143         SyntaxKind[SyntaxKind["DeleteExpression"] = 203] = "DeleteExpression";
3144         SyntaxKind[SyntaxKind["TypeOfExpression"] = 204] = "TypeOfExpression";
3145         SyntaxKind[SyntaxKind["VoidExpression"] = 205] = "VoidExpression";
3146         SyntaxKind[SyntaxKind["AwaitExpression"] = 206] = "AwaitExpression";
3147         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 207] = "PrefixUnaryExpression";
3148         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 208] = "PostfixUnaryExpression";
3149         SyntaxKind[SyntaxKind["BinaryExpression"] = 209] = "BinaryExpression";
3150         SyntaxKind[SyntaxKind["ConditionalExpression"] = 210] = "ConditionalExpression";
3151         SyntaxKind[SyntaxKind["TemplateExpression"] = 211] = "TemplateExpression";
3152         SyntaxKind[SyntaxKind["YieldExpression"] = 212] = "YieldExpression";
3153         SyntaxKind[SyntaxKind["SpreadElement"] = 213] = "SpreadElement";
3154         SyntaxKind[SyntaxKind["ClassExpression"] = 214] = "ClassExpression";
3155         SyntaxKind[SyntaxKind["OmittedExpression"] = 215] = "OmittedExpression";
3156         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 216] = "ExpressionWithTypeArguments";
3157         SyntaxKind[SyntaxKind["AsExpression"] = 217] = "AsExpression";
3158         SyntaxKind[SyntaxKind["NonNullExpression"] = 218] = "NonNullExpression";
3159         SyntaxKind[SyntaxKind["MetaProperty"] = 219] = "MetaProperty";
3160         SyntaxKind[SyntaxKind["SyntheticExpression"] = 220] = "SyntheticExpression";
3161         // Misc
3162         SyntaxKind[SyntaxKind["TemplateSpan"] = 221] = "TemplateSpan";
3163         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 222] = "SemicolonClassElement";
3164         // Element
3165         SyntaxKind[SyntaxKind["Block"] = 223] = "Block";
3166         SyntaxKind[SyntaxKind["EmptyStatement"] = 224] = "EmptyStatement";
3167         SyntaxKind[SyntaxKind["VariableStatement"] = 225] = "VariableStatement";
3168         SyntaxKind[SyntaxKind["ExpressionStatement"] = 226] = "ExpressionStatement";
3169         SyntaxKind[SyntaxKind["IfStatement"] = 227] = "IfStatement";
3170         SyntaxKind[SyntaxKind["DoStatement"] = 228] = "DoStatement";
3171         SyntaxKind[SyntaxKind["WhileStatement"] = 229] = "WhileStatement";
3172         SyntaxKind[SyntaxKind["ForStatement"] = 230] = "ForStatement";
3173         SyntaxKind[SyntaxKind["ForInStatement"] = 231] = "ForInStatement";
3174         SyntaxKind[SyntaxKind["ForOfStatement"] = 232] = "ForOfStatement";
3175         SyntaxKind[SyntaxKind["ContinueStatement"] = 233] = "ContinueStatement";
3176         SyntaxKind[SyntaxKind["BreakStatement"] = 234] = "BreakStatement";
3177         SyntaxKind[SyntaxKind["ReturnStatement"] = 235] = "ReturnStatement";
3178         SyntaxKind[SyntaxKind["WithStatement"] = 236] = "WithStatement";
3179         SyntaxKind[SyntaxKind["SwitchStatement"] = 237] = "SwitchStatement";
3180         SyntaxKind[SyntaxKind["LabeledStatement"] = 238] = "LabeledStatement";
3181         SyntaxKind[SyntaxKind["ThrowStatement"] = 239] = "ThrowStatement";
3182         SyntaxKind[SyntaxKind["TryStatement"] = 240] = "TryStatement";
3183         SyntaxKind[SyntaxKind["DebuggerStatement"] = 241] = "DebuggerStatement";
3184         SyntaxKind[SyntaxKind["VariableDeclaration"] = 242] = "VariableDeclaration";
3185         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 243] = "VariableDeclarationList";
3186         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 244] = "FunctionDeclaration";
3187         SyntaxKind[SyntaxKind["ClassDeclaration"] = 245] = "ClassDeclaration";
3188         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 246] = "InterfaceDeclaration";
3189         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 247] = "TypeAliasDeclaration";
3190         SyntaxKind[SyntaxKind["EnumDeclaration"] = 248] = "EnumDeclaration";
3191         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 249] = "ModuleDeclaration";
3192         SyntaxKind[SyntaxKind["ModuleBlock"] = 250] = "ModuleBlock";
3193         SyntaxKind[SyntaxKind["CaseBlock"] = 251] = "CaseBlock";
3194         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 252] = "NamespaceExportDeclaration";
3195         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 253] = "ImportEqualsDeclaration";
3196         SyntaxKind[SyntaxKind["ImportDeclaration"] = 254] = "ImportDeclaration";
3197         SyntaxKind[SyntaxKind["ImportClause"] = 255] = "ImportClause";
3198         SyntaxKind[SyntaxKind["NamespaceImport"] = 256] = "NamespaceImport";
3199         SyntaxKind[SyntaxKind["NamedImports"] = 257] = "NamedImports";
3200         SyntaxKind[SyntaxKind["ImportSpecifier"] = 258] = "ImportSpecifier";
3201         SyntaxKind[SyntaxKind["ExportAssignment"] = 259] = "ExportAssignment";
3202         SyntaxKind[SyntaxKind["ExportDeclaration"] = 260] = "ExportDeclaration";
3203         SyntaxKind[SyntaxKind["NamedExports"] = 261] = "NamedExports";
3204         SyntaxKind[SyntaxKind["NamespaceExport"] = 262] = "NamespaceExport";
3205         SyntaxKind[SyntaxKind["ExportSpecifier"] = 263] = "ExportSpecifier";
3206         SyntaxKind[SyntaxKind["MissingDeclaration"] = 264] = "MissingDeclaration";
3207         // Module references
3208         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 265] = "ExternalModuleReference";
3209         // JSX
3210         SyntaxKind[SyntaxKind["JsxElement"] = 266] = "JsxElement";
3211         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 267] = "JsxSelfClosingElement";
3212         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 268] = "JsxOpeningElement";
3213         SyntaxKind[SyntaxKind["JsxClosingElement"] = 269] = "JsxClosingElement";
3214         SyntaxKind[SyntaxKind["JsxFragment"] = 270] = "JsxFragment";
3215         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 271] = "JsxOpeningFragment";
3216         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 272] = "JsxClosingFragment";
3217         SyntaxKind[SyntaxKind["JsxAttribute"] = 273] = "JsxAttribute";
3218         SyntaxKind[SyntaxKind["JsxAttributes"] = 274] = "JsxAttributes";
3219         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 275] = "JsxSpreadAttribute";
3220         SyntaxKind[SyntaxKind["JsxExpression"] = 276] = "JsxExpression";
3221         // Clauses
3222         SyntaxKind[SyntaxKind["CaseClause"] = 277] = "CaseClause";
3223         SyntaxKind[SyntaxKind["DefaultClause"] = 278] = "DefaultClause";
3224         SyntaxKind[SyntaxKind["HeritageClause"] = 279] = "HeritageClause";
3225         SyntaxKind[SyntaxKind["CatchClause"] = 280] = "CatchClause";
3226         // Property assignments
3227         SyntaxKind[SyntaxKind["PropertyAssignment"] = 281] = "PropertyAssignment";
3228         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 282] = "ShorthandPropertyAssignment";
3229         SyntaxKind[SyntaxKind["SpreadAssignment"] = 283] = "SpreadAssignment";
3230         // Enum
3231         SyntaxKind[SyntaxKind["EnumMember"] = 284] = "EnumMember";
3232         // Unparsed
3233         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 285] = "UnparsedPrologue";
3234         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 286] = "UnparsedPrepend";
3235         SyntaxKind[SyntaxKind["UnparsedText"] = 287] = "UnparsedText";
3236         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 288] = "UnparsedInternalText";
3237         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 289] = "UnparsedSyntheticReference";
3238         // Top-level nodes
3239         SyntaxKind[SyntaxKind["SourceFile"] = 290] = "SourceFile";
3240         SyntaxKind[SyntaxKind["Bundle"] = 291] = "Bundle";
3241         SyntaxKind[SyntaxKind["UnparsedSource"] = 292] = "UnparsedSource";
3242         SyntaxKind[SyntaxKind["InputFiles"] = 293] = "InputFiles";
3243         // JSDoc nodes
3244         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 294] = "JSDocTypeExpression";
3245         // The * type
3246         SyntaxKind[SyntaxKind["JSDocAllType"] = 295] = "JSDocAllType";
3247         // The ? type
3248         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 296] = "JSDocUnknownType";
3249         SyntaxKind[SyntaxKind["JSDocNullableType"] = 297] = "JSDocNullableType";
3250         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 298] = "JSDocNonNullableType";
3251         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 299] = "JSDocOptionalType";
3252         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 300] = "JSDocFunctionType";
3253         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 301] = "JSDocVariadicType";
3254         // https://jsdoc.app/about-namepaths.html
3255         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 302] = "JSDocNamepathType";
3256         SyntaxKind[SyntaxKind["JSDocComment"] = 303] = "JSDocComment";
3257         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 304] = "JSDocTypeLiteral";
3258         SyntaxKind[SyntaxKind["JSDocSignature"] = 305] = "JSDocSignature";
3259         SyntaxKind[SyntaxKind["JSDocTag"] = 306] = "JSDocTag";
3260         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 307] = "JSDocAugmentsTag";
3261         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 308] = "JSDocImplementsTag";
3262         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 309] = "JSDocAuthorTag";
3263         SyntaxKind[SyntaxKind["JSDocClassTag"] = 310] = "JSDocClassTag";
3264         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 311] = "JSDocPublicTag";
3265         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 312] = "JSDocPrivateTag";
3266         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 313] = "JSDocProtectedTag";
3267         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 314] = "JSDocReadonlyTag";
3268         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 315] = "JSDocCallbackTag";
3269         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 316] = "JSDocEnumTag";
3270         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 317] = "JSDocParameterTag";
3271         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 318] = "JSDocReturnTag";
3272         SyntaxKind[SyntaxKind["JSDocThisTag"] = 319] = "JSDocThisTag";
3273         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 320] = "JSDocTypeTag";
3274         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 321] = "JSDocTemplateTag";
3275         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 322] = "JSDocTypedefTag";
3276         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 323] = "JSDocPropertyTag";
3277         // Synthesized list
3278         SyntaxKind[SyntaxKind["SyntaxList"] = 324] = "SyntaxList";
3279         // Transformation nodes
3280         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 325] = "NotEmittedStatement";
3281         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 326] = "PartiallyEmittedExpression";
3282         SyntaxKind[SyntaxKind["CommaListExpression"] = 327] = "CommaListExpression";
3283         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 328] = "MergeDeclarationMarker";
3284         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 329] = "EndOfDeclarationMarker";
3285         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 330] = "SyntheticReferenceExpression";
3286         // Enum value count
3287         SyntaxKind[SyntaxKind["Count"] = 331] = "Count";
3288         // Markers
3289         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
3290         SyntaxKind[SyntaxKind["LastAssignment"] = 74] = "LastAssignment";
3291         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
3292         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 74] = "LastCompoundAssignment";
3293         SyntaxKind[SyntaxKind["FirstReservedWord"] = 77] = "FirstReservedWord";
3294         SyntaxKind[SyntaxKind["LastReservedWord"] = 112] = "LastReservedWord";
3295         SyntaxKind[SyntaxKind["FirstKeyword"] = 77] = "FirstKeyword";
3296         SyntaxKind[SyntaxKind["LastKeyword"] = 152] = "LastKeyword";
3297         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 113] = "FirstFutureReservedWord";
3298         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 121] = "LastFutureReservedWord";
3299         SyntaxKind[SyntaxKind["FirstTypeNode"] = 168] = "FirstTypeNode";
3300         SyntaxKind[SyntaxKind["LastTypeNode"] = 188] = "LastTypeNode";
3301         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
3302         SyntaxKind[SyntaxKind["LastPunctuation"] = 74] = "LastPunctuation";
3303         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
3304         SyntaxKind[SyntaxKind["LastToken"] = 152] = "LastToken";
3305         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
3306         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
3307         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
3308         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
3309         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
3310         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
3311         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
3312         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 74] = "LastBinaryOperator";
3313         SyntaxKind[SyntaxKind["FirstStatement"] = 225] = "FirstStatement";
3314         SyntaxKind[SyntaxKind["LastStatement"] = 241] = "LastStatement";
3315         SyntaxKind[SyntaxKind["FirstNode"] = 153] = "FirstNode";
3316         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 294] = "FirstJSDocNode";
3317         SyntaxKind[SyntaxKind["LastJSDocNode"] = 323] = "LastJSDocNode";
3318         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 306] = "FirstJSDocTagNode";
3319         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 323] = "LastJSDocTagNode";
3320         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 122] = "FirstContextualKeyword";
3321         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 152] = "LastContextualKeyword";
3322     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
3323     var NodeFlags;
3324     (function (NodeFlags) {
3325         NodeFlags[NodeFlags["None"] = 0] = "None";
3326         NodeFlags[NodeFlags["Let"] = 1] = "Let";
3327         NodeFlags[NodeFlags["Const"] = 2] = "Const";
3328         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
3329         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
3330         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
3331         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
3332         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
3333         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
3334         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
3335         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
3336         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
3337         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
3338         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
3339         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
3340         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
3341         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
3342         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
3343         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
3344         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
3345         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
3346         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
3347         // walking the tree if the flags are not set. However, these flags are just a approximation
3348         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
3349         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
3350         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
3351         // However, the removal operation should not occur often and in the case of the
3352         // removal, it is likely that users will add the import anyway.
3353         // The advantage of this approach is its simplicity. For the case of batch compilation,
3354         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
3355         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
3356         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
3357         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
3358         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
3359         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
3360         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
3361         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
3362         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
3363         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
3364         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
3365         // Parsing context flags
3366         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
3367         // Exclude these flags when parsing a Type
3368         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
3369         // Represents all flags that are potentially set once and
3370         // never cleared on SourceFiles which get re-used in between incremental parses.
3371         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
3372         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
3373     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
3374     var ModifierFlags;
3375     (function (ModifierFlags) {
3376         ModifierFlags[ModifierFlags["None"] = 0] = "None";
3377         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
3378         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
3379         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
3380         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
3381         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
3382         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
3383         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
3384         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
3385         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
3386         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
3387         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
3388         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
3389         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
3390         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
3391         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
3392         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
3393         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
3394         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
3395         ModifierFlags[ModifierFlags["All"] = 3071] = "All";
3396     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
3397     var JsxFlags;
3398     (function (JsxFlags) {
3399         JsxFlags[JsxFlags["None"] = 0] = "None";
3400         /** An element from a named property of the JSX.IntrinsicElements interface */
3401         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
3402         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
3403         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
3404         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
3405     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
3406     /* @internal */
3407     var RelationComparisonResult;
3408     (function (RelationComparisonResult) {
3409         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
3410         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
3411         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
3412         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
3413         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
3414         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
3415     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
3416     /*@internal*/
3417     var GeneratedIdentifierFlags;
3418     (function (GeneratedIdentifierFlags) {
3419         // Kinds
3420         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
3421         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
3422         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
3423         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
3424         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
3425         GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
3426         // Flags
3427         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
3428         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
3429         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
3430     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
3431     var TokenFlags;
3432     (function (TokenFlags) {
3433         TokenFlags[TokenFlags["None"] = 0] = "None";
3434         /* @internal */
3435         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
3436         /* @internal */
3437         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
3438         /* @internal */
3439         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
3440         /* @internal */
3441         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
3442         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
3443         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
3444         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
3445         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
3446         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
3447         /* @internal */
3448         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
3449         /* @internal */
3450         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
3451         /* @internal */
3452         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
3453         /* @internal */
3454         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
3455         /* @internal */
3456         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
3457     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
3458     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
3459     var FlowFlags;
3460     (function (FlowFlags) {
3461         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
3462         FlowFlags[FlowFlags["Start"] = 2] = "Start";
3463         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
3464         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
3465         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
3466         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
3467         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
3468         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
3469         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
3470         FlowFlags[FlowFlags["Call"] = 512] = "Call";
3471         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
3472         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
3473         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
3474         FlowFlags[FlowFlags["Label"] = 12] = "Label";
3475         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
3476     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
3477     /* @internal */
3478     var CommentDirectiveType;
3479     (function (CommentDirectiveType) {
3480         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
3481         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
3482     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
3483     var OperationCanceledException = /** @class */ (function () {
3484         function OperationCanceledException() {
3485         }
3486         return OperationCanceledException;
3487     }());
3488     ts.OperationCanceledException = OperationCanceledException;
3489     /*@internal*/
3490     var RefFileKind;
3491     (function (RefFileKind) {
3492         RefFileKind[RefFileKind["Import"] = 0] = "Import";
3493         RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
3494         RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
3495     })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
3496     /* @internal */
3497     var StructureIsReused;
3498     (function (StructureIsReused) {
3499         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
3500         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
3501         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
3502     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
3503     /** Return code used by getEmitOutput function to indicate status of the function */
3504     var ExitStatus;
3505     (function (ExitStatus) {
3506         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
3507         // when -version or -help was provided, or this was a normal compilation, no diagnostics
3508         // were produced, and all outputs were generated successfully.
3509         ExitStatus[ExitStatus["Success"] = 0] = "Success";
3510         // Diagnostics were produced and because of them no code was generated.
3511         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
3512         // Diagnostics were produced and outputs were generated in spite of them.
3513         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
3514         // When build skipped because passed in project is invalid
3515         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
3516         // When build is skipped because project references form cycle
3517         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
3518         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
3519         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
3520     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
3521     /* @internal */
3522     var UnionReduction;
3523     (function (UnionReduction) {
3524         UnionReduction[UnionReduction["None"] = 0] = "None";
3525         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
3526         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
3527     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
3528     /* @internal */
3529     var ContextFlags;
3530     (function (ContextFlags) {
3531         ContextFlags[ContextFlags["None"] = 0] = "None";
3532         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
3533         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
3534         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
3535     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
3536     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
3537     var NodeBuilderFlags;
3538     (function (NodeBuilderFlags) {
3539         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
3540         // Options
3541         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
3542         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3543         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
3544         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3545         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
3546         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3547         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3548         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
3549         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3550         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
3551         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3552         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3553         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3554         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3555         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3556         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3557         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3558         // Error handling
3559         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
3560         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
3561         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
3562         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
3563         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
3564         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3565         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
3566         // Errors (cont.)
3567         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
3568         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
3569         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
3570         // State
3571         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
3572         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3573         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
3574         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
3575     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
3576     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
3577     var TypeFormatFlags;
3578     (function (TypeFormatFlags) {
3579         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
3580         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
3581         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
3582         // hole because there's a hole in node builder flags
3583         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
3584         // hole because there's a hole in node builder flags
3585         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
3586         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
3587         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
3588         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
3589         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
3590         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
3591         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
3592         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
3593         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
3594         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
3595         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
3596         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
3597         // Error Handling
3598         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
3599         // TypeFormatFlags exclusive
3600         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
3601         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
3602         // State
3603         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
3604         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
3605         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
3606         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
3607         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
3608         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
3609     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
3610     var SymbolFormatFlags;
3611     (function (SymbolFormatFlags) {
3612         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
3613         // Write symbols's type argument if it is instantiated symbol
3614         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
3615         //     var a: C<number>;
3616         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
3617         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
3618         // Use only external alias information to get the symbol name in the given context
3619         // eg.  module m { export class c { } } import x = m.c;
3620         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
3621         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
3622         // Build symbol name using any nodes needed, instead of just components of an entity name
3623         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
3624         // Prefer aliases which are not directly visible
3625         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
3626         // Skip building an accessible symbol chain
3627         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
3628     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
3629     /* @internal */
3630     var SymbolAccessibility;
3631     (function (SymbolAccessibility) {
3632         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
3633         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
3634         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
3635     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
3636     /* @internal */
3637     var SyntheticSymbolKind;
3638     (function (SyntheticSymbolKind) {
3639         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
3640         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
3641     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
3642     var TypePredicateKind;
3643     (function (TypePredicateKind) {
3644         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
3645         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
3646         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
3647         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
3648     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
3649     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
3650     /* @internal */
3651     var TypeReferenceSerializationKind;
3652     (function (TypeReferenceSerializationKind) {
3653         // The TypeReferenceNode could not be resolved.
3654         // The type name should be emitted using a safe fallback.
3655         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
3656         // The TypeReferenceNode resolves to a type with a constructor
3657         // function that can be reached at runtime (e.g. a `class`
3658         // declaration or a `var` declaration for the static side
3659         // of a type, such as the global `Promise` type in lib.d.ts).
3660         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
3661         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
3662         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
3663         // The TypeReferenceNode resolves to a Number-like type.
3664         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
3665         // The TypeReferenceNode resolves to a BigInt-like type.
3666         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
3667         // The TypeReferenceNode resolves to a String-like type.
3668         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
3669         // The TypeReferenceNode resolves to a Boolean-like type.
3670         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
3671         // The TypeReferenceNode resolves to an Array-like type.
3672         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
3673         // The TypeReferenceNode resolves to the ESSymbol type.
3674         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
3675         // The TypeReferenceNode resolved to the global Promise constructor symbol.
3676         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
3677         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
3678         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
3679         // The TypeReferenceNode resolves to any other type.
3680         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
3681     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
3682     var SymbolFlags;
3683     (function (SymbolFlags) {
3684         SymbolFlags[SymbolFlags["None"] = 0] = "None";
3685         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
3686         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
3687         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
3688         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
3689         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
3690         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
3691         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
3692         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
3693         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
3694         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
3695         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
3696         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
3697         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
3698         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
3699         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
3700         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
3701         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
3702         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
3703         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
3704         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
3705         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
3706         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
3707         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
3708         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
3709         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
3710         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
3711         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
3712         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
3713         /* @internal */
3714         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
3715         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
3716         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
3717         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
3718         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
3719         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
3720         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
3721         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
3722         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
3723         // same name, or any other value that is not a variable, e.g. ValueModule or Class
3724         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
3725         // Block-scoped declarations are not allowed to be re-declared
3726         // they can not merge with anything in the value space
3727         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
3728         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
3729         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
3730         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
3731         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
3732         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
3733         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
3734         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
3735         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
3736         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
3737         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
3738         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
3739         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
3740         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
3741         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
3742         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
3743         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
3744         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
3745         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
3746         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
3747         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
3748         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
3749         /* @internal */
3750         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
3751         /* @internal */
3752         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
3753         /* @internal */
3754         // The set of things we consider semantically classifiable.  Used to speed up the LS during
3755         // classification.
3756         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
3757         /* @internal */
3758         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
3759     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
3760     /* @internal */
3761     var EnumKind;
3762     (function (EnumKind) {
3763         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
3764         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
3765     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
3766     /* @internal */
3767     var CheckFlags;
3768     (function (CheckFlags) {
3769         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
3770         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
3771         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
3772         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
3773         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
3774         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
3775         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
3776         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
3777         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
3778         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
3779         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
3780         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
3781         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
3782         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
3783         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
3784         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
3785         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
3786         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
3787         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
3788         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
3789         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
3790         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
3791         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
3792     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
3793     var InternalSymbolName;
3794     (function (InternalSymbolName) {
3795         InternalSymbolName["Call"] = "__call";
3796         InternalSymbolName["Constructor"] = "__constructor";
3797         InternalSymbolName["New"] = "__new";
3798         InternalSymbolName["Index"] = "__index";
3799         InternalSymbolName["ExportStar"] = "__export";
3800         InternalSymbolName["Global"] = "__global";
3801         InternalSymbolName["Missing"] = "__missing";
3802         InternalSymbolName["Type"] = "__type";
3803         InternalSymbolName["Object"] = "__object";
3804         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
3805         InternalSymbolName["Class"] = "__class";
3806         InternalSymbolName["Function"] = "__function";
3807         InternalSymbolName["Computed"] = "__computed";
3808         InternalSymbolName["Resolving"] = "__resolving__";
3809         InternalSymbolName["ExportEquals"] = "export=";
3810         InternalSymbolName["Default"] = "default";
3811         InternalSymbolName["This"] = "this";
3812     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
3813     /* @internal */
3814     var NodeCheckFlags;
3815     (function (NodeCheckFlags) {
3816         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
3817         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
3818         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
3819         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
3820         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
3821         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
3822         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
3823         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
3824         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
3825         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
3826         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
3827         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
3828         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
3829         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
3830         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
3831         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
3832         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
3833         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
3834         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
3835         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
3836         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
3837         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
3838         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
3839     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
3840     var TypeFlags;
3841     (function (TypeFlags) {
3842         TypeFlags[TypeFlags["Any"] = 1] = "Any";
3843         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
3844         TypeFlags[TypeFlags["String"] = 4] = "String";
3845         TypeFlags[TypeFlags["Number"] = 8] = "Number";
3846         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
3847         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
3848         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
3849         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
3850         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
3851         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
3852         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
3853         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
3854         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
3855         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
3856         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
3857         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
3858         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
3859         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
3860         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
3861         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
3862         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
3863         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
3864         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
3865         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
3866         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
3867         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
3868         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
3869         /* @internal */
3870         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
3871         /* @internal */
3872         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
3873         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
3874         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
3875         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
3876         /* @internal */
3877         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
3878         /* @internal */
3879         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
3880         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
3881         /* @internal */
3882         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
3883         /* @internal */
3884         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
3885         TypeFlags[TypeFlags["StringLike"] = 132] = "StringLike";
3886         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
3887         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
3888         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
3889         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
3890         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
3891         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
3892         /* @internal */
3893         TypeFlags[TypeFlags["DisjointDomains"] = 67238908] = "DisjointDomains";
3894         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
3895         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
3896         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
3897         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
3898         TypeFlags[TypeFlags["InstantiablePrimitive"] = 4194304] = "InstantiablePrimitive";
3899         TypeFlags[TypeFlags["Instantiable"] = 63176704] = "Instantiable";
3900         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 66846720] = "StructuredOrInstantiable";
3901         /* @internal */
3902         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
3903         /* @internal */
3904         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
3905         /* @internal */
3906         TypeFlags[TypeFlags["Substructure"] = 66584576] = "Substructure";
3907         // 'Narrowable' types are types where narrowing actually narrows.
3908         // This *should* be every type other than null, undefined, void, and never
3909         TypeFlags[TypeFlags["Narrowable"] = 133970943] = "Narrowable";
3910         TypeFlags[TypeFlags["NotUnionOrUnit"] = 67637251] = "NotUnionOrUnit";
3911         /* @internal */
3912         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 66994211] = "NotPrimitiveUnion";
3913         // The following flags are aggregated during union and intersection type construction
3914         /* @internal */
3915         TypeFlags[TypeFlags["IncludesMask"] = 71041023] = "IncludesMask";
3916         // The following flags are used for different purposes during union and intersection type construction
3917         /* @internal */
3918         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
3919         /* @internal */
3920         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
3921         /* @internal */
3922         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
3923         /* @internal */
3924         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
3925     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
3926     var ObjectFlags;
3927     (function (ObjectFlags) {
3928         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
3929         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
3930         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
3931         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
3932         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
3933         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
3934         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
3935         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
3936         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
3937         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
3938         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
3939         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
3940         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
3941         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
3942         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
3943         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
3944         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
3945         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
3946         /* @internal */
3947         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
3948         /* @internal */
3949         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
3950         /* @internal */
3951         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
3952         /* @internal */
3953         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
3954         /* @internal */
3955         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
3956         /* @internal */
3957         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
3958         /* @internal */
3959         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
3960         /* @internal */
3961         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
3962         /* @internal */
3963         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
3964         /* @internal */
3965         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
3966         /* @internal */
3967         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
3968         /* @internal */
3969         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
3970         /* @internal */
3971         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
3972         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
3973         /* @internal */
3974         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
3975         /* @internal */
3976         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
3977     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
3978     /* @internal */
3979     var VarianceFlags;
3980     (function (VarianceFlags) {
3981         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
3982         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
3983         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
3984         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
3985         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
3986         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
3987         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
3988         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
3989         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
3990     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
3991     /* @internal */
3992     var JsxReferenceKind;
3993     (function (JsxReferenceKind) {
3994         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
3995         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
3996         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
3997     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
3998     var SignatureKind;
3999     (function (SignatureKind) {
4000         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4001         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4002     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4003     /* @internal */
4004     var SignatureFlags;
4005     (function (SignatureFlags) {
4006         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4007         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4008         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4009         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4010         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4011         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4012         // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4013         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4014         // instantiating the return type.
4015         SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags";
4016         SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4017     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4018     var IndexKind;
4019     (function (IndexKind) {
4020         IndexKind[IndexKind["String"] = 0] = "String";
4021         IndexKind[IndexKind["Number"] = 1] = "Number";
4022     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4023     /* @internal */
4024     var TypeMapKind;
4025     (function (TypeMapKind) {
4026         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4027         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4028         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4029         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4030         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4031     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4032     var InferencePriority;
4033     (function (InferencePriority) {
4034         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4035         InferencePriority[InferencePriority["HomomorphicMappedType"] = 2] = "HomomorphicMappedType";
4036         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 4] = "PartialHomomorphicMappedType";
4037         InferencePriority[InferencePriority["MappedTypeConstraint"] = 8] = "MappedTypeConstraint";
4038         InferencePriority[InferencePriority["ContravariantConditional"] = 16] = "ContravariantConditional";
4039         InferencePriority[InferencePriority["ReturnType"] = 32] = "ReturnType";
4040         InferencePriority[InferencePriority["LiteralKeyof"] = 64] = "LiteralKeyof";
4041         InferencePriority[InferencePriority["NoConstraints"] = 128] = "NoConstraints";
4042         InferencePriority[InferencePriority["AlwaysStrict"] = 256] = "AlwaysStrict";
4043         InferencePriority[InferencePriority["MaxValue"] = 512] = "MaxValue";
4044         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 104] = "PriorityImpliesCombination";
4045         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4046     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4047     /* @internal */
4048     var InferenceFlags;
4049     (function (InferenceFlags) {
4050         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4051         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4052         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4053         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4054     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4055     /**
4056      * Ternary values are defined such that
4057      * x & y is False if either x or y is False.
4058      * x & y is Maybe if either x or y is Maybe, but neither x or y is False.
4059      * x & y is True if both x and y are True.
4060      * x | y is False if both x and y are False.
4061      * x | y is Maybe if either x or y is Maybe, but neither x or y is True.
4062      * x | y is True if either x or y is True.
4063      */
4064     /* @internal */
4065     var Ternary;
4066     (function (Ternary) {
4067         Ternary[Ternary["False"] = 0] = "False";
4068         Ternary[Ternary["Maybe"] = 1] = "Maybe";
4069         Ternary[Ternary["True"] = -1] = "True";
4070     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4071     /* @internal */
4072     var AssignmentDeclarationKind;
4073     (function (AssignmentDeclarationKind) {
4074         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4075         /// exports.name = expr
4076         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4077         /// module.exports = expr
4078         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4079         /// className.prototype.name = expr
4080         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4081         /// this.name = expr
4082         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4083         // F.name = expr
4084         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4085         // F.prototype = { ... }
4086         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4087         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4088         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4089         // Object.defineProperty(x, 'name', { get: Function });
4090         // Object.defineProperty(x, 'name', { set: Function });
4091         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4092         // Object.defineProperty(exports || module.exports, 'name', ...);
4093         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4094         // Object.defineProperty(Foo.prototype, 'name', ...);
4095         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4096     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4097     var DiagnosticCategory;
4098     (function (DiagnosticCategory) {
4099         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4100         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4101         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4102         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4103     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4104     /* @internal */
4105     function diagnosticCategoryName(d, lowerCase) {
4106         if (lowerCase === void 0) { lowerCase = true; }
4107         var name = DiagnosticCategory[d.category];
4108         return lowerCase ? name.toLowerCase() : name;
4109     }
4110     ts.diagnosticCategoryName = diagnosticCategoryName;
4111     var ModuleResolutionKind;
4112     (function (ModuleResolutionKind) {
4113         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4114         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4115     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4116     var WatchFileKind;
4117     (function (WatchFileKind) {
4118         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4119         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4120         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4121         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4122         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4123     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4124     var WatchDirectoryKind;
4125     (function (WatchDirectoryKind) {
4126         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4127         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4128         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4129     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4130     var PollingWatchKind;
4131     (function (PollingWatchKind) {
4132         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4133         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4134         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4135     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4136     var ModuleKind;
4137     (function (ModuleKind) {
4138         ModuleKind[ModuleKind["None"] = 0] = "None";
4139         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4140         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4141         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4142         ModuleKind[ModuleKind["System"] = 4] = "System";
4143         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4144         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4145         //       module kind).
4146         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4147         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4148         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4149     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4150     var JsxEmit;
4151     (function (JsxEmit) {
4152         JsxEmit[JsxEmit["None"] = 0] = "None";
4153         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4154         JsxEmit[JsxEmit["React"] = 2] = "React";
4155         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4156     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4157     var ImportsNotUsedAsValues;
4158     (function (ImportsNotUsedAsValues) {
4159         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4160         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4161         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4162     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4163     var NewLineKind;
4164     (function (NewLineKind) {
4165         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4166         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4167     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4168     var ScriptKind;
4169     (function (ScriptKind) {
4170         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4171         ScriptKind[ScriptKind["JS"] = 1] = "JS";
4172         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4173         ScriptKind[ScriptKind["TS"] = 3] = "TS";
4174         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4175         ScriptKind[ScriptKind["External"] = 5] = "External";
4176         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4177         /**
4178          * Used on extensions that doesn't define the ScriptKind but the content defines it.
4179          * Deferred extensions are going to be included in all project contexts.
4180          */
4181         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4182     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4183     var ScriptTarget;
4184     (function (ScriptTarget) {
4185         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4186         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4187         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4188         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4189         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4190         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4191         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4192         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4193         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4194         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4195         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4196     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4197     var LanguageVariant;
4198     (function (LanguageVariant) {
4199         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4200         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4201     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4202     var WatchDirectoryFlags;
4203     (function (WatchDirectoryFlags) {
4204         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4205         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4206     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4207     /* @internal */
4208     var CharacterCodes;
4209     (function (CharacterCodes) {
4210         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4211         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4212         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4213         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
4214         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
4215         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
4216         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
4217         // Unicode 3.0 space characters
4218         CharacterCodes[CharacterCodes["space"] = 32] = "space";
4219         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
4220         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
4221         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
4222         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
4223         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
4224         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
4225         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
4226         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
4227         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
4228         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
4229         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
4230         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
4231         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
4232         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
4233         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
4234         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
4235         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
4236         CharacterCodes[CharacterCodes["_"] = 95] = "_";
4237         CharacterCodes[CharacterCodes["$"] = 36] = "$";
4238         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
4239         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
4240         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
4241         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
4242         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
4243         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
4244         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
4245         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
4246         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
4247         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
4248         CharacterCodes[CharacterCodes["a"] = 97] = "a";
4249         CharacterCodes[CharacterCodes["b"] = 98] = "b";
4250         CharacterCodes[CharacterCodes["c"] = 99] = "c";
4251         CharacterCodes[CharacterCodes["d"] = 100] = "d";
4252         CharacterCodes[CharacterCodes["e"] = 101] = "e";
4253         CharacterCodes[CharacterCodes["f"] = 102] = "f";
4254         CharacterCodes[CharacterCodes["g"] = 103] = "g";
4255         CharacterCodes[CharacterCodes["h"] = 104] = "h";
4256         CharacterCodes[CharacterCodes["i"] = 105] = "i";
4257         CharacterCodes[CharacterCodes["j"] = 106] = "j";
4258         CharacterCodes[CharacterCodes["k"] = 107] = "k";
4259         CharacterCodes[CharacterCodes["l"] = 108] = "l";
4260         CharacterCodes[CharacterCodes["m"] = 109] = "m";
4261         CharacterCodes[CharacterCodes["n"] = 110] = "n";
4262         CharacterCodes[CharacterCodes["o"] = 111] = "o";
4263         CharacterCodes[CharacterCodes["p"] = 112] = "p";
4264         CharacterCodes[CharacterCodes["q"] = 113] = "q";
4265         CharacterCodes[CharacterCodes["r"] = 114] = "r";
4266         CharacterCodes[CharacterCodes["s"] = 115] = "s";
4267         CharacterCodes[CharacterCodes["t"] = 116] = "t";
4268         CharacterCodes[CharacterCodes["u"] = 117] = "u";
4269         CharacterCodes[CharacterCodes["v"] = 118] = "v";
4270         CharacterCodes[CharacterCodes["w"] = 119] = "w";
4271         CharacterCodes[CharacterCodes["x"] = 120] = "x";
4272         CharacterCodes[CharacterCodes["y"] = 121] = "y";
4273         CharacterCodes[CharacterCodes["z"] = 122] = "z";
4274         CharacterCodes[CharacterCodes["A"] = 65] = "A";
4275         CharacterCodes[CharacterCodes["B"] = 66] = "B";
4276         CharacterCodes[CharacterCodes["C"] = 67] = "C";
4277         CharacterCodes[CharacterCodes["D"] = 68] = "D";
4278         CharacterCodes[CharacterCodes["E"] = 69] = "E";
4279         CharacterCodes[CharacterCodes["F"] = 70] = "F";
4280         CharacterCodes[CharacterCodes["G"] = 71] = "G";
4281         CharacterCodes[CharacterCodes["H"] = 72] = "H";
4282         CharacterCodes[CharacterCodes["I"] = 73] = "I";
4283         CharacterCodes[CharacterCodes["J"] = 74] = "J";
4284         CharacterCodes[CharacterCodes["K"] = 75] = "K";
4285         CharacterCodes[CharacterCodes["L"] = 76] = "L";
4286         CharacterCodes[CharacterCodes["M"] = 77] = "M";
4287         CharacterCodes[CharacterCodes["N"] = 78] = "N";
4288         CharacterCodes[CharacterCodes["O"] = 79] = "O";
4289         CharacterCodes[CharacterCodes["P"] = 80] = "P";
4290         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
4291         CharacterCodes[CharacterCodes["R"] = 82] = "R";
4292         CharacterCodes[CharacterCodes["S"] = 83] = "S";
4293         CharacterCodes[CharacterCodes["T"] = 84] = "T";
4294         CharacterCodes[CharacterCodes["U"] = 85] = "U";
4295         CharacterCodes[CharacterCodes["V"] = 86] = "V";
4296         CharacterCodes[CharacterCodes["W"] = 87] = "W";
4297         CharacterCodes[CharacterCodes["X"] = 88] = "X";
4298         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
4299         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
4300         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
4301         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
4302         CharacterCodes[CharacterCodes["at"] = 64] = "at";
4303         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
4304         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
4305         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
4306         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
4307         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
4308         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
4309         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
4310         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
4311         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
4312         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
4313         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
4314         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
4315         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
4316         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
4317         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
4318         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
4319         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
4320         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
4321         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
4322         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
4323         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
4324         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
4325         CharacterCodes[CharacterCodes["question"] = 63] = "question";
4326         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
4327         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
4328         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
4329         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
4330         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
4331         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
4332         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
4333         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
4334         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
4335     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
4336     var Extension;
4337     (function (Extension) {
4338         Extension["Ts"] = ".ts";
4339         Extension["Tsx"] = ".tsx";
4340         Extension["Dts"] = ".d.ts";
4341         Extension["Js"] = ".js";
4342         Extension["Jsx"] = ".jsx";
4343         Extension["Json"] = ".json";
4344         Extension["TsBuildInfo"] = ".tsbuildinfo";
4345     })(Extension = ts.Extension || (ts.Extension = {}));
4346     /* @internal */
4347     var TransformFlags;
4348     (function (TransformFlags) {
4349         TransformFlags[TransformFlags["None"] = 0] = "None";
4350         // Facts
4351         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
4352         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
4353         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
4354         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
4355         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
4356         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
4357         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
4358         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
4359         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
4360         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
4361         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
4362         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
4363         // Markers
4364         // - Flags used to indicate that a subtree contains a specific transformation.
4365         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
4366         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
4367         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
4368         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
4369         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
4370         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
4371         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
4372         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
4373         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
4374         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
4375         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
4376         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
4377         // Please leave this as 1 << 29.
4378         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
4379         // It is a good reminder of how much room we have left
4380         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4381         // Assertions
4382         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
4383         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
4384         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
4385         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
4386         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
4387         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
4388         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
4389         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
4390         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
4391         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
4392         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
4393         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
4394         // Scope Exclusions
4395         // - Bitmasks that exclude flags from propagating out of a specific context
4396         //   into the subtree flags of their container.
4397         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
4398         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
4399         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
4400         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 538920960] = "ArrowFunctionExcludes";
4401         TransformFlags[TransformFlags["FunctionExcludes"] = 538925056] = "FunctionExcludes";
4402         TransformFlags[TransformFlags["ConstructorExcludes"] = 538923008] = "ConstructorExcludes";
4403         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
4404         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
4405         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
4406         TransformFlags[TransformFlags["ModuleExcludes"] = 537991168] = "ModuleExcludes";
4407         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
4408         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
4409         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
4410         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
4411         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
4412         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
4413         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
4414         // Propagating flags
4415         // - Bitmasks for flags that should propagate from a child
4416         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
4417         // Masks
4418         // - Additional bitmasks
4419     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
4420     var EmitFlags;
4421     (function (EmitFlags) {
4422         EmitFlags[EmitFlags["None"] = 0] = "None";
4423         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
4424         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
4425         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
4426         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
4427         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
4428         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
4429         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
4430         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
4431         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
4432         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
4433         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
4434         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
4435         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
4436         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
4437         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
4438         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
4439         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
4440         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
4441         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
4442         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
4443         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
4444         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
4445         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
4446         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
4447         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
4448         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
4449         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
4450         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
4451         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
4452         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
4453         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
4454     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
4455     /**
4456      * Used by the checker, this enum keeps track of external emit helpers that should be type
4457      * checked.
4458      */
4459     /* @internal */
4460     var ExternalEmitHelpers;
4461     (function (ExternalEmitHelpers) {
4462         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
4463         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
4464         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
4465         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
4466         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
4467         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
4468         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
4469         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
4470         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
4471         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
4472         ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
4473         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
4474         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
4475         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
4476         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
4477         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
4478         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
4479         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 131072] = "MakeTemplateObject";
4480         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 262144] = "ClassPrivateFieldGet";
4481         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 524288] = "ClassPrivateFieldSet";
4482         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 1048576] = "CreateBinding";
4483         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
4484         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 1048576] = "LastEmitHelper";
4485         // Helpers included by ES2015 for..of
4486         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
4487         // Helpers included by ES2017 for..await..of
4488         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
4489         // Helpers included by ES2017 async generators
4490         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
4491         // Helpers included by yield* in ES2017 async generators
4492         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
4493         // Helpers included by ES2015 spread
4494         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
4495     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
4496     var EmitHint;
4497     (function (EmitHint) {
4498         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
4499         EmitHint[EmitHint["Expression"] = 1] = "Expression";
4500         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
4501         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
4502         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
4503         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
4504         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
4505     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
4506     /* @internal */
4507     var LexicalEnvironmentFlags;
4508     (function (LexicalEnvironmentFlags) {
4509         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
4510         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
4511         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
4512     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
4513     /*@internal*/
4514     var BundleFileSectionKind;
4515     (function (BundleFileSectionKind) {
4516         BundleFileSectionKind["Prologue"] = "prologue";
4517         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
4518         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
4519         BundleFileSectionKind["Reference"] = "reference";
4520         BundleFileSectionKind["Type"] = "type";
4521         BundleFileSectionKind["Lib"] = "lib";
4522         BundleFileSectionKind["Prepend"] = "prepend";
4523         BundleFileSectionKind["Text"] = "text";
4524         BundleFileSectionKind["Internal"] = "internal";
4525         // comments?
4526     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
4527     var ListFormat;
4528     (function (ListFormat) {
4529         ListFormat[ListFormat["None"] = 0] = "None";
4530         // Line separators
4531         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
4532         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
4533         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
4534         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
4535         // Delimiters
4536         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
4537         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
4538         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
4539         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
4540         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
4541         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
4542         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
4543         // Whitespace
4544         ListFormat[ListFormat["Indented"] = 128] = "Indented";
4545         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
4546         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
4547         // Brackets/Braces
4548         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
4549         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
4550         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
4551         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
4552         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
4553         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
4554         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
4555         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
4556         // Other
4557         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
4558         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
4559         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
4560         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
4561         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
4562         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
4563         // Precomputed Formats
4564         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
4565         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
4566         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
4567         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
4568         ListFormat[ListFormat["TupleTypeElements"] = 528] = "TupleTypeElements";
4569         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
4570         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
4571         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
4572         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
4573         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
4574         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
4575         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
4576         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
4577         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
4578         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
4579         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
4580         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
4581         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
4582         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
4583         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
4584         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
4585         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
4586         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
4587         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
4588         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
4589         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
4590         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
4591         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
4592         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
4593         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
4594         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
4595         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
4596         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
4597         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
4598         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
4599         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
4600         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
4601     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
4602     /* @internal */
4603     var PragmaKindFlags;
4604     (function (PragmaKindFlags) {
4605         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
4606         /**
4607          * Triple slash comment of the form
4608          * /// <pragma-name argname="value" />
4609          */
4610         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
4611         /**
4612          * Single line comment of the form
4613          * // @pragma-name argval1 argval2
4614          * or
4615          * /// @pragma-name argval1 argval2
4616          */
4617         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
4618         /**
4619          * Multiline non-jsdoc pragma of the form
4620          * /* @pragma-name argval1 argval2 * /
4621          */
4622         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
4623         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
4624         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
4625     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
4626     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
4627     //  fancy effectively defining it twice, once in value-space and once in type-space
4628     /* @internal */
4629     ts.commentPragmas = {
4630         "reference": {
4631             args: [
4632                 { name: "types", optional: true, captureSpan: true },
4633                 { name: "lib", optional: true, captureSpan: true },
4634                 { name: "path", optional: true, captureSpan: true },
4635                 { name: "no-default-lib", optional: true }
4636             ],
4637             kind: 1 /* TripleSlashXML */
4638         },
4639         "amd-dependency": {
4640             args: [{ name: "path" }, { name: "name", optional: true }],
4641             kind: 1 /* TripleSlashXML */
4642         },
4643         "amd-module": {
4644             args: [{ name: "name" }],
4645             kind: 1 /* TripleSlashXML */
4646         },
4647         "ts-check": {
4648             kind: 2 /* SingleLine */
4649         },
4650         "ts-nocheck": {
4651             kind: 2 /* SingleLine */
4652         },
4653         "jsx": {
4654             args: [{ name: "factory" }],
4655             kind: 4 /* MultiLine */
4656         },
4657     };
4658 })(ts || (ts = {}));
4659 var ts;
4660 (function (ts) {
4661     /**
4662      * djb2 hashing algorithm
4663      * http://www.cse.yorku.ca/~oz/hash.html
4664      */
4665     /* @internal */
4666     function generateDjb2Hash(data) {
4667         var acc = 5381;
4668         for (var i = 0; i < data.length; i++) {
4669             acc = ((acc << 5) + acc) + data.charCodeAt(i);
4670         }
4671         return acc.toString();
4672     }
4673     ts.generateDjb2Hash = generateDjb2Hash;
4674     /**
4675      * Set a high stack trace limit to provide more information in case of an error.
4676      * Called for command-line and server use cases.
4677      * Not called if TypeScript is used as a library.
4678      */
4679     /* @internal */
4680     function setStackTraceLimit() {
4681         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
4682             Error.stackTraceLimit = 100;
4683         }
4684     }
4685     ts.setStackTraceLimit = setStackTraceLimit;
4686     var FileWatcherEventKind;
4687     (function (FileWatcherEventKind) {
4688         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
4689         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
4690         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
4691     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
4692     /* @internal */
4693     var PollingInterval;
4694     (function (PollingInterval) {
4695         PollingInterval[PollingInterval["High"] = 2000] = "High";
4696         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
4697         PollingInterval[PollingInterval["Low"] = 250] = "Low";
4698     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
4699     /* @internal */
4700     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
4701     function createPollingIntervalBasedLevels(levels) {
4702         var _a;
4703         return _a = {},
4704             _a[PollingInterval.Low] = levels.Low,
4705             _a[PollingInterval.Medium] = levels.Medium,
4706             _a[PollingInterval.High] = levels.High,
4707             _a;
4708     }
4709     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
4710     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
4711     /* @internal */
4712     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
4713     /* @internal */
4714     function setCustomPollingValues(system) {
4715         if (!system.getEnvironmentVariable) {
4716             return;
4717         }
4718         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
4719         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
4720         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
4721         function getLevel(envVar, level) {
4722             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
4723         }
4724         function getCustomLevels(baseVariable) {
4725             var customLevels;
4726             setCustomLevel("Low");
4727             setCustomLevel("Medium");
4728             setCustomLevel("High");
4729             return customLevels;
4730             function setCustomLevel(level) {
4731                 var customLevel = getLevel(baseVariable, level);
4732                 if (customLevel) {
4733                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
4734                 }
4735             }
4736         }
4737         function setCustomLevels(baseVariable, levels) {
4738             var customLevels = getCustomLevels(baseVariable);
4739             if (customLevels) {
4740                 setLevel("Low");
4741                 setLevel("Medium");
4742                 setLevel("High");
4743                 return true;
4744             }
4745             return false;
4746             function setLevel(level) {
4747                 levels[level] = customLevels[level] || levels[level];
4748             }
4749         }
4750         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
4751             var customLevels = getCustomLevels(baseVariable);
4752             return (pollingIntervalChanged || customLevels) &&
4753                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
4754         }
4755     }
4756     ts.setCustomPollingValues = setCustomPollingValues;
4757     /* @internal */
4758     function createDynamicPriorityPollingWatchFile(host) {
4759         var watchedFiles = [];
4760         var changedFilesInLastPoll = [];
4761         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
4762         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
4763         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
4764         return watchFile;
4765         function watchFile(fileName, callback, defaultPollingInterval) {
4766             var file = {
4767                 fileName: fileName,
4768                 callback: callback,
4769                 unchangedPolls: 0,
4770                 mtime: getModifiedTime(fileName)
4771             };
4772             watchedFiles.push(file);
4773             addToPollingIntervalQueue(file, defaultPollingInterval);
4774             return {
4775                 close: function () {
4776                     file.isClosed = true;
4777                     // Remove from watchedFiles
4778                     ts.unorderedRemoveItem(watchedFiles, file);
4779                     // Do not update polling interval queue since that will happen as part of polling
4780                 }
4781             };
4782         }
4783         function createPollingIntervalQueue(pollingInterval) {
4784             var queue = [];
4785             queue.pollingInterval = pollingInterval;
4786             queue.pollIndex = 0;
4787             queue.pollScheduled = false;
4788             return queue;
4789         }
4790         function pollPollingIntervalQueue(queue) {
4791             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
4792             // Set the next polling index and timeout
4793             if (queue.length) {
4794                 scheduleNextPoll(queue.pollingInterval);
4795             }
4796             else {
4797                 ts.Debug.assert(queue.pollIndex === 0);
4798                 queue.pollScheduled = false;
4799             }
4800         }
4801         function pollLowPollingIntervalQueue(queue) {
4802             // Always poll complete list of changedFilesInLastPoll
4803             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
4804             // Finally do the actual polling of the queue
4805             pollPollingIntervalQueue(queue);
4806             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
4807             // as pollPollingIntervalQueue wont schedule for next poll
4808             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
4809                 scheduleNextPoll(PollingInterval.Low);
4810             }
4811         }
4812         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
4813             // Max visit would be all elements of the queue
4814             var needsVisit = queue.length;
4815             var definedValueCopyToIndex = pollIndex;
4816             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
4817                 var watchedFile = queue[pollIndex];
4818                 if (!watchedFile) {
4819                     continue;
4820                 }
4821                 else if (watchedFile.isClosed) {
4822                     queue[pollIndex] = undefined;
4823                     continue;
4824                 }
4825                 polled++;
4826                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
4827                 if (watchedFile.isClosed) {
4828                     // Closed watcher as part of callback
4829                     queue[pollIndex] = undefined;
4830                 }
4831                 else if (fileChanged) {
4832                     watchedFile.unchangedPolls = 0;
4833                     // Changed files go to changedFilesInLastPoll queue
4834                     if (queue !== changedFilesInLastPoll) {
4835                         queue[pollIndex] = undefined;
4836                         addChangedFileToLowPollingIntervalQueue(watchedFile);
4837                     }
4838                 }
4839                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
4840                     watchedFile.unchangedPolls++;
4841                 }
4842                 else if (queue === changedFilesInLastPoll) {
4843                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
4844                     watchedFile.unchangedPolls = 1;
4845                     queue[pollIndex] = undefined;
4846                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
4847                 }
4848                 else if (pollingInterval !== PollingInterval.High) {
4849                     watchedFile.unchangedPolls++;
4850                     queue[pollIndex] = undefined;
4851                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
4852                 }
4853                 if (queue[pollIndex]) {
4854                     // Copy this file to the non hole location
4855                     if (definedValueCopyToIndex < pollIndex) {
4856                         queue[definedValueCopyToIndex] = watchedFile;
4857                         queue[pollIndex] = undefined;
4858                     }
4859                     definedValueCopyToIndex++;
4860                 }
4861             }
4862             // Return next poll index
4863             return pollIndex;
4864             function nextPollIndex() {
4865                 pollIndex++;
4866                 if (pollIndex === queue.length) {
4867                     if (definedValueCopyToIndex < pollIndex) {
4868                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
4869                         queue.length = definedValueCopyToIndex;
4870                     }
4871                     pollIndex = 0;
4872                     definedValueCopyToIndex = 0;
4873                 }
4874             }
4875         }
4876         function pollingIntervalQueue(pollingInterval) {
4877             switch (pollingInterval) {
4878                 case PollingInterval.Low:
4879                     return lowPollingIntervalQueue;
4880                 case PollingInterval.Medium:
4881                     return mediumPollingIntervalQueue;
4882                 case PollingInterval.High:
4883                     return highPollingIntervalQueue;
4884             }
4885         }
4886         function addToPollingIntervalQueue(file, pollingInterval) {
4887             pollingIntervalQueue(pollingInterval).push(file);
4888             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
4889         }
4890         function addChangedFileToLowPollingIntervalQueue(file) {
4891             changedFilesInLastPoll.push(file);
4892             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
4893         }
4894         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
4895             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
4896                 scheduleNextPoll(pollingInterval);
4897             }
4898         }
4899         function scheduleNextPoll(pollingInterval) {
4900             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
4901         }
4902         function getModifiedTime(fileName) {
4903             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
4904         }
4905     }
4906     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
4907     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
4908         // One file can have multiple watchers
4909         var fileWatcherCallbacks = ts.createMultiMap();
4910         var dirWatchers = ts.createMap();
4911         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4912         return nonPollingWatchFile;
4913         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
4914             var filePath = toCanonicalName(fileName);
4915             fileWatcherCallbacks.add(filePath, callback);
4916             var dirPath = ts.getDirectoryPath(filePath) || ".";
4917             var watcher = dirWatchers.get(dirPath) ||
4918                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
4919             watcher.referenceCount++;
4920             return {
4921                 close: function () {
4922                     if (watcher.referenceCount === 1) {
4923                         watcher.close();
4924                         dirWatchers.delete(dirPath);
4925                     }
4926                     else {
4927                         watcher.referenceCount--;
4928                     }
4929                     fileWatcherCallbacks.remove(filePath, callback);
4930                 }
4931             };
4932         }
4933         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
4934             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
4935                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
4936                 if (!ts.isString(relativeFileName)) {
4937                     return;
4938                 }
4939                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
4940                 // Some applications save a working file via rename operations
4941                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
4942                 if (callbacks) {
4943                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
4944                         var fileCallback = callbacks_1[_i];
4945                         fileCallback(fileName, FileWatcherEventKind.Changed);
4946                     }
4947                 }
4948             }, 
4949             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
4950             watcher.referenceCount = 0;
4951             dirWatchers.set(dirPath, watcher);
4952             return watcher;
4953         }
4954     }
4955     /* @internal */
4956     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
4957         var cache = ts.createMap();
4958         var callbacksCache = ts.createMultiMap();
4959         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
4960         return function (fileName, callback, pollingInterval, options) {
4961             var path = toCanonicalFileName(fileName);
4962             var existing = cache.get(path);
4963             if (existing) {
4964                 existing.refCount++;
4965             }
4966             else {
4967                 cache.set(path, {
4968                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
4969                     refCount: 1
4970                 });
4971             }
4972             callbacksCache.add(path, callback);
4973             return {
4974                 close: function () {
4975                     var watcher = ts.Debug.checkDefined(cache.get(path));
4976                     callbacksCache.remove(path, callback);
4977                     watcher.refCount--;
4978                     if (watcher.refCount)
4979                         return;
4980                     cache.delete(path);
4981                     ts.closeFileWatcherOf(watcher);
4982                 }
4983             };
4984         };
4985     }
4986     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
4987     /**
4988      * Returns true if file status changed
4989      */
4990     /*@internal*/
4991     function onWatchedFileStat(watchedFile, modifiedTime) {
4992         var oldTime = watchedFile.mtime.getTime();
4993         var newTime = modifiedTime.getTime();
4994         if (oldTime !== newTime) {
4995             watchedFile.mtime = modifiedTime;
4996             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
4997             return true;
4998         }
4999         return false;
5000     }
5001     ts.onWatchedFileStat = onWatchedFileStat;
5002     /*@internal*/
5003     function getFileWatcherEventKind(oldTime, newTime) {
5004         return oldTime === 0
5005             ? FileWatcherEventKind.Created
5006             : newTime === 0
5007                 ? FileWatcherEventKind.Deleted
5008                 : FileWatcherEventKind.Changed;
5009     }
5010     ts.getFileWatcherEventKind = getFileWatcherEventKind;
5011     /*@internal*/
5012     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
5013     /*@internal*/
5014     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
5015     /*@internal*/
5016     function setSysLog(logger) {
5017         ts.sysLog = logger;
5018     }
5019     ts.setSysLog = setSysLog;
5020     /**
5021      * Watch the directory recursively using host provided method to watch child directories
5022      * that means if this is recursive watcher, watch the children directories as well
5023      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
5024      */
5025     /*@internal*/
5026     function createDirectoryWatcherSupportingRecursive(host) {
5027         var cache = ts.createMap();
5028         var callbackCache = ts.createMultiMap();
5029         var cacheToUpdateChildWatches = ts.createMap();
5030         var timerToUpdateChildWatches;
5031         var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
5032         var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
5033         return function (dirName, callback, recursive, options) { return recursive ?
5034             createDirectoryWatcher(dirName, options, callback) :
5035             host.watchDirectory(dirName, callback, recursive, options); };
5036         /**
5037          * Create the directory watcher for the dirPath.
5038          */
5039         function createDirectoryWatcher(dirName, options, callback) {
5040             var dirPath = toCanonicalFilePath(dirName);
5041             var directoryWatcher = cache.get(dirPath);
5042             if (directoryWatcher) {
5043                 directoryWatcher.refCount++;
5044             }
5045             else {
5046                 directoryWatcher = {
5047                     watcher: host.watchDirectory(dirName, function (fileName) {
5048                         if (isIgnoredPath(fileName))
5049                             return;
5050                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
5051                             // Call the actual callback
5052                             invokeCallbacks(dirPath, fileName);
5053                             // Iterate through existing children and update the watches if needed
5054                             updateChildWatches(dirName, dirPath, options);
5055                         }
5056                         else {
5057                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
5058                         }
5059                     }, /*recursive*/ false, options),
5060                     refCount: 1,
5061                     childWatches: ts.emptyArray
5062                 };
5063                 cache.set(dirPath, directoryWatcher);
5064                 updateChildWatches(dirName, dirPath, options);
5065             }
5066             var callbackToAdd = callback && { dirName: dirName, callback: callback };
5067             if (callbackToAdd) {
5068                 callbackCache.add(dirPath, callbackToAdd);
5069             }
5070             return {
5071                 dirName: dirName,
5072                 close: function () {
5073                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
5074                     if (callbackToAdd)
5075                         callbackCache.remove(dirPath, callbackToAdd);
5076                     directoryWatcher.refCount--;
5077                     if (directoryWatcher.refCount)
5078                         return;
5079                     cache.delete(dirPath);
5080                     ts.closeFileWatcherOf(directoryWatcher);
5081                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
5082                 }
5083             };
5084         }
5085         function invokeCallbacks(dirPath, fileNameOrInvokeMap) {
5086             var fileName;
5087             var invokeMap;
5088             if (ts.isString(fileNameOrInvokeMap)) {
5089                 fileName = fileNameOrInvokeMap;
5090             }
5091             else {
5092                 invokeMap = fileNameOrInvokeMap;
5093             }
5094             // Call the actual callback
5095             callbackCache.forEach(function (callbacks, rootDirName) {
5096                 if (invokeMap && invokeMap.has(rootDirName))
5097                     return;
5098                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
5099                     if (invokeMap) {
5100                         invokeMap.set(rootDirName, true);
5101                     }
5102                     else {
5103                         callbacks.forEach(function (_a) {
5104                             var callback = _a.callback;
5105                             return callback(fileName);
5106                         });
5107                     }
5108                 }
5109             });
5110         }
5111         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
5112             // Iterate through existing children and update the watches if needed
5113             var parentWatcher = cache.get(dirPath);
5114             if (parentWatcher && host.directoryExists(dirName)) {
5115                 // Schedule the update and postpone invoke for callbacks
5116                 scheduleUpdateChildWatches(dirName, dirPath, options);
5117                 return;
5118             }
5119             // Call the actual callbacks and remove child watches
5120             invokeCallbacks(dirPath, fileName);
5121             removeChildWatches(parentWatcher);
5122         }
5123         function scheduleUpdateChildWatches(dirName, dirPath, options) {
5124             if (!cacheToUpdateChildWatches.has(dirPath)) {
5125                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options });
5126             }
5127             if (timerToUpdateChildWatches) {
5128                 host.clearTimeout(timerToUpdateChildWatches);
5129                 timerToUpdateChildWatches = undefined;
5130             }
5131             timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
5132         }
5133         function onTimerToUpdateChildWatches() {
5134             timerToUpdateChildWatches = undefined;
5135             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
5136             var start = ts.timestamp();
5137             var invokeMap = ts.createMap();
5138             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
5139                 var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, done = _a.done;
5140                 ts.Debug.assert(!done);
5141                 cacheToUpdateChildWatches.delete(dirPath);
5142                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
5143                 // to ensure that all the changes are reflected at this time
5144                 invokeCallbacks(dirPath, invokeMap);
5145                 updateChildWatches(dirName, dirPath, options);
5146             }
5147             ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
5148             callbackCache.forEach(function (callbacks, rootDirName) {
5149                 if (invokeMap.has(rootDirName)) {
5150                     callbacks.forEach(function (_a) {
5151                         var callback = _a.callback, dirName = _a.dirName;
5152                         return callback(dirName);
5153                     });
5154                 }
5155             });
5156             var elapsed = ts.timestamp() - start;
5157             ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
5158         }
5159         function removeChildWatches(parentWatcher) {
5160             if (!parentWatcher)
5161                 return;
5162             var existingChildWatches = parentWatcher.childWatches;
5163             parentWatcher.childWatches = ts.emptyArray;
5164             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
5165                 var childWatcher = existingChildWatches_1[_i];
5166                 childWatcher.close();
5167                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
5168             }
5169         }
5170         function updateChildWatches(dirName, dirPath, options) {
5171             // Iterate through existing children and update the watches if needed
5172             var parentWatcher = cache.get(dirPath);
5173             if (parentWatcher) {
5174                 parentWatcher.childWatches = watchChildDirectories(dirName, parentWatcher.childWatches, options);
5175             }
5176         }
5177         /**
5178          * Watch the directories in the parentDir
5179          */
5180         function watchChildDirectories(parentDir, existingChildWatches, options) {
5181             var newChildWatches;
5182             ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
5183                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
5184                 // Filter our the symbolic link directories since those arent included in recursive watch
5185                 // which is same behaviour when recursive: true is passed to fs.watch
5186                 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
5187             }) : ts.emptyArray, existingChildWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
5188             return newChildWatches || ts.emptyArray;
5189             /**
5190              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
5191              */
5192             function createAndAddChildDirectoryWatcher(childName) {
5193                 var result = createDirectoryWatcher(childName, options);
5194                 addChildDirectoryWatcher(result);
5195             }
5196             /**
5197              * Add child directory watcher to the new ChildDirectoryWatcher list
5198              */
5199             function addChildDirectoryWatcher(childWatcher) {
5200                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
5201             }
5202         }
5203         function isIgnoredPath(path) {
5204             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
5205         }
5206         function isInPath(path, searchPath) {
5207             if (ts.stringContains(path, searchPath))
5208                 return true;
5209             if (host.useCaseSensitiveFileNames)
5210                 return false;
5211             return ts.stringContains(toCanonicalFilePath(path), searchPath);
5212         }
5213     }
5214     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
5215     /*@internal*/
5216     var FileSystemEntryKind;
5217     (function (FileSystemEntryKind) {
5218         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
5219         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
5220     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
5221     /*@internal*/
5222     function createFileWatcherCallback(callback) {
5223         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
5224     }
5225     ts.createFileWatcherCallback = createFileWatcherCallback;
5226     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
5227         return function (eventName) {
5228             if (eventName === "rename") {
5229                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
5230             }
5231             else {
5232                 // Change
5233                 callback(fileName, FileWatcherEventKind.Changed);
5234             }
5235         };
5236     }
5237     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
5238         return function (eventName, relativeFileName) {
5239             // In watchDirectory we only care about adding and removing files (when event name is
5240             // "rename"); changes made within files are handled by corresponding fileWatchers (when
5241             // event name is "change")
5242             if (eventName === "rename") {
5243                 // When deleting a file, the passed baseFileName is null
5244                 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
5245             }
5246         };
5247     }
5248     /*@internal*/
5249     function createSystemWatchFunctions(_a) {
5250         var pollingWatchFile = _a.pollingWatchFile, getModifiedTime = _a.getModifiedTime, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout, fsWatch = _a.fsWatch, fileExists = _a.fileExists, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, fsSupportsRecursiveFsWatch = _a.fsSupportsRecursiveFsWatch, directoryExists = _a.directoryExists, getAccessibleSortedChildDirectories = _a.getAccessibleSortedChildDirectories, realpath = _a.realpath, tscWatchFile = _a.tscWatchFile, useNonPollingWatchers = _a.useNonPollingWatchers, tscWatchDirectory = _a.tscWatchDirectory;
5251         var dynamicPollingWatchFile;
5252         var nonPollingWatchFile;
5253         var hostRecursiveDirectoryWatcher;
5254         return {
5255             watchFile: watchFile,
5256             watchDirectory: watchDirectory
5257         };
5258         function watchFile(fileName, callback, pollingInterval, options) {
5259             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
5260             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
5261             switch (watchFileKind) {
5262                 case ts.WatchFileKind.FixedPollingInterval:
5263                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
5264                 case ts.WatchFileKind.PriorityPollingInterval:
5265                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
5266                 case ts.WatchFileKind.DynamicPriorityPolling:
5267                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
5268                 case ts.WatchFileKind.UseFsEvents:
5269                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
5270                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
5271                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
5272                     if (!nonPollingWatchFile) {
5273                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
5274                     }
5275                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
5276                 default:
5277                     ts.Debug.assertNever(watchFileKind);
5278             }
5279         }
5280         function ensureDynamicPollingWatchFile() {
5281             return dynamicPollingWatchFile ||
5282                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
5283         }
5284         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
5285             if (options && options.watchFile !== undefined)
5286                 return options;
5287             switch (tscWatchFile) {
5288                 case "PriorityPollingInterval":
5289                     // Use polling interval based on priority when create watch using host.watchFile
5290                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
5291                 case "DynamicPriorityPolling":
5292                     // Use polling interval but change the interval depending on file changes and their default polling interval
5293                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
5294                 case "UseFsEvents":
5295                     // Use notifications from FS to watch with falling back to fs.watchFile
5296                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
5297                 case "UseFsEventsWithFallbackDynamicPolling":
5298                     // Use notifications from FS to watch with falling back to dynamic watch file
5299                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
5300                 case "UseFsEventsOnParentDirectory":
5301                     useNonPollingWatchers = true;
5302                 // fall through
5303                 default:
5304                     return useNonPollingWatchers ?
5305                         // Use notifications from FS to watch with falling back to fs.watchFile
5306                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
5307                         // Default to do not use fixed polling interval
5308                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
5309             }
5310         }
5311         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
5312             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5313             return {
5314                 watchFile: watchFile,
5315                 fallbackPolling: defaultFallbackPolling === undefined ?
5316                     fallbackPolling :
5317                     defaultFallbackPolling
5318             };
5319         }
5320         function watchDirectory(directoryName, callback, recursive, options) {
5321             if (fsSupportsRecursiveFsWatch) {
5322                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5323             }
5324             if (!hostRecursiveDirectoryWatcher) {
5325                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
5326                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5327                     directoryExists: directoryExists,
5328                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
5329                     watchDirectory: nonRecursiveWatchDirectory,
5330                     realpath: realpath,
5331                     setTimeout: setTimeout,
5332                     clearTimeout: clearTimeout
5333                 });
5334             }
5335             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
5336         }
5337         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
5338             ts.Debug.assert(!recursive);
5339             options = updateOptionsForWatchDirectory(options);
5340             var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
5341             switch (watchDirectoryKind) {
5342                 case ts.WatchDirectoryKind.FixedPollingInterval:
5343                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5344                     /*options*/ undefined);
5345                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
5346                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
5347                     /*options*/ undefined);
5348                 case ts.WatchDirectoryKind.UseFsEvents:
5349                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
5350                 default:
5351                     ts.Debug.assertNever(watchDirectoryKind);
5352             }
5353         }
5354         function updateOptionsForWatchDirectory(options) {
5355             if (options && options.watchDirectory !== undefined)
5356                 return options;
5357             switch (tscWatchDirectory) {
5358                 case "RecursiveDirectoryUsingFsWatchFile":
5359                     // Use polling interval based on priority when create watch using host.watchFile
5360                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
5361                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
5362                     // Use polling interval but change the interval depending on file changes and their default polling interval
5363                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
5364                 default:
5365                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
5366                     return {
5367                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
5368                         fallbackPolling: defaultFallbackPolling !== undefined ?
5369                             defaultFallbackPolling :
5370                             undefined
5371                     };
5372             }
5373         }
5374     }
5375     ts.createSystemWatchFunctions = createSystemWatchFunctions;
5376     /**
5377      * patch writefile to create folder before writing the file
5378      */
5379     /*@internal*/
5380     function patchWriteFileEnsuringDirectory(sys) {
5381         // patch writefile to create folder before writing the file
5382         var originalWriteFile = sys.writeFile;
5383         sys.writeFile = function (path, data, writeBom) {
5384             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); });
5385         };
5386     }
5387     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
5388     function getNodeMajorVersion() {
5389         if (typeof process === "undefined") {
5390             return undefined;
5391         }
5392         var version = process.version;
5393         if (!version) {
5394             return undefined;
5395         }
5396         var dot = version.indexOf(".");
5397         if (dot === -1) {
5398             return undefined;
5399         }
5400         return parseInt(version.substring(1, dot));
5401     }
5402     ts.getNodeMajorVersion = getNodeMajorVersion;
5403     // TODO: GH#18217 this is used as if it's certainly defined in many places.
5404     // eslint-disable-next-line prefer-const
5405     ts.sys = (function () {
5406         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
5407         // byte order mark from the specified encoding. Using any other byte order mark does
5408         // not actually work.
5409         var byteOrderMarkIndicator = "\uFEFF";
5410         function getNodeSystem() {
5411             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
5412             var _fs = require("fs");
5413             var _path = require("path");
5414             var _os = require("os");
5415             // crypto can be absent on reduced node installations
5416             var _crypto;
5417             try {
5418                 _crypto = require("crypto");
5419             }
5420             catch (_a) {
5421                 _crypto = undefined;
5422             }
5423             var activeSession;
5424             var profilePath = "./profile.cpuprofile";
5425             var Buffer = require("buffer").Buffer;
5426             var nodeVersion = getNodeMajorVersion();
5427             var isNode4OrLater = nodeVersion >= 4;
5428             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
5429             var platform = _os.platform();
5430             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
5431             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
5432             var _b = createSystemWatchFunctions({
5433                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
5434                 getModifiedTime: getModifiedTime,
5435                 setTimeout: setTimeout,
5436                 clearTimeout: clearTimeout,
5437                 fsWatch: fsWatch,
5438                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5439                 fileExists: fileExists,
5440                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5441                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5442                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
5443                 directoryExists: directoryExists,
5444                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
5445                 realpath: realpath,
5446                 tscWatchFile: process.env.TSC_WATCHFILE,
5447                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
5448                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
5449             }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
5450             var nodeSystem = {
5451                 args: process.argv.slice(2),
5452                 newLine: _os.EOL,
5453                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
5454                 write: function (s) {
5455                     process.stdout.write(s);
5456                 },
5457                 writeOutputIsTTY: function () {
5458                     return process.stdout.isTTY;
5459                 },
5460                 readFile: readFile,
5461                 writeFile: writeFile,
5462                 watchFile: watchFile,
5463                 watchDirectory: watchDirectory,
5464                 resolvePath: function (path) { return _path.resolve(path); },
5465                 fileExists: fileExists,
5466                 directoryExists: directoryExists,
5467                 createDirectory: function (directoryName) {
5468                     if (!nodeSystem.directoryExists(directoryName)) {
5469                         // Wrapped in a try-catch to prevent crashing if we are in a race
5470                         // with another copy of ourselves to create the same directory
5471                         try {
5472                             _fs.mkdirSync(directoryName);
5473                         }
5474                         catch (e) {
5475                             if (e.code !== "EEXIST") {
5476                                 // Failed for some other reason (access denied?); still throw
5477                                 throw e;
5478                             }
5479                         }
5480                     }
5481                 },
5482                 getExecutingFilePath: function () {
5483                     return __filename;
5484                 },
5485                 getCurrentDirectory: function () {
5486                     return process.cwd();
5487                 },
5488                 getDirectories: getDirectories,
5489                 getEnvironmentVariable: function (name) {
5490                     return process.env[name] || "";
5491                 },
5492                 readDirectory: readDirectory,
5493                 getModifiedTime: getModifiedTime,
5494                 setModifiedTime: setModifiedTime,
5495                 deleteFile: deleteFile,
5496                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
5497                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
5498                 getMemoryUsage: function () {
5499                     if (global.gc) {
5500                         global.gc();
5501                     }
5502                     return process.memoryUsage().heapUsed;
5503                 },
5504                 getFileSize: function (path) {
5505                     try {
5506                         var stat = _fs.statSync(path);
5507                         if (stat.isFile()) {
5508                             return stat.size;
5509                         }
5510                     }
5511                     catch ( /*ignore*/_a) { /*ignore*/ }
5512                     return 0;
5513                 },
5514                 exit: function (exitCode) {
5515                     disableCPUProfiler(function () { return process.exit(exitCode); });
5516                 },
5517                 enableCPUProfiler: enableCPUProfiler,
5518                 disableCPUProfiler: disableCPUProfiler,
5519                 realpath: realpath,
5520                 debugMode: !!process.env.NODE_INSPECTOR_IPC || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
5521                 tryEnableSourceMapsForHost: function () {
5522                     try {
5523                         require("source-map-support").install();
5524                     }
5525                     catch (_a) {
5526                         // Could not enable source maps.
5527                     }
5528                 },
5529                 setTimeout: setTimeout,
5530                 clearTimeout: clearTimeout,
5531                 clearScreen: function () {
5532                     process.stdout.write("\x1Bc");
5533                 },
5534                 setBlocking: function () {
5535                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
5536                         process.stdout._handle.setBlocking(true);
5537                     }
5538                 },
5539                 bufferFrom: bufferFrom,
5540                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
5541                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
5542                 require: function (baseDir, moduleName) {
5543                     try {
5544                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
5545                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
5546                     }
5547                     catch (error) {
5548                         return { module: undefined, modulePath: undefined, error: error };
5549                     }
5550                 }
5551             };
5552             return nodeSystem;
5553             /**
5554              * Uses the builtin inspector APIs to capture a CPU profile
5555              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
5556              */
5557             function enableCPUProfiler(path, cb) {
5558                 if (activeSession) {
5559                     cb();
5560                     return false;
5561                 }
5562                 var inspector = require("inspector");
5563                 if (!inspector || !inspector.Session) {
5564                     cb();
5565                     return false;
5566                 }
5567                 var session = new inspector.Session();
5568                 session.connect();
5569                 session.post("Profiler.enable", function () {
5570                     session.post("Profiler.start", function () {
5571                         activeSession = session;
5572                         profilePath = path;
5573                         cb();
5574                     });
5575                 });
5576                 return true;
5577             }
5578             /**
5579              * Strips non-TS paths from the profile, so users with private projects shouldn't
5580              * need to worry about leaking paths by submitting a cpu profile to us
5581              */
5582             function cleanupPaths(profile) {
5583                 var externalFileCounter = 0;
5584                 var remappedPaths = ts.createMap();
5585                 var normalizedDir = ts.normalizeSlashes(__dirname);
5586                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
5587                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
5588                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
5589                     var node = _a[_i];
5590                     if (node.callFrame.url) {
5591                         var url = ts.normalizeSlashes(node.callFrame.url);
5592                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
5593                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
5594                         }
5595                         else if (!nativePattern.test(url)) {
5596                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
5597                             externalFileCounter++;
5598                         }
5599                     }
5600                 }
5601                 return profile;
5602             }
5603             function disableCPUProfiler(cb) {
5604                 if (activeSession && activeSession !== "stopping") {
5605                     var s_1 = activeSession;
5606                     activeSession.post("Profiler.stop", function (err, _a) {
5607                         var profile = _a.profile;
5608                         if (!err) {
5609                             try {
5610                                 if (_fs.statSync(profilePath).isDirectory()) {
5611                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
5612                                 }
5613                             }
5614                             catch (_b) {
5615                                 // do nothing and ignore fallible fs operation
5616                             }
5617                             try {
5618                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
5619                             }
5620                             catch (_c) {
5621                                 // do nothing and ignore fallible fs operation
5622                             }
5623                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
5624                         }
5625                         activeSession = undefined;
5626                         s_1.disconnect();
5627                         cb();
5628                     });
5629                     activeSession = "stopping";
5630                     return true;
5631                 }
5632                 else {
5633                     cb();
5634                     return false;
5635                 }
5636             }
5637             function bufferFrom(input, encoding) {
5638                 // See https://github.com/Microsoft/TypeScript/issues/25652
5639                 return Buffer.from && Buffer.from !== Int8Array.from
5640                     ? Buffer.from(input, encoding)
5641                     : new Buffer(input, encoding);
5642             }
5643             function isFileSystemCaseSensitive() {
5644                 // win32\win64 are case insensitive platforms
5645                 if (platform === "win32" || platform === "win64") {
5646                     return false;
5647                 }
5648                 // If this file exists under a different case, we must be case-insensitve.
5649                 return !fileExists(swapCase(__filename));
5650             }
5651             /** Convert all lowercase chars to uppercase, and vice-versa */
5652             function swapCase(s) {
5653                 return s.replace(/\w/g, function (ch) {
5654                     var up = ch.toUpperCase();
5655                     return ch === up ? ch.toLowerCase() : up;
5656                 });
5657             }
5658             function fsWatchFileWorker(fileName, callback, pollingInterval) {
5659                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
5660                 var eventKind;
5661                 return {
5662                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
5663                 };
5664                 function fileChanged(curr, prev) {
5665                     // 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)
5666                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
5667                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
5668                     if (+curr.mtime === 0) {
5669                         if (isPreviouslyDeleted) {
5670                             // Already deleted file, no need to callback again
5671                             return;
5672                         }
5673                         eventKind = FileWatcherEventKind.Deleted;
5674                     }
5675                     else if (isPreviouslyDeleted) {
5676                         eventKind = FileWatcherEventKind.Created;
5677                     }
5678                     // If there is no change in modified time, ignore the event
5679                     else if (+curr.mtime === +prev.mtime) {
5680                         return;
5681                     }
5682                     else {
5683                         // File changed
5684                         eventKind = FileWatcherEventKind.Changed;
5685                     }
5686                     callback(fileName, eventKind);
5687                 }
5688             }
5689             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
5690                 var options;
5691                 var lastDirectoryPartWithDirectorySeparator;
5692                 var lastDirectoryPart;
5693                 if (isLinuxOrMacOs) {
5694                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
5695                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
5696                 }
5697                 /** Watcher for the file system entry depending on whether it is missing or present */
5698                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5699                     watchMissingFileSystemEntry() :
5700                     watchPresentFileSystemEntry();
5701                 return {
5702                     close: function () {
5703                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
5704                         watcher.close();
5705                         watcher = undefined;
5706                     }
5707                 };
5708                 /**
5709                  * Invoke the callback with rename and update the watcher if not closed
5710                  * @param createWatcher
5711                  */
5712                 function invokeCallbackAndUpdateWatcher(createWatcher) {
5713                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
5714                     // Call the callback for current directory
5715                     callback("rename", "");
5716                     // If watcher is not closed, update it
5717                     if (watcher) {
5718                         watcher.close();
5719                         watcher = createWatcher();
5720                     }
5721                 }
5722                 /**
5723                  * Watch the file or directory that is currently present
5724                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
5725                  */
5726                 function watchPresentFileSystemEntry() {
5727                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
5728                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
5729                     if (options === undefined) {
5730                         if (fsSupportsRecursiveFsWatch) {
5731                             options = { persistent: true, recursive: !!recursive };
5732                         }
5733                         else {
5734                             options = { persistent: true };
5735                         }
5736                     }
5737                     try {
5738                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
5739                             callbackChangingToMissingFileSystemEntry :
5740                             callback);
5741                         // Watch the missing file or directory or error
5742                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
5743                         return presentWatcher;
5744                     }
5745                     catch (e) {
5746                         // Catch the exception and use polling instead
5747                         // 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
5748                         // so instead of throwing error, use fs.watchFile
5749                         return watchPresentFileSystemEntryWithFsWatchFile();
5750                     }
5751                 }
5752                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
5753                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
5754                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
5755                     return event === "rename" &&
5756                         (!relativeName ||
5757                             relativeName === lastDirectoryPart ||
5758                             relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
5759                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
5760                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
5761                         callback(event, relativeName);
5762                 }
5763                 /**
5764                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
5765                  * 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
5766                  */
5767                 function watchPresentFileSystemEntryWithFsWatchFile() {
5768                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
5769                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
5770                 }
5771                 /**
5772                  * Watch the file or directory that is missing
5773                  * and switch to existing file or directory when the missing filesystem entry is created
5774                  */
5775                 function watchMissingFileSystemEntry() {
5776                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
5777                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
5778                             // Call the callback for current file or directory
5779                             // For now it could be callback for the inner directory creation,
5780                             // but just return current directory, better than current no-op
5781                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
5782                         }
5783                     }, fallbackPollingInterval, fallbackOptions);
5784                 }
5785             }
5786             function readFileWorker(fileName, _encoding) {
5787                 var buffer;
5788                 try {
5789                     buffer = _fs.readFileSync(fileName);
5790                 }
5791                 catch (e) {
5792                     return undefined;
5793                 }
5794                 var len = buffer.length;
5795                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
5796                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
5797                     // flip all byte pairs and treat as little endian.
5798                     len &= ~1; // Round down to a multiple of 2
5799                     for (var i = 0; i < len; i += 2) {
5800                         var temp = buffer[i];
5801                         buffer[i] = buffer[i + 1];
5802                         buffer[i + 1] = temp;
5803                     }
5804                     return buffer.toString("utf16le", 2);
5805                 }
5806                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
5807                     // Little endian UTF-16 byte order mark detected
5808                     return buffer.toString("utf16le", 2);
5809                 }
5810                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
5811                     // UTF-8 byte order mark detected
5812                     return buffer.toString("utf8", 3);
5813                 }
5814                 // Default is UTF-8 with no byte order mark
5815                 return buffer.toString("utf8");
5816             }
5817             function readFile(fileName, _encoding) {
5818                 ts.perfLogger.logStartReadFile(fileName);
5819                 var file = readFileWorker(fileName, _encoding);
5820                 ts.perfLogger.logStopReadFile();
5821                 return file;
5822             }
5823             function writeFile(fileName, data, writeByteOrderMark) {
5824                 ts.perfLogger.logEvent("WriteFile: " + fileName);
5825                 // If a BOM is required, emit one
5826                 if (writeByteOrderMark) {
5827                     data = byteOrderMarkIndicator + data;
5828                 }
5829                 var fd;
5830                 try {
5831                     fd = _fs.openSync(fileName, "w");
5832                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
5833                 }
5834                 finally {
5835                     if (fd !== undefined) {
5836                         _fs.closeSync(fd);
5837                     }
5838                 }
5839             }
5840             function getAccessibleFileSystemEntries(path) {
5841                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
5842                 try {
5843                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
5844                     var files = [];
5845                     var directories = [];
5846                     for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) {
5847                         var dirent = entries_2[_i];
5848                         // withFileTypes is not supported before Node 10.10.
5849                         var entry = typeof dirent === "string" ? dirent : dirent.name;
5850                         // This is necessary because on some file system node fails to exclude
5851                         // "." and "..". See https://github.com/nodejs/node/issues/4002
5852                         if (entry === "." || entry === "..") {
5853                             continue;
5854                         }
5855                         var stat = void 0;
5856                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
5857                             var name = ts.combinePaths(path, entry);
5858                             try {
5859                                 stat = _fs.statSync(name);
5860                             }
5861                             catch (e) {
5862                                 continue;
5863                             }
5864                         }
5865                         else {
5866                             stat = dirent;
5867                         }
5868                         if (stat.isFile()) {
5869                             files.push(entry);
5870                         }
5871                         else if (stat.isDirectory()) {
5872                             directories.push(entry);
5873                         }
5874                     }
5875                     files.sort();
5876                     directories.sort();
5877                     return { files: files, directories: directories };
5878                 }
5879                 catch (e) {
5880                     return ts.emptyFileSystemEntries;
5881                 }
5882             }
5883             function readDirectory(path, extensions, excludes, includes, depth) {
5884                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
5885             }
5886             function fileSystemEntryExists(path, entryKind) {
5887                 try {
5888                     var stat = _fs.statSync(path);
5889                     switch (entryKind) {
5890                         case 0 /* File */: return stat.isFile();
5891                         case 1 /* Directory */: return stat.isDirectory();
5892                         default: return false;
5893                     }
5894                 }
5895                 catch (e) {
5896                     return false;
5897                 }
5898             }
5899             function fileExists(path) {
5900                 return fileSystemEntryExists(path, 0 /* File */);
5901             }
5902             function directoryExists(path) {
5903                 return fileSystemEntryExists(path, 1 /* Directory */);
5904             }
5905             function getDirectories(path) {
5906                 return getAccessibleFileSystemEntries(path).directories.slice();
5907             }
5908             function realpath(path) {
5909                 try {
5910                     return _fs.realpathSync(path);
5911                 }
5912                 catch (_a) {
5913                     return path;
5914                 }
5915             }
5916             function getModifiedTime(path) {
5917                 try {
5918                     return _fs.statSync(path).mtime;
5919                 }
5920                 catch (e) {
5921                     return undefined;
5922                 }
5923             }
5924             function setModifiedTime(path, time) {
5925                 try {
5926                     _fs.utimesSync(path, time, time);
5927                 }
5928                 catch (e) {
5929                     return;
5930                 }
5931             }
5932             function deleteFile(path) {
5933                 try {
5934                     return _fs.unlinkSync(path);
5935                 }
5936                 catch (e) {
5937                     return;
5938                 }
5939             }
5940             function createSHA256Hash(data) {
5941                 var hash = _crypto.createHash("sha256");
5942                 hash.update(data);
5943                 return hash.digest("hex");
5944             }
5945         }
5946         var sys;
5947         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
5948             // process and process.nextTick checks if current environment is node-like
5949             // process.browser check excludes webpack and browserify
5950             sys = getNodeSystem();
5951         }
5952         if (sys) {
5953             // patch writefile to create folder before writing the file
5954             patchWriteFileEnsuringDirectory(sys);
5955         }
5956         return sys;
5957     })();
5958     if (ts.sys && ts.sys.getEnvironmentVariable) {
5959         setCustomPollingValues(ts.sys);
5960         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
5961             ? 1 /* Normal */
5962             : 0 /* None */);
5963     }
5964     if (ts.sys && ts.sys.debugMode) {
5965         ts.Debug.isDebugging = true;
5966     }
5967 })(ts || (ts = {}));
5968 /* @internal */
5969 var ts;
5970 (function (ts) {
5971     /**
5972      * Internally, we represent paths as strings with '/' as the directory separator.
5973      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5974      * we expect the host to correctly handle paths in our specified format.
5975      */
5976     ts.directorySeparator = "/";
5977     var altDirectorySeparator = "\\";
5978     var urlSchemeSeparator = "://";
5979     var backslashRegExp = /\\/g;
5980     //// Path Tests
5981     /**
5982      * Determines whether a charCode corresponds to `/` or `\`.
5983      */
5984     function isAnyDirectorySeparator(charCode) {
5985         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
5986     }
5987     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
5988     /**
5989      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
5990      */
5991     function isUrl(path) {
5992         return getEncodedRootLength(path) < 0;
5993     }
5994     ts.isUrl = isUrl;
5995     /**
5996      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
5997      * like `c:`, `c:\` or `c:/`).
5998      */
5999     function isRootedDiskPath(path) {
6000         return getEncodedRootLength(path) > 0;
6001     }
6002     ts.isRootedDiskPath = isRootedDiskPath;
6003     /**
6004      * Determines whether a path consists only of a path root.
6005      */
6006     function isDiskPathRoot(path) {
6007         var rootLength = getEncodedRootLength(path);
6008         return rootLength > 0 && rootLength === path.length;
6009     }
6010     ts.isDiskPathRoot = isDiskPathRoot;
6011     /**
6012      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
6013      *
6014      * ```ts
6015      * // POSIX
6016      * pathIsAbsolute("/path/to/file.ext") === true
6017      * // DOS
6018      * pathIsAbsolute("c:/path/to/file.ext") === true
6019      * // URL
6020      * pathIsAbsolute("file:///path/to/file.ext") === true
6021      * // Non-absolute
6022      * pathIsAbsolute("path/to/file.ext") === false
6023      * pathIsAbsolute("./path/to/file.ext") === false
6024      * ```
6025      */
6026     function pathIsAbsolute(path) {
6027         return getEncodedRootLength(path) !== 0;
6028     }
6029     ts.pathIsAbsolute = pathIsAbsolute;
6030     /**
6031      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
6032      */
6033     function pathIsRelative(path) {
6034         return /^\.\.?($|[\\/])/.test(path);
6035     }
6036     ts.pathIsRelative = pathIsRelative;
6037     function hasExtension(fileName) {
6038         return ts.stringContains(getBaseFileName(fileName), ".");
6039     }
6040     ts.hasExtension = hasExtension;
6041     function fileExtensionIs(path, extension) {
6042         return path.length > extension.length && ts.endsWith(path, extension);
6043     }
6044     ts.fileExtensionIs = fileExtensionIs;
6045     function fileExtensionIsOneOf(path, extensions) {
6046         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
6047             var extension = extensions_1[_i];
6048             if (fileExtensionIs(path, extension)) {
6049                 return true;
6050             }
6051         }
6052         return false;
6053     }
6054     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
6055     /**
6056      * Determines whether a path has a trailing separator (`/` or `\\`).
6057      */
6058     function hasTrailingDirectorySeparator(path) {
6059         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
6060     }
6061     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
6062     //// Path Parsing
6063     function isVolumeCharacter(charCode) {
6064         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
6065             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
6066     }
6067     function getFileUrlVolumeSeparatorEnd(url, start) {
6068         var ch0 = url.charCodeAt(start);
6069         if (ch0 === 58 /* colon */)
6070             return start + 1;
6071         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
6072             var ch2 = url.charCodeAt(start + 2);
6073             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
6074                 return start + 3;
6075         }
6076         return -1;
6077     }
6078     /**
6079      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6080      * If the root is part of a URL, the twos-complement of the root length is returned.
6081      */
6082     function getEncodedRootLength(path) {
6083         if (!path)
6084             return 0;
6085         var ch0 = path.charCodeAt(0);
6086         // POSIX or UNC
6087         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
6088             if (path.charCodeAt(1) !== ch0)
6089                 return 1; // POSIX: "/" (or non-normalized "\")
6090             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
6091             if (p1 < 0)
6092                 return path.length; // UNC: "//server" or "\\server"
6093             return p1 + 1; // UNC: "//server/" or "\\server\"
6094         }
6095         // DOS
6096         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
6097             var ch2 = path.charCodeAt(2);
6098             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
6099                 return 3; // DOS: "c:/" or "c:\"
6100             if (path.length === 2)
6101                 return 2; // DOS: "c:" (but not "c:d")
6102         }
6103         // URL
6104         var schemeEnd = path.indexOf(urlSchemeSeparator);
6105         if (schemeEnd !== -1) {
6106             var authorityStart = schemeEnd + urlSchemeSeparator.length;
6107             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
6108             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
6109                 // For local "file" URLs, include the leading DOS volume (if present).
6110                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
6111                 // special case interpreted as "the machine from which the URL is being interpreted".
6112                 var scheme = path.slice(0, schemeEnd);
6113                 var authority = path.slice(authorityStart, authorityEnd);
6114                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
6115                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
6116                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
6117                     if (volumeSeparatorEnd !== -1) {
6118                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
6119                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
6120                             return ~(volumeSeparatorEnd + 1);
6121                         }
6122                         if (volumeSeparatorEnd === path.length) {
6123                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
6124                             // but not "file:///c:d" or "file:///c%3ad"
6125                             return ~volumeSeparatorEnd;
6126                         }
6127                     }
6128                 }
6129                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
6130             }
6131             return ~path.length; // URL: "file://server", "http://server"
6132         }
6133         // relative
6134         return 0;
6135     }
6136     /**
6137      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
6138      *
6139      * For example:
6140      * ```ts
6141      * getRootLength("a") === 0                   // ""
6142      * getRootLength("/") === 1                   // "/"
6143      * getRootLength("c:") === 2                  // "c:"
6144      * getRootLength("c:d") === 0                 // ""
6145      * getRootLength("c:/") === 3                 // "c:/"
6146      * getRootLength("c:\\") === 3                // "c:\\"
6147      * getRootLength("//server") === 7            // "//server"
6148      * getRootLength("//server/share") === 8      // "//server/"
6149      * getRootLength("\\\\server") === 7          // "\\\\server"
6150      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
6151      * getRootLength("file:///path") === 8        // "file:///"
6152      * getRootLength("file:///c:") === 10         // "file:///c:"
6153      * getRootLength("file:///c:d") === 8         // "file:///"
6154      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
6155      * getRootLength("file://server") === 13      // "file://server"
6156      * getRootLength("file://server/path") === 14 // "file://server/"
6157      * getRootLength("http://server") === 13      // "http://server"
6158      * getRootLength("http://server/path") === 14 // "http://server/"
6159      * ```
6160      */
6161     function getRootLength(path) {
6162         var rootLength = getEncodedRootLength(path);
6163         return rootLength < 0 ? ~rootLength : rootLength;
6164     }
6165     ts.getRootLength = getRootLength;
6166     function getDirectoryPath(path) {
6167         path = normalizeSlashes(path);
6168         // If the path provided is itself the root, then return it.
6169         var rootLength = getRootLength(path);
6170         if (rootLength === path.length)
6171             return path;
6172         // return the leading portion of the path up to the last (non-terminal) directory separator
6173         // but not including any trailing directory separator.
6174         path = removeTrailingDirectorySeparator(path);
6175         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
6176     }
6177     ts.getDirectoryPath = getDirectoryPath;
6178     function getBaseFileName(path, extensions, ignoreCase) {
6179         path = normalizeSlashes(path);
6180         // if the path provided is itself the root, then it has not file name.
6181         var rootLength = getRootLength(path);
6182         if (rootLength === path.length)
6183             return "";
6184         // return the trailing portion of the path starting after the last (non-terminal) directory
6185         // separator but not including any trailing directory separator.
6186         path = removeTrailingDirectorySeparator(path);
6187         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
6188         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
6189         return extension ? name.slice(0, name.length - extension.length) : name;
6190     }
6191     ts.getBaseFileName = getBaseFileName;
6192     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
6193         if (!ts.startsWith(extension, "."))
6194             extension = "." + extension;
6195         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
6196             var pathExtension = path.slice(path.length - extension.length);
6197             if (stringEqualityComparer(pathExtension, extension)) {
6198                 return pathExtension;
6199             }
6200         }
6201     }
6202     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
6203         if (typeof extensions === "string") {
6204             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
6205         }
6206         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
6207             var extension = extensions_2[_i];
6208             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
6209             if (result)
6210                 return result;
6211         }
6212         return "";
6213     }
6214     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
6215         // Retrieves any string from the final "." onwards from a base file name.
6216         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
6217         if (extensions) {
6218             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
6219         }
6220         var baseFileName = getBaseFileName(path);
6221         var extensionIndex = baseFileName.lastIndexOf(".");
6222         if (extensionIndex >= 0) {
6223             return baseFileName.substring(extensionIndex);
6224         }
6225         return "";
6226     }
6227     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
6228     function pathComponents(path, rootLength) {
6229         var root = path.substring(0, rootLength);
6230         var rest = path.substring(rootLength).split(ts.directorySeparator);
6231         if (rest.length && !ts.lastOrUndefined(rest))
6232             rest.pop();
6233         return __spreadArrays([root], rest);
6234     }
6235     /**
6236      * Parse a path into an array containing a root component (at index 0) and zero or more path
6237      * components (at indices > 0). The result is not normalized.
6238      * If the path is relative, the root component is `""`.
6239      * If the path is absolute, the root component includes the first path separator (`/`).
6240      *
6241      * ```ts
6242      * // POSIX
6243      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
6244      * getPathComponents("/path/to/") === ["/", "path", "to"]
6245      * getPathComponents("/") === ["/"]
6246      * // DOS
6247      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
6248      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
6249      * getPathComponents("c:/") === ["c:/"]
6250      * getPathComponents("c:") === ["c:"]
6251      * // URL
6252      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
6253      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
6254      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
6255      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
6256      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
6257      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
6258      * getPathComponents("file://server/") === ["file://server/"]
6259      * getPathComponents("file://server") === ["file://server"]
6260      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
6261      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
6262      * getPathComponents("file:///") === ["file:///"]
6263      * getPathComponents("file://") === ["file://"]
6264      */
6265     function getPathComponents(path, currentDirectory) {
6266         if (currentDirectory === void 0) { currentDirectory = ""; }
6267         path = combinePaths(currentDirectory, path);
6268         return pathComponents(path, getRootLength(path));
6269     }
6270     ts.getPathComponents = getPathComponents;
6271     //// Path Formatting
6272     /**
6273      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
6274      * segments (at indices > 0).
6275      *
6276      * ```ts
6277      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
6278      * ```
6279      */
6280     function getPathFromPathComponents(pathComponents) {
6281         if (pathComponents.length === 0)
6282             return "";
6283         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
6284         return root + pathComponents.slice(1).join(ts.directorySeparator);
6285     }
6286     ts.getPathFromPathComponents = getPathFromPathComponents;
6287     //// Path Normalization
6288     /**
6289      * Normalize path separators, converting `\` into `/`.
6290      */
6291     function normalizeSlashes(path) {
6292         return path.replace(backslashRegExp, ts.directorySeparator);
6293     }
6294     ts.normalizeSlashes = normalizeSlashes;
6295     /**
6296      * Reduce an array of path components to a more simplified path by navigating any
6297      * `"."` or `".."` entries in the path.
6298      */
6299     function reducePathComponents(components) {
6300         if (!ts.some(components))
6301             return [];
6302         var reduced = [components[0]];
6303         for (var i = 1; i < components.length; i++) {
6304             var component = components[i];
6305             if (!component)
6306                 continue;
6307             if (component === ".")
6308                 continue;
6309             if (component === "..") {
6310                 if (reduced.length > 1) {
6311                     if (reduced[reduced.length - 1] !== "..") {
6312                         reduced.pop();
6313                         continue;
6314                     }
6315                 }
6316                 else if (reduced[0])
6317                     continue;
6318             }
6319             reduced.push(component);
6320         }
6321         return reduced;
6322     }
6323     ts.reducePathComponents = reducePathComponents;
6324     /**
6325      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
6326      *
6327      * ```ts
6328      * // Non-rooted
6329      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
6330      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
6331      * // POSIX
6332      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
6333      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
6334      * // DOS
6335      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
6336      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
6337      * // URL
6338      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
6339      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
6340      * ```
6341      */
6342     function combinePaths(path) {
6343         var paths = [];
6344         for (var _i = 1; _i < arguments.length; _i++) {
6345             paths[_i - 1] = arguments[_i];
6346         }
6347         if (path)
6348             path = normalizeSlashes(path);
6349         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
6350             var relativePath = paths_1[_a];
6351             if (!relativePath)
6352                 continue;
6353             relativePath = normalizeSlashes(relativePath);
6354             if (!path || getRootLength(relativePath) !== 0) {
6355                 path = relativePath;
6356             }
6357             else {
6358                 path = ensureTrailingDirectorySeparator(path) + relativePath;
6359             }
6360         }
6361         return path;
6362     }
6363     ts.combinePaths = combinePaths;
6364     /**
6365      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
6366      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
6367      *
6368      * ```ts
6369      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
6370      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
6371      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
6372      * ```
6373      */
6374     function resolvePath(path) {
6375         var paths = [];
6376         for (var _i = 1; _i < arguments.length; _i++) {
6377             paths[_i - 1] = arguments[_i];
6378         }
6379         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
6380     }
6381     ts.resolvePath = resolvePath;
6382     /**
6383      * Parse a path into an array containing a root component (at index 0) and zero or more path
6384      * components (at indices > 0). The result is normalized.
6385      * If the path is relative, the root component is `""`.
6386      * If the path is absolute, the root component includes the first path separator (`/`).
6387      *
6388      * ```ts
6389      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
6390      * ```
6391      */
6392     function getNormalizedPathComponents(path, currentDirectory) {
6393         return reducePathComponents(getPathComponents(path, currentDirectory));
6394     }
6395     ts.getNormalizedPathComponents = getNormalizedPathComponents;
6396     function getNormalizedAbsolutePath(fileName, currentDirectory) {
6397         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
6398     }
6399     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
6400     function normalizePath(path) {
6401         path = normalizeSlashes(path);
6402         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
6403         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
6404     }
6405     ts.normalizePath = normalizePath;
6406     function getPathWithoutRoot(pathComponents) {
6407         if (pathComponents.length === 0)
6408             return "";
6409         return pathComponents.slice(1).join(ts.directorySeparator);
6410     }
6411     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
6412         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
6413     }
6414     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
6415     function toPath(fileName, basePath, getCanonicalFileName) {
6416         var nonCanonicalizedPath = isRootedDiskPath(fileName)
6417             ? normalizePath(fileName)
6418             : getNormalizedAbsolutePath(fileName, basePath);
6419         return getCanonicalFileName(nonCanonicalizedPath);
6420     }
6421     ts.toPath = toPath;
6422     function normalizePathAndParts(path) {
6423         path = normalizeSlashes(path);
6424         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
6425         if (parts.length) {
6426             var joinedParts = root + parts.join(ts.directorySeparator);
6427             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
6428         }
6429         else {
6430             return { path: root, parts: parts };
6431         }
6432     }
6433     ts.normalizePathAndParts = normalizePathAndParts;
6434     function removeTrailingDirectorySeparator(path) {
6435         if (hasTrailingDirectorySeparator(path)) {
6436             return path.substr(0, path.length - 1);
6437         }
6438         return path;
6439     }
6440     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6441     function ensureTrailingDirectorySeparator(path) {
6442         if (!hasTrailingDirectorySeparator(path)) {
6443             return path + ts.directorySeparator;
6444         }
6445         return path;
6446     }
6447     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6448     /**
6449      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6450      * with `./` or `../`) so as not to be confused with an unprefixed module name.
6451      *
6452      * ```ts
6453      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6454      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6455      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6456      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6457      * ```
6458      */
6459     function ensurePathIsNonModuleName(path) {
6460         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6461     }
6462     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6463     function changeAnyExtension(path, ext, extensions, ignoreCase) {
6464         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6465         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6466     }
6467     ts.changeAnyExtension = changeAnyExtension;
6468     //// Path Comparisons
6469     // check path for these segments: '', '.'. '..'
6470     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
6471     function comparePathsWorker(a, b, componentComparer) {
6472         if (a === b)
6473             return 0 /* EqualTo */;
6474         if (a === undefined)
6475             return -1 /* LessThan */;
6476         if (b === undefined)
6477             return 1 /* GreaterThan */;
6478         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6479         //       need to perform path reduction.
6480         var aRoot = a.substring(0, getRootLength(a));
6481         var bRoot = b.substring(0, getRootLength(b));
6482         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6483         if (result !== 0 /* EqualTo */) {
6484             return result;
6485         }
6486         // NOTE: Performance optimization - shortcut if there are no relative path segments in
6487         //       the non-root portion of the path
6488         var aRest = a.substring(aRoot.length);
6489         var bRest = b.substring(bRoot.length);
6490         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6491             return componentComparer(aRest, bRest);
6492         }
6493         // The path contains a relative path segment. Normalize the paths and perform a slower component
6494         // by component comparison.
6495         var aComponents = reducePathComponents(getPathComponents(a));
6496         var bComponents = reducePathComponents(getPathComponents(b));
6497         var sharedLength = Math.min(aComponents.length, bComponents.length);
6498         for (var i = 1; i < sharedLength; i++) {
6499             var result_1 = componentComparer(aComponents[i], bComponents[i]);
6500             if (result_1 !== 0 /* EqualTo */) {
6501                 return result_1;
6502             }
6503         }
6504         return ts.compareValues(aComponents.length, bComponents.length);
6505     }
6506     /**
6507      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6508      */
6509     function comparePathsCaseSensitive(a, b) {
6510         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6511     }
6512     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6513     /**
6514      * Performs a case-insensitive comparison of two paths.
6515      */
6516     function comparePathsCaseInsensitive(a, b) {
6517         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6518     }
6519     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6520     function comparePaths(a, b, currentDirectory, ignoreCase) {
6521         if (typeof currentDirectory === "string") {
6522             a = combinePaths(currentDirectory, a);
6523             b = combinePaths(currentDirectory, b);
6524         }
6525         else if (typeof currentDirectory === "boolean") {
6526             ignoreCase = currentDirectory;
6527         }
6528         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6529     }
6530     ts.comparePaths = comparePaths;
6531     function containsPath(parent, child, currentDirectory, ignoreCase) {
6532         if (typeof currentDirectory === "string") {
6533             parent = combinePaths(currentDirectory, parent);
6534             child = combinePaths(currentDirectory, child);
6535         }
6536         else if (typeof currentDirectory === "boolean") {
6537             ignoreCase = currentDirectory;
6538         }
6539         if (parent === undefined || child === undefined)
6540             return false;
6541         if (parent === child)
6542             return true;
6543         var parentComponents = reducePathComponents(getPathComponents(parent));
6544         var childComponents = reducePathComponents(getPathComponents(child));
6545         if (childComponents.length < parentComponents.length) {
6546             return false;
6547         }
6548         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6549         for (var i = 0; i < parentComponents.length; i++) {
6550             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6551             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6552                 return false;
6553             }
6554         }
6555         return true;
6556     }
6557     ts.containsPath = containsPath;
6558     /**
6559      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6560      * Comparison is case-sensitive between the canonical paths.
6561      *
6562      * @deprecated Use `containsPath` if possible.
6563      */
6564     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6565         var canonicalFileName = getCanonicalFileName(fileName);
6566         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6567         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6568     }
6569     ts.startsWithDirectory = startsWithDirectory;
6570     //// Relative Paths
6571     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6572         var fromComponents = reducePathComponents(getPathComponents(from));
6573         var toComponents = reducePathComponents(getPathComponents(to));
6574         var start;
6575         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6576             var fromComponent = getCanonicalFileName(fromComponents[start]);
6577             var toComponent = getCanonicalFileName(toComponents[start]);
6578             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6579             if (!comparer(fromComponent, toComponent))
6580                 break;
6581         }
6582         if (start === 0) {
6583             return toComponents;
6584         }
6585         var components = toComponents.slice(start);
6586         var relative = [];
6587         for (; start < fromComponents.length; start++) {
6588             relative.push("..");
6589         }
6590         return __spreadArrays([""], relative, components);
6591     }
6592     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6593     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6594         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6595         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6596         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6597         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6598         return getPathFromPathComponents(pathComponents);
6599     }
6600     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6601     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6602         return !isRootedDiskPath(absoluteOrRelativePath)
6603             ? absoluteOrRelativePath
6604             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6605     }
6606     ts.convertToRelativePath = convertToRelativePath;
6607     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6608         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6609     }
6610     ts.getRelativePathFromFile = getRelativePathFromFile;
6611     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6612         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6613         var firstComponent = pathComponents[0];
6614         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6615             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6616             pathComponents[0] = prefix + firstComponent;
6617         }
6618         return getPathFromPathComponents(pathComponents);
6619     }
6620     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6621     function forEachAncestorDirectory(directory, callback) {
6622         while (true) {
6623             var result = callback(directory);
6624             if (result !== undefined) {
6625                 return result;
6626             }
6627             var parentPath = getDirectoryPath(directory);
6628             if (parentPath === directory) {
6629                 return undefined;
6630             }
6631             directory = parentPath;
6632         }
6633     }
6634     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6635     function isNodeModulesDirectory(dirPath) {
6636         return ts.endsWith(dirPath, "/node_modules");
6637     }
6638     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6639 })(ts || (ts = {}));
6640 // <auto-generated />
6641 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
6642 /* @internal */
6643 var ts;
6644 (function (ts) {
6645     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) {
6646         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid };
6647     }
6648     ts.Diagnostics = {
6649         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
6650         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
6651         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
6652         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."),
6653         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."),
6654         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
6655         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
6656         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."),
6657         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
6658         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."),
6659         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."),
6660         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."),
6661         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."),
6662         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."),
6663         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."),
6664         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."),
6665         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."),
6666         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."),
6667         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."),
6668         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'."),
6669         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."),
6670         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."),
6671         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
6672         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
6673         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
6674         _0_modifier_cannot_appear_on_a_class_element: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_class_element_1031", "'{0}' modifier cannot appear on a class element."),
6675         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."),
6676         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."),
6677         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."),
6678         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."),
6679         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."),
6680         _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."),
6681         _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."),
6682         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
6683         _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."),
6684         _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."),
6685         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."),
6686         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."),
6687         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
6688         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."),
6689         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."),
6690         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."),
6691         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."),
6692         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."),
6693         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
6694         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."),
6695         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."),
6696         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."),
6697         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."),
6698         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."),
6699         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."),
6700         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
6701         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."),
6702         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."),
6703         The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_1064", "The return type of an async function or method must be the global Promise<T> type."),
6704         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."),
6705         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."),
6706         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."),
6707         _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."),
6708         _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."),
6709         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."),
6710         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
6711         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}'."),
6712         _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."),
6713         _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."),
6714         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."),
6715         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."),
6716         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."),
6717         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
6718         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."),
6719         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."),
6720         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
6721         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
6722         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
6723         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."),
6724         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."),
6725         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."),
6726         A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator: diag(1103, ts.DiagnosticCategory.Error, "A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator_1103", "A 'for-await-of' statement is only allowed within an async function or async generator."),
6727         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."),
6728         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."),
6729         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
6730         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."),
6731         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
6732         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
6733         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."),
6734         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
6735         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."),
6736         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."),
6737         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."),
6738         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."),
6739         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."),
6740         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
6741         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."),
6742         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
6743         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
6744         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
6745         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
6746         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
6747         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
6748         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
6749         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
6750         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
6751         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
6752         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
6753         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
6754         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
6755         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
6756         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
6757         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
6758         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
6759         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
6760         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
6761         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
6762         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
6763         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."),
6764         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'."),
6765         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."),
6766         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
6767         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."),
6768         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."),
6769         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
6770         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
6771         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."),
6772         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."),
6773         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."),
6774         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."),
6775         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."),
6776         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."),
6777         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."),
6778         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."),
6779         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."),
6780         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
6781         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
6782         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."),
6783         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
6784         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
6785         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
6786         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
6787         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
6788         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
6789         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
6790         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."),
6791         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."),
6792         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
6793         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
6794         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."),
6795         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."),
6796         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."),
6797         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."),
6798         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."),
6799         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
6800         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
6801         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
6802         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."),
6803         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."),
6804         Catch_clause_variable_cannot_have_a_type_annotation: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_cannot_have_a_type_annotation_1196", "Catch clause variable cannot have a type annotation."),
6805         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."),
6806         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."),
6807         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
6808         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
6809         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."),
6810         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."),
6811         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'."),
6812         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
6813         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."),
6814         All_files_must_be_modules_when_the_isolatedModules_flag_is_provided: diag(1208, ts.DiagnosticCategory.Error, "All_files_must_be_modules_when_the_isolatedModules_flag_is_provided_1208", "All files must be modules when the '--isolatedModules' flag is provided."),
6815         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."),
6816         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."),
6817         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."),
6818         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."),
6819         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."),
6820         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."),
6821         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."),
6822         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'."),
6823         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."),
6824         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."),
6825         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."),
6826         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."),
6827         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
6828         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."),
6829         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
6830         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}'."),
6831         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}'."),
6832         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."),
6833         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."),
6834         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."),
6835         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."),
6836         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."),
6837         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."),
6838         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."),
6839         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."),
6840         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'."),
6841         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'."),
6842         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."),
6843         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."),
6844         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."),
6845         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."),
6846         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."),
6847         _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."),
6848         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."),
6849         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."),
6850         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."),
6851         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."),
6852         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."),
6853         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."),
6854         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'."),
6855         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."),
6856         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."),
6857         _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."),
6858         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."),
6859         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."),
6860         A_rest_element_must_be_last_in_a_tuple_type: diag(1256, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_tuple_type_1256", "A rest element must be last in a tuple type."),
6861         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."),
6862         Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation: diag(1258, ts.DiagnosticCategory.Error, "Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation_1258", "Definite assignment assertions can only be used along with a type annotation."),
6863         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"),
6864         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
6865         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."),
6866         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."),
6867         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."),
6868         can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."),
6869         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."),
6870         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."),
6871         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."),
6872         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."),
6873         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."),
6874         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."),
6875         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."),
6876         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."),
6877         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."),
6878         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."),
6879         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'."),
6880         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."),
6881         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."),
6882         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"),
6883         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
6884         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."),
6885         _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}()'?"),
6886         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'."),
6887         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'."),
6888         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'."),
6889         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."),
6890         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."),
6891         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."),
6892         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."),
6893         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."),
6894         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."),
6895         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."),
6896         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}')'?"),
6897         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
6898         The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'esnext' or 'system'."),
6899         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
6900         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"),
6901         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."),
6902         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."),
6903         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
6904         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
6905         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."),
6906         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."),
6907         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."),
6908         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."),
6909         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."),
6910         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."),
6911         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'?"),
6912         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 '}'."),
6913         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."),
6914         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."),
6915         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?"),
6916         _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'."),
6917         _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'."),
6918         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."),
6919         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
6920         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"),
6921         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
6922         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
6923         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"),
6924         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
6925         Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."),
6926         This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error: diag(1371, ts.DiagnosticCategory.Error, "This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is__1371", "This import is never used as a value and must use 'import type' because the 'importsNotUsedAsValues' is set to 'error'."),
6927         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
6928         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"),
6929         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."),
6930         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
6931         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
6932         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."),
6933         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'."),
6934         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'."),
6935         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;`?"),
6936         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;`?"),
6937         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'."),
6938         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."),
6939         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."),
6940         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."),
6941         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),
6942         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),
6943         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),
6944         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),
6945         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
6946         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."),
6947         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."),
6948         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
6949         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
6950         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}'."),
6951         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
6952         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."),
6953         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."),
6954         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."),
6955         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."),
6956         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."),
6957         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."),
6958         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."),
6959         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)."),
6960         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
6961         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."),
6962         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)."),
6963         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
6964         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."),
6965         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}'."),
6966         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}'."),
6967         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}'."),
6968         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
6969         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}'."),
6970         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}'."),
6971         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
6972         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}'."),
6973         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."),
6974         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}'."),
6975         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
6976         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."),
6977         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."),
6978         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."),
6979         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."),
6980         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."),
6981         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."),
6982         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."),
6983         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."),
6984         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}'."),
6985         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."),
6986         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}'."),
6987         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'."),
6988         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}'."),
6989         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}'."),
6990         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}'."),
6991         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."),
6992         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."),
6993         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'?"),
6994         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
6995         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."),
6996         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
6997         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."),
6998         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}'."),
6999         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."),
7000         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."),
7001         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."),
7002         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."),
7003         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."),
7004         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."),
7005         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'."),
7006         The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: diag(2361, ts.DiagnosticCategory.Error, "The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter_2361", "The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter."),
7007         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."),
7008         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."),
7009         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."),
7010         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}'."),
7011         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'."),
7012         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."),
7013         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7014         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."),
7015         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."),
7016         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."),
7017         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7018         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."),
7019         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7020         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7021         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."),
7022         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."),
7023         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."),
7024         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."),
7025         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."),
7026         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."),
7027         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."),
7028         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."),
7029         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."),
7030         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."),
7031         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."),
7032         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7033         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7034         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7035         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7036         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."),
7037         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7038         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7039         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."),
7040         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."),
7041         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."),
7042         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}'."),
7043         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."),
7044         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."),
7045         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."),
7046         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."),
7047         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."),
7048         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}'."),
7049         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."),
7050         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'."),
7051         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."),
7052         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}'."),
7053         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7054         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."),
7055         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'."),
7056         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}'."),
7057         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}'."),
7058         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}'."),
7059         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7060         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}'."),
7061         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}'."),
7062         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}'."),
7063         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}'."),
7064         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7065         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."),
7066         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."),
7067         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."),
7068         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."),
7069         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7070         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."),
7071         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7072         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7073         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."),
7074         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."),
7075         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."),
7076         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."),
7077         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."),
7078         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."),
7079         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7080         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."),
7081         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}'."),
7082         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."),
7083         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}'."),
7084         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}'."),
7085         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}'."),
7086         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."),
7087         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}'."),
7088         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."),
7089         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."),
7090         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7091         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7092         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7093         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."),
7094         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."),
7095         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."),
7096         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}'."),
7097         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7098         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7099         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."),
7100         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."),
7101         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}'."),
7102         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."),
7103         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."),
7104         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."),
7105         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'."),
7106         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."),
7107         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."),
7108         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."),
7109         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7110         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'."),
7111         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."),
7112         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'."),
7113         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."),
7114         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."),
7115         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."),
7116         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."),
7117         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."),
7118         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."),
7119         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'."),
7120         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}'."),
7121         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."),
7122         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}'."),
7123         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."),
7124         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}'."),
7125         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."),
7126         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."),
7127         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."),
7128         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."),
7129         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."),
7130         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."),
7131         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}'."),
7132         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."),
7133         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."),
7134         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."),
7135         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."),
7136         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 *'."),
7137         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."),
7138         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."),
7139         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."),
7140         _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."),
7141         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7142         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."),
7143         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."),
7144         _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."),
7145         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."),
7146         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."),
7147         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."),
7148         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."),
7149         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."),
7150         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."),
7151         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."),
7152         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."),
7153         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}'."),
7154         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."),
7155         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."),
7156         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."),
7157         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."),
7158         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."),
7159         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."),
7160         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."),
7161         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."),
7162         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."),
7163         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."),
7164         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."),
7165         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."),
7166         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."),
7167         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."),
7168         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."),
7169         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
7170         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
7171         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
7172         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."),
7173         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."),
7174         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}'."),
7175         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}'."),
7176         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."),
7177         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."),
7178         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."),
7179         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."),
7180         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."),
7181         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."),
7182         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."),
7183         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[]'."),
7184         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."),
7185         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."),
7186         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."),
7187         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}'?"),
7188         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}'?"),
7189         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."),
7190         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
7191         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}."),
7192         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."),
7193         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."),
7194         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}."),
7195         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}'."),
7196         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?"),
7197         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}'?"),
7198         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."),
7199         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."),
7200         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."),
7201         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."),
7202         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."),
7203         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."),
7204         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."),
7205         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
7206         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
7207         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."),
7208         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."),
7209         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."),
7210         Property_0_is_a_static_member_of_type_1: diag(2576, ts.DiagnosticCategory.Error, "Property_0_is_a_static_member_of_type_1_2576", "Property '{0}' is a static member of type '{1}'"),
7211         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
7212         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
7213         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`."),
7214         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`."),
7215         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha: diag(2582, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`."),
7216         Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later: diag(2583, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2583", "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later."),
7217         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'."),
7218         _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."),
7219         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
7220         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
7221         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."),
7222         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."),
7223         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."),
7224         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig: diag(2591, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_th_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig."),
7225         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig: diag(2592, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_an_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery` and then add `jquery` to the types field in your tsconfig."),
7226         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig: diag(2593, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashje_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
7227         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."),
7228         _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."),
7229         _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."),
7230         _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."),
7231         _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."),
7232         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."),
7233         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."),
7234         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."),
7235         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}'."),
7236         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."),
7237         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."),
7238         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."),
7239         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."),
7240         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."),
7241         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."),
7242         _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."),
7243         _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."),
7244         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."),
7245         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?"),
7246         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?"),
7247         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}'."),
7248         _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."),
7249         _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."),
7250         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."),
7251         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."),
7252         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."),
7253         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}'."),
7254         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."),
7255         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."),
7256         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."),
7257         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}'."),
7258         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."),
7259         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."),
7260         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."),
7261         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}'?"),
7262         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}'?"),
7263         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."),
7264         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."),
7265         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."),
7266         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."),
7267         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."),
7268         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."),
7269         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."),
7270         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."),
7271         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."),
7272         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."),
7273         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."),
7274         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."),
7275         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."),
7276         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."),
7277         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}'."),
7278         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'."),
7279         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."),
7280         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."),
7281         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."),
7282         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."),
7283         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}'."),
7284         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."),
7285         _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."),
7286         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."),
7287         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}'."),
7288         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'?"),
7289         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."),
7290         _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."),
7291         _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."),
7292         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}'."),
7293         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),
7294         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?"),
7295         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."),
7296         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."),
7297         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}'."),
7298         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."),
7299         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."),
7300         _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."),
7301         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."),
7302         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."),
7303         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."),
7304         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."),
7305         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."),
7306         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."),
7307         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."),
7308         _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."),
7309         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."),
7310         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."),
7311         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}\"]'?"),
7312         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."),
7313         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."),
7314         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."),
7315         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}'."),
7316         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
7317         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."),
7318         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?"),
7319         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'."),
7320         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'."),
7321         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'."),
7322         Module_0_has_no_exported_member_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_2_2724", "Module '{0}' has no exported member '{1}'. Did you mean '{2}'?"),
7323         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}."),
7324         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
7325         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}'?"),
7326         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
7327         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."),
7328         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."),
7329         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(...)'."),
7330         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"),
7331         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
7332         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
7333         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}'?"),
7334         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}'."),
7335         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."),
7336         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."),
7337         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}"),
7338         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."),
7339         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}'."),
7340         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."),
7341         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."),
7342         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."),
7343         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."),
7344         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."),
7345         _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}'."),
7346         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."),
7347         _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}'?"),
7348         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
7349         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."),
7350         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
7351         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
7352         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
7353         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."),
7354         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."),
7355         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
7356         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."),
7357         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."),
7358         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."),
7359         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
7360         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."),
7361         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}'."),
7362         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}'."),
7363         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}'."),
7364         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}'."),
7365         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."),
7366         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."),
7367         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
7368         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."),
7369         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
7370         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."),
7371         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
7372         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?"),
7373         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."),
7374         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."),
7375         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."),
7376         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."),
7377         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."),
7378         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."),
7379         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."),
7380         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
7381         _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."),
7382         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."),
7383         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
7384         _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."),
7385         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."),
7386         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."),
7387         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."),
7388         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}'."),
7389         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}'."),
7390         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}'."),
7391         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}'."),
7392         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}'."),
7393         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}'."),
7394         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}'."),
7395         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}'."),
7396         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}'."),
7397         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}'."),
7398         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}'."),
7399         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}'."),
7400         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."),
7401         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}'."),
7402         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}'."),
7403         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."),
7404         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}'."),
7405         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}'."),
7406         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."),
7407         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}'."),
7408         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}'."),
7409         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}'."),
7410         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}'."),
7411         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}'."),
7412         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}'."),
7413         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}'."),
7414         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}'."),
7415         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."),
7416         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}'."),
7417         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}'."),
7418         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."),
7419         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}'."),
7420         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}'."),
7421         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}'."),
7422         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}'."),
7423         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}'."),
7424         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}'."),
7425         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}'."),
7426         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}'."),
7427         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."),
7428         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}'."),
7429         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}'."),
7430         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."),
7431         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}'."),
7432         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}'."),
7433         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}'."),
7434         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}'."),
7435         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."),
7436         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}'."),
7437         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}'."),
7438         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."),
7439         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}'."),
7440         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}'."),
7441         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}'."),
7442         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}'."),
7443         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}'."),
7444         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}'."),
7445         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."),
7446         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}'."),
7447         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}'."),
7448         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."),
7449         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}'."),
7450         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}'."),
7451         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}'."),
7452         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}'."),
7453         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."),
7454         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}'."),
7455         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}'."),
7456         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}'."),
7457         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}'."),
7458         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}'."),
7459         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."),
7460         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}'."),
7461         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}'."),
7462         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."),
7463         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."),
7464         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}'."),
7465         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}'."),
7466         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."),
7467         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}'."),
7468         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}'."),
7469         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}'."),
7470         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}'."),
7471         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}'."),
7472         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}'."),
7473         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."),
7474         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}'."),
7475         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}'."),
7476         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."),
7477         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."),
7478         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
7479         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."),
7480         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."),
7481         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}'."),
7482         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
7483         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}."),
7484         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
7485         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}."),
7486         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}'?"),
7487         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}."),
7488         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."),
7489         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."),
7490         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'."),
7491         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."),
7492         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}'."),
7493         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}'."),
7494         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}'."),
7495         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."),
7496         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."),
7497         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}'."),
7498         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}'."),
7499         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."),
7500         Option_paths_cannot_be_used_without_specifying_baseUrl_option: diag(5060, ts.DiagnosticCategory.Error, "Option_paths_cannot_be_used_without_specifying_baseUrl_option_5060", "Option 'paths' cannot be used without specifying '--baseUrl' option."),
7501         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."),
7502         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."),
7503         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."),
7504         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}'."),
7505         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}'."),
7506         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."),
7507         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."),
7508         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."),
7509         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}'."),
7510         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."),
7511         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'."),
7512         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
7513         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}."),
7514         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."),
7515         _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}'."),
7516         _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."),
7517         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}'?"),
7518         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
7519         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}'?"),
7520         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}."),
7521         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}."),
7522         _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}'."),
7523         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
7524         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."),
7525         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."),
7526         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."),
7527         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
7528         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."),
7529         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."),
7530         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
7531         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
7532         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."),
7533         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."),
7534         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
7535         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
7536         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."),
7537         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
7538         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."),
7539         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
7540         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'."),
7541         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'."),
7542         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
7543         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
7544         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'."),
7545         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
7546         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
7547         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
7548         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
7549         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
7550         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
7551         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."),
7552         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
7553         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
7554         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
7555         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
7556         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
7557         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
7558         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
7559         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
7560         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
7561         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
7562         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
7563         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}'."),
7564         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}."),
7565         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}'."),
7566         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
7567         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
7568         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
7569         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."),
7570         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
7571         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}."),
7572         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."),
7573         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."),
7574         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."),
7575         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."),
7576         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)."),
7577         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
7578         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."),
7579         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
7580         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."),
7581         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."),
7582         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)."),
7583         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."),
7584         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
7585         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."),
7586         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)."),
7587         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."),
7588         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."),
7589         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."),
7590         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."),
7591         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."),
7592         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."),
7593         Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."),
7594         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."),
7595         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}."),
7596         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."),
7597         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"),
7598         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."),
7599         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
7600         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}'."),
7601         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}'."),
7602         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}'. ========"),
7603         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
7604         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}'."),
7605         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
7606         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}'."),
7607         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}'."),
7608         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}'."),
7609         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
7610         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."),
7611         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}'."),
7612         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
7613         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."),
7614         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}'."),
7615         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
7616         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."),
7617         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}'."),
7618         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}'."),
7619         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}'."),
7620         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}'."),
7621         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}'."),
7622         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}'."),
7623         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
7624         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
7625         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."),
7626         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
7627         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'?"),
7628         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."),
7629         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}'. ========"),
7630         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
7631         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
7632         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}. ========"),
7633         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. ========"),
7634         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
7635         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."),
7636         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. ========"),
7637         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."),
7638         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}'."),
7639         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."),
7640         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}'. ========"),
7641         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. ========"),
7642         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}'."),
7643         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'."),
7644         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."),
7645         _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),
7646         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
7647         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
7648         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."),
7649         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}'."),
7650         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),
7651         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
7652         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}'."),
7653         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."),
7654         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."),
7655         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}'."),
7656         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."),
7657         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'."),
7658         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}'."),
7659         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."),
7660         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
7661         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
7662         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."),
7663         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."),
7664         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')."),
7665         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."),
7666         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."),
7667         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')"),
7668         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."),
7669         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)."),
7670         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."),
7671         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."),
7672         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."),
7673         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
7674         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."),
7675         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."),
7676         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
7677         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
7678         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'."),
7679         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."),
7680         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
7681         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"),
7682         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
7683         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
7684         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
7685         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
7686         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
7687         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
7688         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
7689         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
7690         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'."),
7691         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
7692         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
7693         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
7694         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."),
7695         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."),
7696         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."),
7697         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
7698         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."),
7699         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
7700         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."),
7701         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."),
7702         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),
7703         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."),
7704         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."),
7705         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)."),
7706         _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),
7707         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
7708         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
7709         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
7710         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}"),
7711         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
7712         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}"),
7713         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
7714         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
7715         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused"),
7716         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."),
7717         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}'."),
7718         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}'."),
7719         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."),
7720         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."),
7721         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."),
7722         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?"),
7723         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?"),
7724         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."),
7725         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}'."),
7726         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
7727         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
7728         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}'. ========"),
7729         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}. ========"),
7730         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."),
7731         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."),
7732         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."),
7733         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
7734         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
7735         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'."),
7736         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'."),
7737         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'."),
7738         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."),
7739         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}'."),
7740         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."),
7741         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}."),
7742         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."),
7743         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."),
7744         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
7745         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
7746         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."),
7747         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}'."),
7748         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."),
7749         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."),
7750         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"),
7751         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"),
7752         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}'"),
7753         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}'"),
7754         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"),
7755         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"),
7756         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"),
7757         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
7758         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}"),
7759         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}'"),
7760         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
7761         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
7762         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"),
7763         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
7764         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"),
7765         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"),
7766         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"),
7767         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
7768         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
7769         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')"),
7770         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"),
7771         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."),
7772         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."),
7773         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}'..."),
7774         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"),
7775         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
7776         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}'"),
7777         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}'"),
7778         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}'"),
7779         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}'"),
7780         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
7781         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."),
7782         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"),
7783         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}'"),
7784         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"),
7785         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"),
7786         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."),
7787         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}'"),
7788         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."),
7789         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."),
7790         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."),
7791         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?"),
7792         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."),
7793         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."),
7794         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."),
7795         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."),
7796         _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."),
7797         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."),
7798         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."),
7799         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."),
7800         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'."),
7801         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."),
7802         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."),
7803         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."),
7804         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."),
7805         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."),
7806         _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."),
7807         _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."),
7808         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."),
7809         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."),
7810         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."),
7811         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
7812         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
7813         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
7814         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."),
7815         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."),
7816         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."),
7817         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."),
7818         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."),
7819         Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
7820         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}'."),
7821         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'."),
7822         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."),
7823         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."),
7824         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}`"),
7825         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'."),
7826         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."),
7827         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."),
7828         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."),
7829         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."),
7830         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."),
7831         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."),
7832         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."),
7833         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."),
7834         _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."),
7835         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}'?"),
7836         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}'?"),
7837         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}'."),
7838         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}'."),
7839         _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."),
7840         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
7841         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."),
7842         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."),
7843         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."),
7844         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."),
7845         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."),
7846         _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."),
7847         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."),
7848         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."),
7849         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."),
7850         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."),
7851         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."),
7852         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."),
7853         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."),
7854         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}'."),
7855         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}'."),
7856         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
7857         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."),
7858         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."),
7859         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."),
7860         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."),
7861         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."),
7862         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."),
7863         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."),
7864         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."),
7865         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."),
7866         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."),
7867         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."),
7868         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."),
7869         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}'."),
7870         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."),
7871         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
7872         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
7873         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."),
7874         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."),
7875         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'."),
7876         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."),
7877         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}'."),
7878         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
7879         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."),
7880         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'."),
7881         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."),
7882         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."),
7883         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."),
7884         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."),
7885         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
7886         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."),
7887         _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}'?"),
7888         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."),
7889         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."),
7890         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."),
7891         JSX_fragment_is_not_supported_when_using_jsxFactory: diag(17016, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_jsxFactory_17016", "JSX fragment is not supported when using --jsxFactory"),
7892         JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma: diag(17017, ts.DiagnosticCategory.Error, "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017", "JSX fragment is not supported when using an inline JSX factory pragma"),
7893         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}'?"),
7894         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}"),
7895         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."),
7896         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."),
7897         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}'."),
7898         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."),
7899         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."),
7900         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."),
7901         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."),
7902         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."),
7903         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."),
7904         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."),
7905         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."),
7906         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
7907         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"),
7908         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
7909         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
7910         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
7911         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
7912         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
7913         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
7914         Remove_destructuring: diag(90009, ts.DiagnosticCategory.Message, "Remove_destructuring_90009", "Remove destructuring"),
7915         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
7916         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
7917         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
7918         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
7919         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
7920         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}\""),
7921         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
7922         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
7923         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
7924         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
7925         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
7926         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
7927         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
7928         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
7929         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
7930         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
7931         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}'"),
7932         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
7933         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
7934         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
7935         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
7936         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
7937         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
7938         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}\""),
7939         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
7940         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
7941         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
7942         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
7943         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
7944         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
7945         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
7946         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
7947         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
7948         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
7949         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
7950         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
7951         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
7952         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
7953         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
7954         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
7955         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
7956         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
7957         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
7958         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
7959         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
7960         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}'"),
7961         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
7962         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
7963         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
7964         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"),
7965         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
7966         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
7967         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"),
7968         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"),
7969         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"),
7970         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)"),
7971         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
7972         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
7973         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
7974         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
7975         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"),
7976         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"),
7977         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
7978         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
7979         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
7980         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
7981         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"),
7982         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
7983         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
7984         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
7985         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
7986         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
7987         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
7988         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
7989         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
7990         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
7991         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
7992         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
7993         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
7994         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
7995         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
7996         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
7997         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"),
7998         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
7999         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8000         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8001         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8002         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8003         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8004         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8005         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8006         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8007         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8008         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"),
8009         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"),
8010         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8011         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"),
8012         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"),
8013         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"),
8014         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8015         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8016         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8017         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8018         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8019         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"),
8020         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8021         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8022         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8023         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8024         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8025         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8026         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8027         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"),
8028         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8029         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8030         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8031         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8032         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8033         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8034         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'"),
8035         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8036         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"),
8037         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}'"),
8038         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}'"),
8039         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"),
8040         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"),
8041         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8042         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8043         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8044         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"),
8045         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"),
8046         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8047         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"),
8048         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"),
8049         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"),
8050         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8051         Remove_block_body_braces: diag(95112, ts.DiagnosticCategory.Message, "Remove_block_body_braces_95112", "Remove block body braces"),
8052         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"),
8053         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8054         Remove_all_incorrect_body_block_braces: diag(95115, ts.DiagnosticCategory.Message, "Remove_all_incorrect_body_block_braces_95115", "Remove all incorrect body block braces"),
8055         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8056         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."),
8057         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'."),
8058         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?"),
8059         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"),
8060         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."),
8061         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."),
8062         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8063         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."),
8064         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."),
8065         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}'."),
8066         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."),
8067         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"),
8068         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"),
8069         _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"),
8070         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."),
8071         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."),
8072         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."),
8073         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."),
8074         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."),
8075         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."),
8076         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."),
8077         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."),
8078         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."),
8079         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."),
8080         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."),
8081     };
8082 })(ts || (ts = {}));
8083 var ts;
8084 (function (ts) {
8085     var _a;
8086     /* @internal */
8087     function tokenIsIdentifierOrKeyword(token) {
8088         return token >= 75 /* Identifier */;
8089     }
8090     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
8091     /* @internal */
8092     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
8093         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
8094     }
8095     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
8096     var textToKeywordObj = (_a = {
8097             abstract: 122 /* AbstractKeyword */,
8098             any: 125 /* AnyKeyword */,
8099             as: 123 /* AsKeyword */,
8100             asserts: 124 /* AssertsKeyword */,
8101             bigint: 151 /* BigIntKeyword */,
8102             boolean: 128 /* BooleanKeyword */,
8103             break: 77 /* BreakKeyword */,
8104             case: 78 /* CaseKeyword */,
8105             catch: 79 /* CatchKeyword */,
8106             class: 80 /* ClassKeyword */,
8107             continue: 82 /* ContinueKeyword */,
8108             const: 81 /* ConstKeyword */
8109         },
8110         _a["" + "constructor"] = 129 /* ConstructorKeyword */,
8111         _a.debugger = 83 /* DebuggerKeyword */,
8112         _a.declare = 130 /* DeclareKeyword */,
8113         _a.default = 84 /* DefaultKeyword */,
8114         _a.delete = 85 /* DeleteKeyword */,
8115         _a.do = 86 /* DoKeyword */,
8116         _a.else = 87 /* ElseKeyword */,
8117         _a.enum = 88 /* EnumKeyword */,
8118         _a.export = 89 /* ExportKeyword */,
8119         _a.extends = 90 /* ExtendsKeyword */,
8120         _a.false = 91 /* FalseKeyword */,
8121         _a.finally = 92 /* FinallyKeyword */,
8122         _a.for = 93 /* ForKeyword */,
8123         _a.from = 149 /* FromKeyword */,
8124         _a.function = 94 /* FunctionKeyword */,
8125         _a.get = 131 /* GetKeyword */,
8126         _a.if = 95 /* IfKeyword */,
8127         _a.implements = 113 /* ImplementsKeyword */,
8128         _a.import = 96 /* ImportKeyword */,
8129         _a.in = 97 /* InKeyword */,
8130         _a.infer = 132 /* InferKeyword */,
8131         _a.instanceof = 98 /* InstanceOfKeyword */,
8132         _a.interface = 114 /* InterfaceKeyword */,
8133         _a.is = 133 /* IsKeyword */,
8134         _a.keyof = 134 /* KeyOfKeyword */,
8135         _a.let = 115 /* LetKeyword */,
8136         _a.module = 135 /* ModuleKeyword */,
8137         _a.namespace = 136 /* NamespaceKeyword */,
8138         _a.never = 137 /* NeverKeyword */,
8139         _a.new = 99 /* NewKeyword */,
8140         _a.null = 100 /* NullKeyword */,
8141         _a.number = 140 /* NumberKeyword */,
8142         _a.object = 141 /* ObjectKeyword */,
8143         _a.package = 116 /* PackageKeyword */,
8144         _a.private = 117 /* PrivateKeyword */,
8145         _a.protected = 118 /* ProtectedKeyword */,
8146         _a.public = 119 /* PublicKeyword */,
8147         _a.readonly = 138 /* ReadonlyKeyword */,
8148         _a.require = 139 /* RequireKeyword */,
8149         _a.global = 150 /* GlobalKeyword */,
8150         _a.return = 101 /* ReturnKeyword */,
8151         _a.set = 142 /* SetKeyword */,
8152         _a.static = 120 /* StaticKeyword */,
8153         _a.string = 143 /* StringKeyword */,
8154         _a.super = 102 /* SuperKeyword */,
8155         _a.switch = 103 /* SwitchKeyword */,
8156         _a.symbol = 144 /* SymbolKeyword */,
8157         _a.this = 104 /* ThisKeyword */,
8158         _a.throw = 105 /* ThrowKeyword */,
8159         _a.true = 106 /* TrueKeyword */,
8160         _a.try = 107 /* TryKeyword */,
8161         _a.type = 145 /* TypeKeyword */,
8162         _a.typeof = 108 /* TypeOfKeyword */,
8163         _a.undefined = 146 /* UndefinedKeyword */,
8164         _a.unique = 147 /* UniqueKeyword */,
8165         _a.unknown = 148 /* UnknownKeyword */,
8166         _a.var = 109 /* VarKeyword */,
8167         _a.void = 110 /* VoidKeyword */,
8168         _a.while = 111 /* WhileKeyword */,
8169         _a.with = 112 /* WithKeyword */,
8170         _a.yield = 121 /* YieldKeyword */,
8171         _a.async = 126 /* AsyncKeyword */,
8172         _a.await = 127 /* AwaitKeyword */,
8173         _a.of = 152 /* OfKeyword */,
8174         _a);
8175     var textToKeyword = ts.createMapFromTemplate(textToKeywordObj);
8176     var textToToken = ts.createMapFromTemplate(__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 */, "^=": 74 /* CaretEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ }));
8177     /*
8178         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
8179         IdentifierStart ::
8180             Can contain Unicode 3.0.0 categories:
8181             Uppercase letter (Lu),
8182             Lowercase letter (Ll),
8183             Titlecase letter (Lt),
8184             Modifier letter (Lm),
8185             Other letter (Lo), or
8186             Letter number (Nl).
8187         IdentifierPart :: =
8188             Can contain IdentifierStart + Unicode 3.0.0 categories:
8189             Non-spacing mark (Mn),
8190             Combining spacing mark (Mc),
8191             Decimal number (Nd), or
8192             Connector punctuation (Pc).
8193
8194         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
8195         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
8196     */
8197     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,];
8198     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,];
8199     /*
8200         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
8201         IdentifierStart ::
8202             Can contain Unicode 6.2 categories:
8203             Uppercase letter (Lu),
8204             Lowercase letter (Ll),
8205             Titlecase letter (Lt),
8206             Modifier letter (Lm),
8207             Other letter (Lo), or
8208             Letter number (Nl).
8209         IdentifierPart ::
8210             Can contain IdentifierStart + Unicode 6.2 categories:
8211             Non-spacing mark (Mn),
8212             Combining spacing mark (Mc),
8213             Decimal number (Nd),
8214             Connector punctuation (Pc),
8215             <ZWNJ>, or
8216             <ZWJ>.
8217
8218         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
8219         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
8220     */
8221     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,];
8222     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,];
8223     /**
8224      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
8225      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
8226      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
8227      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
8228      */
8229     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];
8230     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];
8231     /**
8232      * Test for whether a single line comment's text contains a directive.
8233      */
8234     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
8235     /**
8236      * Test for whether a multi-line comment's last line contains a directive.
8237      */
8238     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
8239     function lookupInUnicodeMap(code, map) {
8240         // Bail out quickly if it couldn't possibly be in the map.
8241         if (code < map[0]) {
8242             return false;
8243         }
8244         // Perform binary search in one of the Unicode range maps
8245         var lo = 0;
8246         var hi = map.length;
8247         var mid;
8248         while (lo + 1 < hi) {
8249             mid = lo + (hi - lo) / 2;
8250             // mid has to be even to catch a range's beginning
8251             mid -= mid % 2;
8252             if (map[mid] <= code && code <= map[mid + 1]) {
8253                 return true;
8254             }
8255             if (code < map[mid]) {
8256                 hi = mid;
8257             }
8258             else {
8259                 lo = mid + 2;
8260             }
8261         }
8262         return false;
8263     }
8264     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
8265         return languageVersion >= 2 /* ES2015 */ ?
8266             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
8267             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
8268                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
8269     }
8270     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
8271     function isUnicodeIdentifierPart(code, languageVersion) {
8272         return languageVersion >= 2 /* ES2015 */ ?
8273             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
8274             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
8275                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
8276     }
8277     function makeReverseMap(source) {
8278         var result = [];
8279         source.forEach(function (value, name) {
8280             result[value] = name;
8281         });
8282         return result;
8283     }
8284     var tokenStrings = makeReverseMap(textToToken);
8285     function tokenToString(t) {
8286         return tokenStrings[t];
8287     }
8288     ts.tokenToString = tokenToString;
8289     /* @internal */
8290     function stringToToken(s) {
8291         return textToToken.get(s);
8292     }
8293     ts.stringToToken = stringToToken;
8294     /* @internal */
8295     function computeLineStarts(text) {
8296         var result = new Array();
8297         var pos = 0;
8298         var lineStart = 0;
8299         while (pos < text.length) {
8300             var ch = text.charCodeAt(pos);
8301             pos++;
8302             switch (ch) {
8303                 case 13 /* carriageReturn */:
8304                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
8305                         pos++;
8306                     }
8307                 // falls through
8308                 case 10 /* lineFeed */:
8309                     result.push(lineStart);
8310                     lineStart = pos;
8311                     break;
8312                 default:
8313                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
8314                         result.push(lineStart);
8315                         lineStart = pos;
8316                     }
8317                     break;
8318             }
8319         }
8320         result.push(lineStart);
8321         return result;
8322     }
8323     ts.computeLineStarts = computeLineStarts;
8324     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
8325         return sourceFile.getPositionOfLineAndCharacter ?
8326             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
8327             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
8328     }
8329     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
8330     /* @internal */
8331     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
8332         if (line < 0 || line >= lineStarts.length) {
8333             if (allowEdits) {
8334                 // Clamp line to nearest allowable value
8335                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
8336             }
8337             else {
8338                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
8339             }
8340         }
8341         var res = lineStarts[line] + character;
8342         if (allowEdits) {
8343             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
8344             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
8345             // apply them to the computed position to improve accuracy
8346             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
8347         }
8348         if (line < lineStarts.length - 1) {
8349             ts.Debug.assert(res < lineStarts[line + 1]);
8350         }
8351         else if (debugText !== undefined) {
8352             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
8353         }
8354         return res;
8355     }
8356     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
8357     /* @internal */
8358     function getLineStarts(sourceFile) {
8359         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
8360     }
8361     ts.getLineStarts = getLineStarts;
8362     /* @internal */
8363     function computeLineAndCharacterOfPosition(lineStarts, position) {
8364         var lineNumber = computeLineOfPosition(lineStarts, position);
8365         return {
8366             line: lineNumber,
8367             character: position - lineStarts[lineNumber]
8368         };
8369     }
8370     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
8371     /**
8372      * @internal
8373      * We assume the first line starts at position 0 and 'position' is non-negative.
8374      */
8375     function computeLineOfPosition(lineStarts, position, lowerBound) {
8376         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
8377         if (lineNumber < 0) {
8378             // If the actual position was not found,
8379             // the binary search returns the 2's-complement of the next line start
8380             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
8381             // then the search will return -2.
8382             //
8383             // We want the index of the previous line start, so we subtract 1.
8384             // Review 2's-complement if this is confusing.
8385             lineNumber = ~lineNumber - 1;
8386             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
8387         }
8388         return lineNumber;
8389     }
8390     ts.computeLineOfPosition = computeLineOfPosition;
8391     /** @internal */
8392     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
8393         if (pos1 === pos2)
8394             return 0;
8395         var lineStarts = getLineStarts(sourceFile);
8396         var lower = Math.min(pos1, pos2);
8397         var isNegative = lower === pos2;
8398         var upper = isNegative ? pos1 : pos2;
8399         var lowerLine = computeLineOfPosition(lineStarts, lower);
8400         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
8401         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
8402     }
8403     ts.getLinesBetweenPositions = getLinesBetweenPositions;
8404     function getLineAndCharacterOfPosition(sourceFile, position) {
8405         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
8406     }
8407     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
8408     function isWhiteSpaceLike(ch) {
8409         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
8410     }
8411     ts.isWhiteSpaceLike = isWhiteSpaceLike;
8412     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
8413     function isWhiteSpaceSingleLine(ch) {
8414         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
8415         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
8416         return ch === 32 /* space */ ||
8417             ch === 9 /* tab */ ||
8418             ch === 11 /* verticalTab */ ||
8419             ch === 12 /* formFeed */ ||
8420             ch === 160 /* nonBreakingSpace */ ||
8421             ch === 133 /* nextLine */ ||
8422             ch === 5760 /* ogham */ ||
8423             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
8424             ch === 8239 /* narrowNoBreakSpace */ ||
8425             ch === 8287 /* mathematicalSpace */ ||
8426             ch === 12288 /* ideographicSpace */ ||
8427             ch === 65279 /* byteOrderMark */;
8428     }
8429     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
8430     function isLineBreak(ch) {
8431         // ES5 7.3:
8432         // The ECMAScript line terminator characters are listed in Table 3.
8433         //     Table 3: Line Terminator Characters
8434         //     Code Unit Value     Name                    Formal Name
8435         //     \u000A              Line Feed               <LF>
8436         //     \u000D              Carriage Return         <CR>
8437         //     \u2028              Line separator          <LS>
8438         //     \u2029              Paragraph separator     <PS>
8439         // Only the characters in Table 3 are treated as line terminators. Other new line or line
8440         // breaking characters are treated as white space but not as line terminators.
8441         return ch === 10 /* lineFeed */ ||
8442             ch === 13 /* carriageReturn */ ||
8443             ch === 8232 /* lineSeparator */ ||
8444             ch === 8233 /* paragraphSeparator */;
8445     }
8446     ts.isLineBreak = isLineBreak;
8447     function isDigit(ch) {
8448         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
8449     }
8450     function isHexDigit(ch) {
8451         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
8452     }
8453     function isCodePoint(code) {
8454         return code <= 0x10FFFF;
8455     }
8456     /* @internal */
8457     function isOctalDigit(ch) {
8458         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
8459     }
8460     ts.isOctalDigit = isOctalDigit;
8461     function couldStartTrivia(text, pos) {
8462         // Keep in sync with skipTrivia
8463         var ch = text.charCodeAt(pos);
8464         switch (ch) {
8465             case 13 /* carriageReturn */:
8466             case 10 /* lineFeed */:
8467             case 9 /* tab */:
8468             case 11 /* verticalTab */:
8469             case 12 /* formFeed */:
8470             case 32 /* space */:
8471             case 47 /* slash */:
8472             // starts of normal trivia
8473             // falls through
8474             case 60 /* lessThan */:
8475             case 124 /* bar */:
8476             case 61 /* equals */:
8477             case 62 /* greaterThan */:
8478                 // Starts of conflict marker trivia
8479                 return true;
8480             case 35 /* hash */:
8481                 // Only if its the beginning can we have #! trivia
8482                 return pos === 0;
8483             default:
8484                 return ch > 127 /* maxAsciiCharacter */;
8485         }
8486     }
8487     ts.couldStartTrivia = couldStartTrivia;
8488     /* @internal */
8489     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
8490         if (stopAtComments === void 0) { stopAtComments = false; }
8491         if (ts.positionIsSynthesized(pos)) {
8492             return pos;
8493         }
8494         // Keep in sync with couldStartTrivia
8495         while (true) {
8496             var ch = text.charCodeAt(pos);
8497             switch (ch) {
8498                 case 13 /* carriageReturn */:
8499                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8500                         pos++;
8501                     }
8502                 // falls through
8503                 case 10 /* lineFeed */:
8504                     pos++;
8505                     if (stopAfterLineBreak) {
8506                         return pos;
8507                     }
8508                     continue;
8509                 case 9 /* tab */:
8510                 case 11 /* verticalTab */:
8511                 case 12 /* formFeed */:
8512                 case 32 /* space */:
8513                     pos++;
8514                     continue;
8515                 case 47 /* slash */:
8516                     if (stopAtComments) {
8517                         break;
8518                     }
8519                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
8520                         pos += 2;
8521                         while (pos < text.length) {
8522                             if (isLineBreak(text.charCodeAt(pos))) {
8523                                 break;
8524                             }
8525                             pos++;
8526                         }
8527                         continue;
8528                     }
8529                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
8530                         pos += 2;
8531                         while (pos < text.length) {
8532                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8533                                 pos += 2;
8534                                 break;
8535                             }
8536                             pos++;
8537                         }
8538                         continue;
8539                     }
8540                     break;
8541                 case 60 /* lessThan */:
8542                 case 124 /* bar */:
8543                 case 61 /* equals */:
8544                 case 62 /* greaterThan */:
8545                     if (isConflictMarkerTrivia(text, pos)) {
8546                         pos = scanConflictMarkerTrivia(text, pos);
8547                         continue;
8548                     }
8549                     break;
8550                 case 35 /* hash */:
8551                     if (pos === 0 && isShebangTrivia(text, pos)) {
8552                         pos = scanShebangTrivia(text, pos);
8553                         continue;
8554                     }
8555                     break;
8556                 default:
8557                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8558                         pos++;
8559                         continue;
8560                     }
8561                     break;
8562             }
8563             return pos;
8564         }
8565     }
8566     ts.skipTrivia = skipTrivia;
8567     // All conflict markers consist of the same character repeated seven times.  If it is
8568     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
8569     var mergeConflictMarkerLength = "<<<<<<<".length;
8570     function isConflictMarkerTrivia(text, pos) {
8571         ts.Debug.assert(pos >= 0);
8572         // Conflict markers must be at the start of a line.
8573         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
8574             var ch = text.charCodeAt(pos);
8575             if ((pos + mergeConflictMarkerLength) < text.length) {
8576                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
8577                     if (text.charCodeAt(pos + i) !== ch) {
8578                         return false;
8579                     }
8580                 }
8581                 return ch === 61 /* equals */ ||
8582                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
8583             }
8584         }
8585         return false;
8586     }
8587     function scanConflictMarkerTrivia(text, pos, error) {
8588         if (error) {
8589             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
8590         }
8591         var ch = text.charCodeAt(pos);
8592         var len = text.length;
8593         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
8594             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
8595                 pos++;
8596             }
8597         }
8598         else {
8599             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
8600             // Consume everything from the start of a ||||||| or ======= marker to the start
8601             // of the next ======= or >>>>>>> marker.
8602             while (pos < len) {
8603                 var currentChar = text.charCodeAt(pos);
8604                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
8605                     break;
8606                 }
8607                 pos++;
8608             }
8609         }
8610         return pos;
8611     }
8612     var shebangTriviaRegex = /^#!.*/;
8613     /*@internal*/
8614     function isShebangTrivia(text, pos) {
8615         // Shebangs check must only be done at the start of the file
8616         ts.Debug.assert(pos === 0);
8617         return shebangTriviaRegex.test(text);
8618     }
8619     ts.isShebangTrivia = isShebangTrivia;
8620     /*@internal*/
8621     function scanShebangTrivia(text, pos) {
8622         var shebang = shebangTriviaRegex.exec(text)[0];
8623         pos = pos + shebang.length;
8624         return pos;
8625     }
8626     ts.scanShebangTrivia = scanShebangTrivia;
8627     /**
8628      * Invokes a callback for each comment range following the provided position.
8629      *
8630      * Single-line comment ranges include the leading double-slash characters but not the ending
8631      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
8632      * asterisk-slash characters.
8633      *
8634      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
8635      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
8636      * @param text The source text to scan.
8637      * @param pos The position at which to start scanning.
8638      * @param trailing If false, whitespace is skipped until the first line break and comments
8639      *      between that location and the next token are returned. If true, comments occurring
8640      *      between the given position and the next line break are returned.
8641      * @param cb The callback to execute as each comment range is encountered.
8642      * @param state A state value to pass to each iteration of the callback.
8643      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
8644      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
8645      *      return value of the callback.
8646      */
8647     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
8648         var pendingPos;
8649         var pendingEnd;
8650         var pendingKind;
8651         var pendingHasTrailingNewLine;
8652         var hasPendingCommentRange = false;
8653         var collecting = trailing;
8654         var accumulator = initial;
8655         if (pos === 0) {
8656             collecting = true;
8657             var shebang = getShebang(text);
8658             if (shebang) {
8659                 pos = shebang.length;
8660             }
8661         }
8662         scan: while (pos >= 0 && pos < text.length) {
8663             var ch = text.charCodeAt(pos);
8664             switch (ch) {
8665                 case 13 /* carriageReturn */:
8666                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
8667                         pos++;
8668                     }
8669                 // falls through
8670                 case 10 /* lineFeed */:
8671                     pos++;
8672                     if (trailing) {
8673                         break scan;
8674                     }
8675                     collecting = true;
8676                     if (hasPendingCommentRange) {
8677                         pendingHasTrailingNewLine = true;
8678                     }
8679                     continue;
8680                 case 9 /* tab */:
8681                 case 11 /* verticalTab */:
8682                 case 12 /* formFeed */:
8683                 case 32 /* space */:
8684                     pos++;
8685                     continue;
8686                 case 47 /* slash */:
8687                     var nextChar = text.charCodeAt(pos + 1);
8688                     var hasTrailingNewLine = false;
8689                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
8690                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
8691                         var startPos = pos;
8692                         pos += 2;
8693                         if (nextChar === 47 /* slash */) {
8694                             while (pos < text.length) {
8695                                 if (isLineBreak(text.charCodeAt(pos))) {
8696                                     hasTrailingNewLine = true;
8697                                     break;
8698                                 }
8699                                 pos++;
8700                             }
8701                         }
8702                         else {
8703                             while (pos < text.length) {
8704                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
8705                                     pos += 2;
8706                                     break;
8707                                 }
8708                                 pos++;
8709                             }
8710                         }
8711                         if (collecting) {
8712                             if (hasPendingCommentRange) {
8713                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8714                                 if (!reduce && accumulator) {
8715                                     // If we are not reducing and we have a truthy result, return it.
8716                                     return accumulator;
8717                                 }
8718                             }
8719                             pendingPos = startPos;
8720                             pendingEnd = pos;
8721                             pendingKind = kind;
8722                             pendingHasTrailingNewLine = hasTrailingNewLine;
8723                             hasPendingCommentRange = true;
8724                         }
8725                         continue;
8726                     }
8727                     break scan;
8728                 default:
8729                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
8730                         if (hasPendingCommentRange && isLineBreak(ch)) {
8731                             pendingHasTrailingNewLine = true;
8732                         }
8733                         pos++;
8734                         continue;
8735                     }
8736                     break scan;
8737             }
8738         }
8739         if (hasPendingCommentRange) {
8740             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
8741         }
8742         return accumulator;
8743     }
8744     function forEachLeadingCommentRange(text, pos, cb, state) {
8745         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
8746     }
8747     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
8748     function forEachTrailingCommentRange(text, pos, cb, state) {
8749         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
8750     }
8751     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
8752     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
8753         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
8754     }
8755     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
8756     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
8757         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
8758     }
8759     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
8760     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
8761         if (!comments) {
8762             comments = [];
8763         }
8764         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
8765         return comments;
8766     }
8767     function getLeadingCommentRanges(text, pos) {
8768         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8769     }
8770     ts.getLeadingCommentRanges = getLeadingCommentRanges;
8771     function getTrailingCommentRanges(text, pos) {
8772         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
8773     }
8774     ts.getTrailingCommentRanges = getTrailingCommentRanges;
8775     /** Optionally, get the shebang */
8776     function getShebang(text) {
8777         var match = shebangTriviaRegex.exec(text);
8778         if (match) {
8779             return match[0];
8780         }
8781     }
8782     ts.getShebang = getShebang;
8783     function isIdentifierStart(ch, languageVersion) {
8784         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8785             ch === 36 /* $ */ || ch === 95 /* _ */ ||
8786             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
8787     }
8788     ts.isIdentifierStart = isIdentifierStart;
8789     function isIdentifierPart(ch, languageVersion, identifierVariant) {
8790         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
8791             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
8792             // "-" and ":" are valid in JSX Identifiers
8793             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
8794             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
8795     }
8796     ts.isIdentifierPart = isIdentifierPart;
8797     /* @internal */
8798     function isIdentifierText(name, languageVersion, identifierVariant) {
8799         var ch = codePointAt(name, 0);
8800         if (!isIdentifierStart(ch, languageVersion)) {
8801             return false;
8802         }
8803         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
8804             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
8805                 return false;
8806             }
8807         }
8808         return true;
8809     }
8810     ts.isIdentifierText = isIdentifierText;
8811     // Creates a scanner over a (possibly unspecified) range of a piece of text.
8812     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
8813         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
8814         var text = textInitial;
8815         // Current position (end position of text of current token)
8816         var pos;
8817         // end of text
8818         var end;
8819         // Start position of whitespace before current token
8820         var startPos;
8821         // Start position of text of current token
8822         var tokenPos;
8823         var token;
8824         var tokenValue;
8825         var tokenFlags;
8826         var commentDirectives;
8827         var inJSDocType = 0;
8828         setText(text, start, length);
8829         var scanner = {
8830             getStartPos: function () { return startPos; },
8831             getTextPos: function () { return pos; },
8832             getToken: function () { return token; },
8833             getTokenPos: function () { return tokenPos; },
8834             getTokenText: function () { return text.substring(tokenPos, pos); },
8835             getTokenValue: function () { return tokenValue; },
8836             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
8837             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
8838             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
8839             isIdentifier: function () { return token === 75 /* Identifier */ || token > 112 /* LastReservedWord */; },
8840             isReservedWord: function () { return token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */; },
8841             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
8842             getCommentDirectives: function () { return commentDirectives; },
8843             getTokenFlags: function () { return tokenFlags; },
8844             reScanGreaterToken: reScanGreaterToken,
8845             reScanSlashToken: reScanSlashToken,
8846             reScanTemplateToken: reScanTemplateToken,
8847             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
8848             scanJsxIdentifier: scanJsxIdentifier,
8849             scanJsxAttributeValue: scanJsxAttributeValue,
8850             reScanJsxAttributeValue: reScanJsxAttributeValue,
8851             reScanJsxToken: reScanJsxToken,
8852             reScanLessThanToken: reScanLessThanToken,
8853             reScanQuestionToken: reScanQuestionToken,
8854             scanJsxToken: scanJsxToken,
8855             scanJsDocToken: scanJsDocToken,
8856             scan: scan,
8857             getText: getText,
8858             clearCommentDirectives: clearCommentDirectives,
8859             setText: setText,
8860             setScriptTarget: setScriptTarget,
8861             setLanguageVariant: setLanguageVariant,
8862             setOnError: setOnError,
8863             setTextPos: setTextPos,
8864             setInJSDocType: setInJSDocType,
8865             tryScan: tryScan,
8866             lookAhead: lookAhead,
8867             scanRange: scanRange,
8868         };
8869         if (ts.Debug.isDebugging) {
8870             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
8871                 get: function () {
8872                     var text = scanner.getText();
8873                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
8874                 },
8875             });
8876         }
8877         return scanner;
8878         function error(message, errPos, length) {
8879             if (errPos === void 0) { errPos = pos; }
8880             if (onError) {
8881                 var oldPos = pos;
8882                 pos = errPos;
8883                 onError(message, length || 0);
8884                 pos = oldPos;
8885             }
8886         }
8887         function scanNumberFragment() {
8888             var start = pos;
8889             var allowSeparator = false;
8890             var isPreviousTokenSeparator = false;
8891             var result = "";
8892             while (true) {
8893                 var ch = text.charCodeAt(pos);
8894                 if (ch === 95 /* _ */) {
8895                     tokenFlags |= 512 /* ContainsSeparator */;
8896                     if (allowSeparator) {
8897                         allowSeparator = false;
8898                         isPreviousTokenSeparator = true;
8899                         result += text.substring(start, pos);
8900                     }
8901                     else if (isPreviousTokenSeparator) {
8902                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
8903                     }
8904                     else {
8905                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
8906                     }
8907                     pos++;
8908                     start = pos;
8909                     continue;
8910                 }
8911                 if (isDigit(ch)) {
8912                     allowSeparator = true;
8913                     isPreviousTokenSeparator = false;
8914                     pos++;
8915                     continue;
8916                 }
8917                 break;
8918             }
8919             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
8920                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
8921             }
8922             return result + text.substring(start, pos);
8923         }
8924         function scanNumber() {
8925             var start = pos;
8926             var mainFragment = scanNumberFragment();
8927             var decimalFragment;
8928             var scientificFragment;
8929             if (text.charCodeAt(pos) === 46 /* dot */) {
8930                 pos++;
8931                 decimalFragment = scanNumberFragment();
8932             }
8933             var end = pos;
8934             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
8935                 pos++;
8936                 tokenFlags |= 16 /* Scientific */;
8937                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
8938                     pos++;
8939                 var preNumericPart = pos;
8940                 var finalFragment = scanNumberFragment();
8941                 if (!finalFragment) {
8942                     error(ts.Diagnostics.Digit_expected);
8943                 }
8944                 else {
8945                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
8946                     end = pos;
8947                 }
8948             }
8949             var result;
8950             if (tokenFlags & 512 /* ContainsSeparator */) {
8951                 result = mainFragment;
8952                 if (decimalFragment) {
8953                     result += "." + decimalFragment;
8954                 }
8955                 if (scientificFragment) {
8956                     result += scientificFragment;
8957                 }
8958             }
8959             else {
8960                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
8961             }
8962             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
8963                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
8964                 return {
8965                     type: 8 /* NumericLiteral */,
8966                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
8967                 };
8968             }
8969             else {
8970                 tokenValue = result;
8971                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
8972                 checkForIdentifierStartAfterNumericLiteral(start);
8973                 return { type: type, value: tokenValue };
8974             }
8975         }
8976         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
8977             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
8978                 return;
8979             }
8980             var identifierStart = pos;
8981             var length = scanIdentifierParts().length;
8982             if (length === 1 && text[identifierStart] === "n") {
8983                 if (isScientific) {
8984                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
8985                 }
8986                 else {
8987                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
8988                 }
8989             }
8990             else {
8991                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
8992                 pos = identifierStart;
8993             }
8994         }
8995         function scanOctalDigits() {
8996             var start = pos;
8997             while (isOctalDigit(text.charCodeAt(pos))) {
8998                 pos++;
8999             }
9000             return +(text.substring(start, pos));
9001         }
9002         /**
9003          * Scans the given number of hexadecimal digits in the text,
9004          * returning -1 if the given number is unavailable.
9005          */
9006         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9007             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9008             return valueString ? parseInt(valueString, 16) : -1;
9009         }
9010         /**
9011          * Scans as many hexadecimal digits as are available in the text,
9012          * returning "" if the given number of digits was unavailable.
9013          */
9014         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9015             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9016         }
9017         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9018             var valueChars = [];
9019             var allowSeparator = false;
9020             var isPreviousTokenSeparator = false;
9021             while (valueChars.length < minCount || scanAsManyAsPossible) {
9022                 var ch = text.charCodeAt(pos);
9023                 if (canHaveSeparators && ch === 95 /* _ */) {
9024                     tokenFlags |= 512 /* ContainsSeparator */;
9025                     if (allowSeparator) {
9026                         allowSeparator = false;
9027                         isPreviousTokenSeparator = true;
9028                     }
9029                     else if (isPreviousTokenSeparator) {
9030                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9031                     }
9032                     else {
9033                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9034                     }
9035                     pos++;
9036                     continue;
9037                 }
9038                 allowSeparator = canHaveSeparators;
9039                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9040                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9041                 }
9042                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9043                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9044                     break;
9045                 }
9046                 valueChars.push(ch);
9047                 pos++;
9048                 isPreviousTokenSeparator = false;
9049             }
9050             if (valueChars.length < minCount) {
9051                 valueChars = [];
9052             }
9053             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9054                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9055             }
9056             return String.fromCharCode.apply(String, valueChars);
9057         }
9058         function scanString(jsxAttributeString) {
9059             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9060             var quote = text.charCodeAt(pos);
9061             pos++;
9062             var result = "";
9063             var start = pos;
9064             while (true) {
9065                 if (pos >= end) {
9066                     result += text.substring(start, pos);
9067                     tokenFlags |= 4 /* Unterminated */;
9068                     error(ts.Diagnostics.Unterminated_string_literal);
9069                     break;
9070                 }
9071                 var ch = text.charCodeAt(pos);
9072                 if (ch === quote) {
9073                     result += text.substring(start, pos);
9074                     pos++;
9075                     break;
9076                 }
9077                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
9078                     result += text.substring(start, pos);
9079                     result += scanEscapeSequence();
9080                     start = pos;
9081                     continue;
9082                 }
9083                 if (isLineBreak(ch) && !jsxAttributeString) {
9084                     result += text.substring(start, pos);
9085                     tokenFlags |= 4 /* Unterminated */;
9086                     error(ts.Diagnostics.Unterminated_string_literal);
9087                     break;
9088                 }
9089                 pos++;
9090             }
9091             return result;
9092         }
9093         /**
9094          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
9095          * a literal component of a TemplateExpression.
9096          */
9097         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
9098             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
9099             pos++;
9100             var start = pos;
9101             var contents = "";
9102             var resultingToken;
9103             while (true) {
9104                 if (pos >= end) {
9105                     contents += text.substring(start, pos);
9106                     tokenFlags |= 4 /* Unterminated */;
9107                     error(ts.Diagnostics.Unterminated_template_literal);
9108                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9109                     break;
9110                 }
9111                 var currChar = text.charCodeAt(pos);
9112                 // '`'
9113                 if (currChar === 96 /* backtick */) {
9114                     contents += text.substring(start, pos);
9115                     pos++;
9116                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
9117                     break;
9118                 }
9119                 // '${'
9120                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
9121                     contents += text.substring(start, pos);
9122                     pos += 2;
9123                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
9124                     break;
9125                 }
9126                 // Escape character
9127                 if (currChar === 92 /* backslash */) {
9128                     contents += text.substring(start, pos);
9129                     contents += scanEscapeSequence(isTaggedTemplate);
9130                     start = pos;
9131                     continue;
9132                 }
9133                 // Speculated ECMAScript 6 Spec 11.8.6.1:
9134                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
9135                 if (currChar === 13 /* carriageReturn */) {
9136                     contents += text.substring(start, pos);
9137                     pos++;
9138                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9139                         pos++;
9140                     }
9141                     contents += "\n";
9142                     start = pos;
9143                     continue;
9144                 }
9145                 pos++;
9146             }
9147             ts.Debug.assert(resultingToken !== undefined);
9148             tokenValue = contents;
9149             return resultingToken;
9150         }
9151         function scanEscapeSequence(isTaggedTemplate) {
9152             var start = pos;
9153             pos++;
9154             if (pos >= end) {
9155                 error(ts.Diagnostics.Unexpected_end_of_text);
9156                 return "";
9157             }
9158             var ch = text.charCodeAt(pos);
9159             pos++;
9160             switch (ch) {
9161                 case 48 /* _0 */:
9162                     // '\01'
9163                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
9164                         pos++;
9165                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
9166                         return text.substring(start, pos);
9167                     }
9168                     return "\0";
9169                 case 98 /* b */:
9170                     return "\b";
9171                 case 116 /* t */:
9172                     return "\t";
9173                 case 110 /* n */:
9174                     return "\n";
9175                 case 118 /* v */:
9176                     return "\v";
9177                 case 102 /* f */:
9178                     return "\f";
9179                 case 114 /* r */:
9180                     return "\r";
9181                 case 39 /* singleQuote */:
9182                     return "\'";
9183                 case 34 /* doubleQuote */:
9184                     return "\"";
9185                 case 117 /* u */:
9186                     if (isTaggedTemplate) {
9187                         // '\u' or '\u0' or '\u00' or '\u000'
9188                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
9189                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
9190                                 pos = escapePos;
9191                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9192                                 return text.substring(start, pos);
9193                             }
9194                         }
9195                     }
9196                     // '\u{DDDDDDDD}'
9197                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
9198                         pos++;
9199                         // '\u{'
9200                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
9201                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9202                             return text.substring(start, pos);
9203                         }
9204                         if (isTaggedTemplate) {
9205                             var savePos = pos;
9206                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9207                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9208                             // '\u{Not Code Point' or '\u{CodePoint'
9209                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
9210                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
9211                                 return text.substring(start, pos);
9212                             }
9213                             else {
9214                                 pos = savePos;
9215                             }
9216                         }
9217                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9218                         return scanExtendedUnicodeEscape();
9219                     }
9220                     tokenFlags |= 1024 /* UnicodeEscape */;
9221                     // '\uDDDD'
9222                     return scanHexadecimalEscape(/*numDigits*/ 4);
9223                 case 120 /* x */:
9224                     if (isTaggedTemplate) {
9225                         if (!isHexDigit(text.charCodeAt(pos))) {
9226                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9227                             return text.substring(start, pos);
9228                         }
9229                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
9230                             pos++;
9231                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
9232                             return text.substring(start, pos);
9233                         }
9234                     }
9235                     // '\xDD'
9236                     return scanHexadecimalEscape(/*numDigits*/ 2);
9237                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
9238                 // the line terminator is interpreted to be "the empty code unit sequence".
9239                 case 13 /* carriageReturn */:
9240                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
9241                         pos++;
9242                     }
9243                 // falls through
9244                 case 10 /* lineFeed */:
9245                 case 8232 /* lineSeparator */:
9246                 case 8233 /* paragraphSeparator */:
9247                     return "";
9248                 default:
9249                     return String.fromCharCode(ch);
9250             }
9251         }
9252         function scanHexadecimalEscape(numDigits) {
9253             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
9254             if (escapedValue >= 0) {
9255                 return String.fromCharCode(escapedValue);
9256             }
9257             else {
9258                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9259                 return "";
9260             }
9261         }
9262         function scanExtendedUnicodeEscape() {
9263             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9264             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9265             var isInvalidExtendedEscape = false;
9266             // Validate the value of the digit
9267             if (escapedValue < 0) {
9268                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9269                 isInvalidExtendedEscape = true;
9270             }
9271             else if (escapedValue > 0x10FFFF) {
9272                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
9273                 isInvalidExtendedEscape = true;
9274             }
9275             if (pos >= end) {
9276                 error(ts.Diagnostics.Unexpected_end_of_text);
9277                 isInvalidExtendedEscape = true;
9278             }
9279             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
9280                 // Only swallow the following character up if it's a '}'.
9281                 pos++;
9282             }
9283             else {
9284                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
9285                 isInvalidExtendedEscape = true;
9286             }
9287             if (isInvalidExtendedEscape) {
9288                 return "";
9289             }
9290             return utf16EncodeAsString(escapedValue);
9291         }
9292         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
9293         // and return code point value if valid Unicode escape is found. Otherwise return -1.
9294         function peekUnicodeEscape() {
9295             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
9296                 var start_1 = pos;
9297                 pos += 2;
9298                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
9299                 pos = start_1;
9300                 return value;
9301             }
9302             return -1;
9303         }
9304         function peekExtendedUnicodeEscape() {
9305             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
9306                 var start_2 = pos;
9307                 pos += 3;
9308                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
9309                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
9310                 pos = start_2;
9311                 return escapedValue;
9312             }
9313             return -1;
9314         }
9315         function scanIdentifierParts() {
9316             var result = "";
9317             var start = pos;
9318             while (pos < end) {
9319                 var ch = codePointAt(text, pos);
9320                 if (isIdentifierPart(ch, languageVersion)) {
9321                     pos += charSize(ch);
9322                 }
9323                 else if (ch === 92 /* backslash */) {
9324                     ch = peekExtendedUnicodeEscape();
9325                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
9326                         pos += 3;
9327                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9328                         result += scanExtendedUnicodeEscape();
9329                         start = pos;
9330                         continue;
9331                     }
9332                     ch = peekUnicodeEscape();
9333                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
9334                         break;
9335                     }
9336                     tokenFlags |= 1024 /* UnicodeEscape */;
9337                     result += text.substring(start, pos);
9338                     result += utf16EncodeAsString(ch);
9339                     // Valid Unicode escape is always six characters
9340                     pos += 6;
9341                     start = pos;
9342                 }
9343                 else {
9344                     break;
9345                 }
9346             }
9347             result += text.substring(start, pos);
9348             return result;
9349         }
9350         function getIdentifierToken() {
9351             // Reserved words are between 2 and 11 characters long and start with a lowercase letter
9352             var len = tokenValue.length;
9353             if (len >= 2 && len <= 11) {
9354                 var ch = tokenValue.charCodeAt(0);
9355                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
9356                     var keyword = textToKeyword.get(tokenValue);
9357                     if (keyword !== undefined) {
9358                         return token = keyword;
9359                     }
9360                 }
9361             }
9362             return token = 75 /* Identifier */;
9363         }
9364         function scanBinaryOrOctalDigits(base) {
9365             var value = "";
9366             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
9367             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
9368             var separatorAllowed = false;
9369             var isPreviousTokenSeparator = false;
9370             while (true) {
9371                 var ch = text.charCodeAt(pos);
9372                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
9373                 if (ch === 95 /* _ */) {
9374                     tokenFlags |= 512 /* ContainsSeparator */;
9375                     if (separatorAllowed) {
9376                         separatorAllowed = false;
9377                         isPreviousTokenSeparator = true;
9378                     }
9379                     else if (isPreviousTokenSeparator) {
9380                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9381                     }
9382                     else {
9383                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9384                     }
9385                     pos++;
9386                     continue;
9387                 }
9388                 separatorAllowed = true;
9389                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
9390                     break;
9391                 }
9392                 value += text[pos];
9393                 pos++;
9394                 isPreviousTokenSeparator = false;
9395             }
9396             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9397                 // Literal ends with underscore - not allowed
9398                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9399             }
9400             return value;
9401         }
9402         function checkBigIntSuffix() {
9403             if (text.charCodeAt(pos) === 110 /* n */) {
9404                 tokenValue += "n";
9405                 // Use base 10 instead of base 2 or base 8 for shorter literals
9406                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
9407                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
9408                 }
9409                 pos++;
9410                 return 9 /* BigIntLiteral */;
9411             }
9412             else { // not a bigint, so can convert to number in simplified form
9413                 // Number() may not support 0b or 0o, so use parseInt() instead
9414                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
9415                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
9416                     : tokenFlags & 256 /* OctalSpecifier */
9417                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
9418                         : +tokenValue;
9419                 tokenValue = "" + numericValue;
9420                 return 8 /* NumericLiteral */;
9421             }
9422         }
9423         function scan() {
9424             var _a;
9425             startPos = pos;
9426             tokenFlags = 0 /* None */;
9427             var asteriskSeen = false;
9428             while (true) {
9429                 tokenPos = pos;
9430                 if (pos >= end) {
9431                     return token = 1 /* EndOfFileToken */;
9432                 }
9433                 var ch = codePointAt(text, pos);
9434                 // Special handling for shebang
9435                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
9436                     pos = scanShebangTrivia(text, pos);
9437                     if (skipTrivia) {
9438                         continue;
9439                     }
9440                     else {
9441                         return token = 6 /* ShebangTrivia */;
9442                     }
9443                 }
9444                 switch (ch) {
9445                     case 10 /* lineFeed */:
9446                     case 13 /* carriageReturn */:
9447                         tokenFlags |= 1 /* PrecedingLineBreak */;
9448                         if (skipTrivia) {
9449                             pos++;
9450                             continue;
9451                         }
9452                         else {
9453                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9454                                 // consume both CR and LF
9455                                 pos += 2;
9456                             }
9457                             else {
9458                                 pos++;
9459                             }
9460                             return token = 4 /* NewLineTrivia */;
9461                         }
9462                     case 9 /* tab */:
9463                     case 11 /* verticalTab */:
9464                     case 12 /* formFeed */:
9465                     case 32 /* space */:
9466                     case 160 /* nonBreakingSpace */:
9467                     case 5760 /* ogham */:
9468                     case 8192 /* enQuad */:
9469                     case 8193 /* emQuad */:
9470                     case 8194 /* enSpace */:
9471                     case 8195 /* emSpace */:
9472                     case 8196 /* threePerEmSpace */:
9473                     case 8197 /* fourPerEmSpace */:
9474                     case 8198 /* sixPerEmSpace */:
9475                     case 8199 /* figureSpace */:
9476                     case 8200 /* punctuationSpace */:
9477                     case 8201 /* thinSpace */:
9478                     case 8202 /* hairSpace */:
9479                     case 8203 /* zeroWidthSpace */:
9480                     case 8239 /* narrowNoBreakSpace */:
9481                     case 8287 /* mathematicalSpace */:
9482                     case 12288 /* ideographicSpace */:
9483                     case 65279 /* byteOrderMark */:
9484                         if (skipTrivia) {
9485                             pos++;
9486                             continue;
9487                         }
9488                         else {
9489                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
9490                                 pos++;
9491                             }
9492                             return token = 5 /* WhitespaceTrivia */;
9493                         }
9494                     case 33 /* exclamation */:
9495                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9496                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9497                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
9498                             }
9499                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
9500                         }
9501                         pos++;
9502                         return token = 53 /* ExclamationToken */;
9503                     case 34 /* doubleQuote */:
9504                     case 39 /* singleQuote */:
9505                         tokenValue = scanString();
9506                         return token = 10 /* StringLiteral */;
9507                     case 96 /* backtick */:
9508                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
9509                     case 37 /* percent */:
9510                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9511                             return pos += 2, token = 68 /* PercentEqualsToken */;
9512                         }
9513                         pos++;
9514                         return token = 44 /* PercentToken */;
9515                     case 38 /* ampersand */:
9516                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
9517                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
9518                         }
9519                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9520                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
9521                         }
9522                         pos++;
9523                         return token = 50 /* AmpersandToken */;
9524                     case 40 /* openParen */:
9525                         pos++;
9526                         return token = 20 /* OpenParenToken */;
9527                     case 41 /* closeParen */:
9528                         pos++;
9529                         return token = 21 /* CloseParenToken */;
9530                     case 42 /* asterisk */:
9531                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9532                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
9533                         }
9534                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9535                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9536                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
9537                             }
9538                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
9539                         }
9540                         pos++;
9541                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
9542                             // decoration at the start of a JSDoc comment line
9543                             asteriskSeen = true;
9544                             continue;
9545                         }
9546                         return token = 41 /* AsteriskToken */;
9547                     case 43 /* plus */:
9548                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
9549                             return pos += 2, token = 45 /* PlusPlusToken */;
9550                         }
9551                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9552                             return pos += 2, token = 63 /* PlusEqualsToken */;
9553                         }
9554                         pos++;
9555                         return token = 39 /* PlusToken */;
9556                     case 44 /* comma */:
9557                         pos++;
9558                         return token = 27 /* CommaToken */;
9559                     case 45 /* minus */:
9560                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
9561                             return pos += 2, token = 46 /* MinusMinusToken */;
9562                         }
9563                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9564                             return pos += 2, token = 64 /* MinusEqualsToken */;
9565                         }
9566                         pos++;
9567                         return token = 40 /* MinusToken */;
9568                     case 46 /* dot */:
9569                         if (isDigit(text.charCodeAt(pos + 1))) {
9570                             tokenValue = scanNumber().value;
9571                             return token = 8 /* NumericLiteral */;
9572                         }
9573                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
9574                             return pos += 3, token = 25 /* DotDotDotToken */;
9575                         }
9576                         pos++;
9577                         return token = 24 /* DotToken */;
9578                     case 47 /* slash */:
9579                         // Single-line comment
9580                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9581                             pos += 2;
9582                             while (pos < end) {
9583                                 if (isLineBreak(text.charCodeAt(pos))) {
9584                                     break;
9585                                 }
9586                                 pos++;
9587                             }
9588                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
9589                             if (skipTrivia) {
9590                                 continue;
9591                             }
9592                             else {
9593                                 return token = 2 /* SingleLineCommentTrivia */;
9594                             }
9595                         }
9596                         // Multi-line comment
9597                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9598                             pos += 2;
9599                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
9600                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
9601                             }
9602                             var commentClosed = false;
9603                             var lastLineStart = tokenPos;
9604                             while (pos < end) {
9605                                 var ch_1 = text.charCodeAt(pos);
9606                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9607                                     pos += 2;
9608                                     commentClosed = true;
9609                                     break;
9610                                 }
9611                                 pos++;
9612                                 if (isLineBreak(ch_1)) {
9613                                     lastLineStart = pos;
9614                                     tokenFlags |= 1 /* PrecedingLineBreak */;
9615                                 }
9616                             }
9617                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
9618                             if (!commentClosed) {
9619                                 error(ts.Diagnostics.Asterisk_Slash_expected);
9620                             }
9621                             if (skipTrivia) {
9622                                 continue;
9623                             }
9624                             else {
9625                                 if (!commentClosed) {
9626                                     tokenFlags |= 4 /* Unterminated */;
9627                                 }
9628                                 return token = 3 /* MultiLineCommentTrivia */;
9629                             }
9630                         }
9631                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9632                             return pos += 2, token = 67 /* SlashEqualsToken */;
9633                         }
9634                         pos++;
9635                         return token = 43 /* SlashToken */;
9636                     case 48 /* _0 */:
9637                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
9638                             pos += 2;
9639                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
9640                             if (!tokenValue) {
9641                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
9642                                 tokenValue = "0";
9643                             }
9644                             tokenValue = "0x" + tokenValue;
9645                             tokenFlags |= 64 /* HexSpecifier */;
9646                             return token = checkBigIntSuffix();
9647                         }
9648                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
9649                             pos += 2;
9650                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
9651                             if (!tokenValue) {
9652                                 error(ts.Diagnostics.Binary_digit_expected);
9653                                 tokenValue = "0";
9654                             }
9655                             tokenValue = "0b" + tokenValue;
9656                             tokenFlags |= 128 /* BinarySpecifier */;
9657                             return token = checkBigIntSuffix();
9658                         }
9659                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
9660                             pos += 2;
9661                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
9662                             if (!tokenValue) {
9663                                 error(ts.Diagnostics.Octal_digit_expected);
9664                                 tokenValue = "0";
9665                             }
9666                             tokenValue = "0o" + tokenValue;
9667                             tokenFlags |= 256 /* OctalSpecifier */;
9668                             return token = checkBigIntSuffix();
9669                         }
9670                         // Try to parse as an octal
9671                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
9672                             tokenValue = "" + scanOctalDigits();
9673                             tokenFlags |= 32 /* Octal */;
9674                             return token = 8 /* NumericLiteral */;
9675                         }
9676                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
9677                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
9678                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
9679                     // falls through
9680                     case 49 /* _1 */:
9681                     case 50 /* _2 */:
9682                     case 51 /* _3 */:
9683                     case 52 /* _4 */:
9684                     case 53 /* _5 */:
9685                     case 54 /* _6 */:
9686                     case 55 /* _7 */:
9687                     case 56 /* _8 */:
9688                     case 57 /* _9 */:
9689                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
9690                         return token;
9691                     case 58 /* colon */:
9692                         pos++;
9693                         return token = 58 /* ColonToken */;
9694                     case 59 /* semicolon */:
9695                         pos++;
9696                         return token = 26 /* SemicolonToken */;
9697                     case 60 /* lessThan */:
9698                         if (isConflictMarkerTrivia(text, pos)) {
9699                             pos = scanConflictMarkerTrivia(text, pos, error);
9700                             if (skipTrivia) {
9701                                 continue;
9702                             }
9703                             else {
9704                                 return token = 7 /* ConflictMarkerTrivia */;
9705                             }
9706                         }
9707                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
9708                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9709                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
9710                             }
9711                             return pos += 2, token = 47 /* LessThanLessThanToken */;
9712                         }
9713                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9714                             return pos += 2, token = 32 /* LessThanEqualsToken */;
9715                         }
9716                         if (languageVariant === 1 /* JSX */ &&
9717                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
9718                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
9719                             return pos += 2, token = 30 /* LessThanSlashToken */;
9720                         }
9721                         pos++;
9722                         return token = 29 /* LessThanToken */;
9723                     case 61 /* equals */:
9724                         if (isConflictMarkerTrivia(text, pos)) {
9725                             pos = scanConflictMarkerTrivia(text, pos, error);
9726                             if (skipTrivia) {
9727                                 continue;
9728                             }
9729                             else {
9730                                 return token = 7 /* ConflictMarkerTrivia */;
9731                             }
9732                         }
9733                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9734                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9735                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
9736                             }
9737                             return pos += 2, token = 34 /* EqualsEqualsToken */;
9738                         }
9739                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9740                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
9741                         }
9742                         pos++;
9743                         return token = 62 /* EqualsToken */;
9744                     case 62 /* greaterThan */:
9745                         if (isConflictMarkerTrivia(text, pos)) {
9746                             pos = scanConflictMarkerTrivia(text, pos, error);
9747                             if (skipTrivia) {
9748                                 continue;
9749                             }
9750                             else {
9751                                 return token = 7 /* ConflictMarkerTrivia */;
9752                             }
9753                         }
9754                         pos++;
9755                         return token = 31 /* GreaterThanToken */;
9756                     case 63 /* question */:
9757                         pos++;
9758                         if (text.charCodeAt(pos) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 1))) {
9759                             pos++;
9760                             return token = 28 /* QuestionDotToken */;
9761                         }
9762                         if (text.charCodeAt(pos) === 63 /* question */) {
9763                             pos++;
9764                             return token = 60 /* QuestionQuestionToken */;
9765                         }
9766                         return token = 57 /* QuestionToken */;
9767                     case 91 /* openBracket */:
9768                         pos++;
9769                         return token = 22 /* OpenBracketToken */;
9770                     case 93 /* closeBracket */:
9771                         pos++;
9772                         return token = 23 /* CloseBracketToken */;
9773                     case 94 /* caret */:
9774                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9775                             return pos += 2, token = 74 /* CaretEqualsToken */;
9776                         }
9777                         pos++;
9778                         return token = 52 /* CaretToken */;
9779                     case 123 /* openBrace */:
9780                         pos++;
9781                         return token = 18 /* OpenBraceToken */;
9782                     case 124 /* bar */:
9783                         if (isConflictMarkerTrivia(text, pos)) {
9784                             pos = scanConflictMarkerTrivia(text, pos, error);
9785                             if (skipTrivia) {
9786                                 continue;
9787                             }
9788                             else {
9789                                 return token = 7 /* ConflictMarkerTrivia */;
9790                             }
9791                         }
9792                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
9793                             return pos += 2, token = 56 /* BarBarToken */;
9794                         }
9795                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9796                             return pos += 2, token = 73 /* BarEqualsToken */;
9797                         }
9798                         pos++;
9799                         return token = 51 /* BarToken */;
9800                     case 125 /* closeBrace */:
9801                         pos++;
9802                         return token = 19 /* CloseBraceToken */;
9803                     case 126 /* tilde */:
9804                         pos++;
9805                         return token = 54 /* TildeToken */;
9806                     case 64 /* at */:
9807                         pos++;
9808                         return token = 59 /* AtToken */;
9809                     case 92 /* backslash */:
9810                         var extendedCookedChar = peekExtendedUnicodeEscape();
9811                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
9812                             pos += 3;
9813                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
9814                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
9815                             return token = getIdentifierToken();
9816                         }
9817                         var cookedChar = peekUnicodeEscape();
9818                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
9819                             pos += 6;
9820                             tokenFlags |= 1024 /* UnicodeEscape */;
9821                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
9822                             return token = getIdentifierToken();
9823                         }
9824                         error(ts.Diagnostics.Invalid_character);
9825                         pos++;
9826                         return token = 0 /* Unknown */;
9827                     case 35 /* hash */:
9828                         if (pos !== 0 && text[pos + 1] === "!") {
9829                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
9830                             pos++;
9831                             return token = 0 /* Unknown */;
9832                         }
9833                         pos++;
9834                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
9835                             pos++;
9836                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
9837                                 pos++;
9838                             tokenValue = text.substring(tokenPos, pos);
9839                             if (ch === 92 /* backslash */) {
9840                                 tokenValue += scanIdentifierParts();
9841                             }
9842                         }
9843                         else {
9844                             tokenValue = "#";
9845                             error(ts.Diagnostics.Invalid_character);
9846                         }
9847                         return token = 76 /* PrivateIdentifier */;
9848                     default:
9849                         if (isIdentifierStart(ch, languageVersion)) {
9850                             pos += charSize(ch);
9851                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
9852                                 pos += charSize(ch);
9853                             tokenValue = text.substring(tokenPos, pos);
9854                             if (ch === 92 /* backslash */) {
9855                                 tokenValue += scanIdentifierParts();
9856                             }
9857                             return token = getIdentifierToken();
9858                         }
9859                         else if (isWhiteSpaceSingleLine(ch)) {
9860                             pos += charSize(ch);
9861                             continue;
9862                         }
9863                         else if (isLineBreak(ch)) {
9864                             tokenFlags |= 1 /* PrecedingLineBreak */;
9865                             pos += charSize(ch);
9866                             continue;
9867                         }
9868                         error(ts.Diagnostics.Invalid_character);
9869                         pos += charSize(ch);
9870                         return token = 0 /* Unknown */;
9871                 }
9872             }
9873         }
9874         function reScanGreaterToken() {
9875             if (token === 31 /* GreaterThanToken */) {
9876                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
9877                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
9878                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
9879                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
9880                         }
9881                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
9882                     }
9883                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
9884                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
9885                     }
9886                     pos++;
9887                     return token = 48 /* GreaterThanGreaterThanToken */;
9888                 }
9889                 if (text.charCodeAt(pos) === 61 /* equals */) {
9890                     pos++;
9891                     return token = 33 /* GreaterThanEqualsToken */;
9892                 }
9893             }
9894             return token;
9895         }
9896         function reScanSlashToken() {
9897             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
9898                 var p = tokenPos + 1;
9899                 var inEscape = false;
9900                 var inCharacterClass = false;
9901                 while (true) {
9902                     // If we reach the end of a file, or hit a newline, then this is an unterminated
9903                     // regex.  Report error and return what we have so far.
9904                     if (p >= end) {
9905                         tokenFlags |= 4 /* Unterminated */;
9906                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9907                         break;
9908                     }
9909                     var ch = text.charCodeAt(p);
9910                     if (isLineBreak(ch)) {
9911                         tokenFlags |= 4 /* Unterminated */;
9912                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
9913                         break;
9914                     }
9915                     if (inEscape) {
9916                         // Parsing an escape character;
9917                         // reset the flag and just advance to the next char.
9918                         inEscape = false;
9919                     }
9920                     else if (ch === 47 /* slash */ && !inCharacterClass) {
9921                         // A slash within a character class is permissible,
9922                         // but in general it signals the end of the regexp literal.
9923                         p++;
9924                         break;
9925                     }
9926                     else if (ch === 91 /* openBracket */) {
9927                         inCharacterClass = true;
9928                     }
9929                     else if (ch === 92 /* backslash */) {
9930                         inEscape = true;
9931                     }
9932                     else if (ch === 93 /* closeBracket */) {
9933                         inCharacterClass = false;
9934                     }
9935                     p++;
9936                 }
9937                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
9938                     p++;
9939                 }
9940                 pos = p;
9941                 tokenValue = text.substring(tokenPos, pos);
9942                 token = 13 /* RegularExpressionLiteral */;
9943             }
9944             return token;
9945         }
9946         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
9947             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
9948             if (type === undefined) {
9949                 return commentDirectives;
9950             }
9951             return ts.append(commentDirectives, {
9952                 range: { pos: lineStart, end: pos },
9953                 type: type,
9954             });
9955         }
9956         function getDirectiveFromComment(text, commentDirectiveRegEx) {
9957             var match = commentDirectiveRegEx.exec(text);
9958             if (!match) {
9959                 return undefined;
9960             }
9961             switch (match[1]) {
9962                 case "ts-expect-error":
9963                     return 0 /* ExpectError */;
9964                 case "ts-ignore":
9965                     return 1 /* Ignore */;
9966             }
9967             return undefined;
9968         }
9969         /**
9970          * Unconditionally back up and scan a template expression portion.
9971          */
9972         function reScanTemplateToken(isTaggedTemplate) {
9973             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
9974             pos = tokenPos;
9975             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
9976         }
9977         function reScanTemplateHeadOrNoSubstitutionTemplate() {
9978             pos = tokenPos;
9979             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
9980         }
9981         function reScanJsxToken() {
9982             pos = tokenPos = startPos;
9983             return token = scanJsxToken();
9984         }
9985         function reScanLessThanToken() {
9986             if (token === 47 /* LessThanLessThanToken */) {
9987                 pos = tokenPos + 1;
9988                 return token = 29 /* LessThanToken */;
9989             }
9990             return token;
9991         }
9992         function reScanQuestionToken() {
9993             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
9994             pos = tokenPos + 1;
9995             return token = 57 /* QuestionToken */;
9996         }
9997         function scanJsxToken() {
9998             startPos = tokenPos = pos;
9999             if (pos >= end) {
10000                 return token = 1 /* EndOfFileToken */;
10001             }
10002             var char = text.charCodeAt(pos);
10003             if (char === 60 /* lessThan */) {
10004                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10005                     pos += 2;
10006                     return token = 30 /* LessThanSlashToken */;
10007                 }
10008                 pos++;
10009                 return token = 29 /* LessThanToken */;
10010             }
10011             if (char === 123 /* openBrace */) {
10012                 pos++;
10013                 return token = 18 /* OpenBraceToken */;
10014             }
10015             // First non-whitespace character on this line.
10016             var firstNonWhitespace = 0;
10017             var lastNonWhitespace = -1;
10018             // These initial values are special because the first line is:
10019             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10020             while (pos < end) {
10021                 // We want to keep track of the last non-whitespace (but including
10022                 // newlines character for hitting the end of the JSX Text region)
10023                 if (!isWhiteSpaceSingleLine(char)) {
10024                     lastNonWhitespace = pos;
10025                 }
10026                 char = text.charCodeAt(pos);
10027                 if (char === 123 /* openBrace */) {
10028                     break;
10029                 }
10030                 if (char === 60 /* lessThan */) {
10031                     if (isConflictMarkerTrivia(text, pos)) {
10032                         pos = scanConflictMarkerTrivia(text, pos, error);
10033                         return token = 7 /* ConflictMarkerTrivia */;
10034                     }
10035                     break;
10036                 }
10037                 if (char === 62 /* greaterThan */) {
10038                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10039                 }
10040                 if (char === 125 /* closeBrace */) {
10041                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10042                 }
10043                 if (lastNonWhitespace > 0)
10044                     lastNonWhitespace++;
10045                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10046                 // i.e (- : whitespace)
10047                 //      <div>----
10048                 //      </div> becomes <div></div>
10049                 //
10050                 //      <div>----</div> becomes <div>----</div>
10051                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10052                     firstNonWhitespace = -1;
10053                 }
10054                 else if (!isWhiteSpaceLike(char)) {
10055                     firstNonWhitespace = pos;
10056                 }
10057                 pos++;
10058             }
10059             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10060             tokenValue = text.substring(startPos, endPosition);
10061             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10062         }
10063         // Scans a JSX identifier; these differ from normal identifiers in that
10064         // they allow dashes
10065         function scanJsxIdentifier() {
10066             if (tokenIsIdentifierOrKeyword(token)) {
10067                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
10068                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
10069                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
10070                 while (pos < end) {
10071                     var ch = text.charCodeAt(pos);
10072                     if (ch === 45 /* minus */) {
10073                         tokenValue += "-";
10074                         pos++;
10075                         continue;
10076                     }
10077                     var oldPos = pos;
10078                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
10079                     if (pos === oldPos) {
10080                         break;
10081                     }
10082                 }
10083             }
10084             return token;
10085         }
10086         function scanJsxAttributeValue() {
10087             startPos = pos;
10088             switch (text.charCodeAt(pos)) {
10089                 case 34 /* doubleQuote */:
10090                 case 39 /* singleQuote */:
10091                     tokenValue = scanString(/*jsxAttributeString*/ true);
10092                     return token = 10 /* StringLiteral */;
10093                 default:
10094                     // If this scans anything other than `{`, it's a parse error.
10095                     return scan();
10096             }
10097         }
10098         function reScanJsxAttributeValue() {
10099             pos = tokenPos = startPos;
10100             return scanJsxAttributeValue();
10101         }
10102         function scanJsDocToken() {
10103             startPos = tokenPos = pos;
10104             tokenFlags = 0 /* None */;
10105             if (pos >= end) {
10106                 return token = 1 /* EndOfFileToken */;
10107             }
10108             var ch = codePointAt(text, pos);
10109             pos += charSize(ch);
10110             switch (ch) {
10111                 case 9 /* tab */:
10112                 case 11 /* verticalTab */:
10113                 case 12 /* formFeed */:
10114                 case 32 /* space */:
10115                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10116                         pos++;
10117                     }
10118                     return token = 5 /* WhitespaceTrivia */;
10119                 case 64 /* at */:
10120                     return token = 59 /* AtToken */;
10121                 case 10 /* lineFeed */:
10122                 case 13 /* carriageReturn */:
10123                     tokenFlags |= 1 /* PrecedingLineBreak */;
10124                     return token = 4 /* NewLineTrivia */;
10125                 case 42 /* asterisk */:
10126                     return token = 41 /* AsteriskToken */;
10127                 case 123 /* openBrace */:
10128                     return token = 18 /* OpenBraceToken */;
10129                 case 125 /* closeBrace */:
10130                     return token = 19 /* CloseBraceToken */;
10131                 case 91 /* openBracket */:
10132                     return token = 22 /* OpenBracketToken */;
10133                 case 93 /* closeBracket */:
10134                     return token = 23 /* CloseBracketToken */;
10135                 case 60 /* lessThan */:
10136                     return token = 29 /* LessThanToken */;
10137                 case 62 /* greaterThan */:
10138                     return token = 31 /* GreaterThanToken */;
10139                 case 61 /* equals */:
10140                     return token = 62 /* EqualsToken */;
10141                 case 44 /* comma */:
10142                     return token = 27 /* CommaToken */;
10143                 case 46 /* dot */:
10144                     return token = 24 /* DotToken */;
10145                 case 96 /* backtick */:
10146                     return token = 61 /* BacktickToken */;
10147                 case 92 /* backslash */:
10148                     pos--;
10149                     var extendedCookedChar = peekExtendedUnicodeEscape();
10150                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10151                         pos += 3;
10152                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10153                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10154                         return token = getIdentifierToken();
10155                     }
10156                     var cookedChar = peekUnicodeEscape();
10157                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10158                         pos += 6;
10159                         tokenFlags |= 1024 /* UnicodeEscape */;
10160                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10161                         return token = getIdentifierToken();
10162                     }
10163                     pos++;
10164                     return token = 0 /* Unknown */;
10165             }
10166             if (isIdentifierStart(ch, languageVersion)) {
10167                 var char = ch;
10168                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
10169                     pos += charSize(char);
10170                 tokenValue = text.substring(tokenPos, pos);
10171                 if (char === 92 /* backslash */) {
10172                     tokenValue += scanIdentifierParts();
10173                 }
10174                 return token = getIdentifierToken();
10175             }
10176             else {
10177                 return token = 0 /* Unknown */;
10178             }
10179         }
10180         function speculationHelper(callback, isLookahead) {
10181             var savePos = pos;
10182             var saveStartPos = startPos;
10183             var saveTokenPos = tokenPos;
10184             var saveToken = token;
10185             var saveTokenValue = tokenValue;
10186             var saveTokenFlags = tokenFlags;
10187             var result = callback();
10188             // If our callback returned something 'falsy' or we're just looking ahead,
10189             // then unconditionally restore us to where we were.
10190             if (!result || isLookahead) {
10191                 pos = savePos;
10192                 startPos = saveStartPos;
10193                 tokenPos = saveTokenPos;
10194                 token = saveToken;
10195                 tokenValue = saveTokenValue;
10196                 tokenFlags = saveTokenFlags;
10197             }
10198             return result;
10199         }
10200         function scanRange(start, length, callback) {
10201             var saveEnd = end;
10202             var savePos = pos;
10203             var saveStartPos = startPos;
10204             var saveTokenPos = tokenPos;
10205             var saveToken = token;
10206             var saveTokenValue = tokenValue;
10207             var saveTokenFlags = tokenFlags;
10208             var saveErrorExpectations = commentDirectives;
10209             setText(text, start, length);
10210             var result = callback();
10211             end = saveEnd;
10212             pos = savePos;
10213             startPos = saveStartPos;
10214             tokenPos = saveTokenPos;
10215             token = saveToken;
10216             tokenValue = saveTokenValue;
10217             tokenFlags = saveTokenFlags;
10218             commentDirectives = saveErrorExpectations;
10219             return result;
10220         }
10221         function lookAhead(callback) {
10222             return speculationHelper(callback, /*isLookahead*/ true);
10223         }
10224         function tryScan(callback) {
10225             return speculationHelper(callback, /*isLookahead*/ false);
10226         }
10227         function getText() {
10228             return text;
10229         }
10230         function clearCommentDirectives() {
10231             commentDirectives = undefined;
10232         }
10233         function setText(newText, start, length) {
10234             text = newText || "";
10235             end = length === undefined ? text.length : start + length;
10236             setTextPos(start || 0);
10237         }
10238         function setOnError(errorCallback) {
10239             onError = errorCallback;
10240         }
10241         function setScriptTarget(scriptTarget) {
10242             languageVersion = scriptTarget;
10243         }
10244         function setLanguageVariant(variant) {
10245             languageVariant = variant;
10246         }
10247         function setTextPos(textPos) {
10248             ts.Debug.assert(textPos >= 0);
10249             pos = textPos;
10250             startPos = textPos;
10251             tokenPos = textPos;
10252             token = 0 /* Unknown */;
10253             tokenValue = undefined;
10254             tokenFlags = 0 /* None */;
10255         }
10256         function setInJSDocType(inType) {
10257             inJSDocType += inType ? 1 : -1;
10258         }
10259     }
10260     ts.createScanner = createScanner;
10261     /* @internal */
10262     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
10263         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
10264         var size = str.length;
10265         // Account for out-of-bounds indices:
10266         if (i < 0 || i >= size) {
10267             return undefined; // String.codePointAt returns `undefined` for OOB indexes
10268         }
10269         // Get the first code unit
10270         var first = str.charCodeAt(i);
10271         // check if it’s the start of a surrogate pair
10272         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
10273             var second = str.charCodeAt(i + 1);
10274             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
10275                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
10276                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
10277             }
10278         }
10279         return first;
10280     };
10281     /* @internal */
10282     function charSize(ch) {
10283         if (ch >= 0x10000) {
10284             return 2;
10285         }
10286         return 1;
10287     }
10288     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
10289     function utf16EncodeAsStringFallback(codePoint) {
10290         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
10291         if (codePoint <= 65535) {
10292             return String.fromCharCode(codePoint);
10293         }
10294         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
10295         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
10296         return String.fromCharCode(codeUnit1, codeUnit2);
10297     }
10298     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
10299     /* @internal */
10300     function utf16EncodeAsString(codePoint) {
10301         return utf16EncodeAsStringWorker(codePoint);
10302     }
10303     ts.utf16EncodeAsString = utf16EncodeAsString;
10304 })(ts || (ts = {}));
10305 var ts;
10306 (function (ts) {
10307     function isExternalModuleNameRelative(moduleName) {
10308         // TypeScript 1.0 spec (April 2014): 11.2.1
10309         // An external module name is "relative" if the first term is "." or "..".
10310         // 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.
10311         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
10312     }
10313     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
10314     function sortAndDeduplicateDiagnostics(diagnostics) {
10315         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
10316     }
10317     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
10318     function getDefaultLibFileName(options) {
10319         switch (options.target) {
10320             case 99 /* ESNext */:
10321                 return "lib.esnext.full.d.ts";
10322             case 7 /* ES2020 */:
10323                 return "lib.es2020.full.d.ts";
10324             case 6 /* ES2019 */:
10325                 return "lib.es2019.full.d.ts";
10326             case 5 /* ES2018 */:
10327                 return "lib.es2018.full.d.ts";
10328             case 4 /* ES2017 */:
10329                 return "lib.es2017.full.d.ts";
10330             case 3 /* ES2016 */:
10331                 return "lib.es2016.full.d.ts";
10332             case 2 /* ES2015 */:
10333                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
10334             default:
10335                 return "lib.d.ts";
10336         }
10337     }
10338     ts.getDefaultLibFileName = getDefaultLibFileName;
10339     function textSpanEnd(span) {
10340         return span.start + span.length;
10341     }
10342     ts.textSpanEnd = textSpanEnd;
10343     function textSpanIsEmpty(span) {
10344         return span.length === 0;
10345     }
10346     ts.textSpanIsEmpty = textSpanIsEmpty;
10347     function textSpanContainsPosition(span, position) {
10348         return position >= span.start && position < textSpanEnd(span);
10349     }
10350     ts.textSpanContainsPosition = textSpanContainsPosition;
10351     /* @internal */
10352     function textRangeContainsPositionInclusive(span, position) {
10353         return position >= span.pos && position <= span.end;
10354     }
10355     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
10356     // Returns true if 'span' contains 'other'.
10357     function textSpanContainsTextSpan(span, other) {
10358         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
10359     }
10360     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
10361     function textSpanOverlapsWith(span, other) {
10362         return textSpanOverlap(span, other) !== undefined;
10363     }
10364     ts.textSpanOverlapsWith = textSpanOverlapsWith;
10365     function textSpanOverlap(span1, span2) {
10366         var overlap = textSpanIntersection(span1, span2);
10367         return overlap && overlap.length === 0 ? undefined : overlap;
10368     }
10369     ts.textSpanOverlap = textSpanOverlap;
10370     function textSpanIntersectsWithTextSpan(span, other) {
10371         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
10372     }
10373     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
10374     function textSpanIntersectsWith(span, start, length) {
10375         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
10376     }
10377     ts.textSpanIntersectsWith = textSpanIntersectsWith;
10378     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
10379         var end1 = start1 + length1;
10380         var end2 = start2 + length2;
10381         return start2 <= end1 && end2 >= start1;
10382     }
10383     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
10384     function textSpanIntersectsWithPosition(span, position) {
10385         return position <= textSpanEnd(span) && position >= span.start;
10386     }
10387     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
10388     function textSpanIntersection(span1, span2) {
10389         var start = Math.max(span1.start, span2.start);
10390         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
10391         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
10392     }
10393     ts.textSpanIntersection = textSpanIntersection;
10394     function createTextSpan(start, length) {
10395         if (start < 0) {
10396             throw new Error("start < 0");
10397         }
10398         if (length < 0) {
10399             throw new Error("length < 0");
10400         }
10401         return { start: start, length: length };
10402     }
10403     ts.createTextSpan = createTextSpan;
10404     function createTextSpanFromBounds(start, end) {
10405         return createTextSpan(start, end - start);
10406     }
10407     ts.createTextSpanFromBounds = createTextSpanFromBounds;
10408     function textChangeRangeNewSpan(range) {
10409         return createTextSpan(range.span.start, range.newLength);
10410     }
10411     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
10412     function textChangeRangeIsUnchanged(range) {
10413         return textSpanIsEmpty(range.span) && range.newLength === 0;
10414     }
10415     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
10416     function createTextChangeRange(span, newLength) {
10417         if (newLength < 0) {
10418             throw new Error("newLength < 0");
10419         }
10420         return { span: span, newLength: newLength };
10421     }
10422     ts.createTextChangeRange = createTextChangeRange;
10423     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
10424     /**
10425      * Called to merge all the changes that occurred across several versions of a script snapshot
10426      * into a single change.  i.e. if a user keeps making successive edits to a script we will
10427      * have a text change from V1 to V2, V2 to V3, ..., Vn.
10428      *
10429      * This function will then merge those changes into a single change range valid between V1 and
10430      * Vn.
10431      */
10432     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
10433         if (changes.length === 0) {
10434             return ts.unchangedTextChangeRange;
10435         }
10436         if (changes.length === 1) {
10437             return changes[0];
10438         }
10439         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
10440         // as it makes things much easier to reason about.
10441         var change0 = changes[0];
10442         var oldStartN = change0.span.start;
10443         var oldEndN = textSpanEnd(change0.span);
10444         var newEndN = oldStartN + change0.newLength;
10445         for (var i = 1; i < changes.length; i++) {
10446             var nextChange = changes[i];
10447             // Consider the following case:
10448             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
10449             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
10450             // i.e. the span starting at 30 with length 30 is increased to length 40.
10451             //
10452             //      0         10        20        30        40        50        60        70        80        90        100
10453             //      -------------------------------------------------------------------------------------------------------
10454             //                |                                                 /
10455             //                |                                            /----
10456             //  T1            |                                       /----
10457             //                |                                  /----
10458             //                |                             /----
10459             //      -------------------------------------------------------------------------------------------------------
10460             //                                     |                            \
10461             //                                     |                               \
10462             //   T2                                |                                 \
10463             //                                     |                                   \
10464             //                                     |                                      \
10465             //      -------------------------------------------------------------------------------------------------------
10466             //
10467             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
10468             // it's just the min of the old and new starts.  i.e.:
10469             //
10470             //      0         10        20        30        40        50        60        70        80        90        100
10471             //      ------------------------------------------------------------*------------------------------------------
10472             //                |                                                 /
10473             //                |                                            /----
10474             //  T1            |                                       /----
10475             //                |                                  /----
10476             //                |                             /----
10477             //      ----------------------------------------$-------------------$------------------------------------------
10478             //                .                    |                            \
10479             //                .                    |                               \
10480             //   T2           .                    |                                 \
10481             //                .                    |                                   \
10482             //                .                    |                                      \
10483             //      ----------------------------------------------------------------------*--------------------------------
10484             //
10485             // (Note the dots represent the newly inferred start.
10486             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
10487             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
10488             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
10489             // means:
10490             //
10491             //      0         10        20        30        40        50        60        70        80        90        100
10492             //      --------------------------------------------------------------------------------*----------------------
10493             //                |                                                                     /
10494             //                |                                                                /----
10495             //  T1            |                                                           /----
10496             //                |                                                      /----
10497             //                |                                                 /----
10498             //      ------------------------------------------------------------$------------------------------------------
10499             //                .                    |                            \
10500             //                .                    |                               \
10501             //   T2           .                    |                                 \
10502             //                .                    |                                   \
10503             //                .                    |                                      \
10504             //      ----------------------------------------------------------------------*--------------------------------
10505             //
10506             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
10507             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
10508             // that's the same as if we started at char 80 instead of 60.
10509             //
10510             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
10511             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
10512             // first.
10513             //
10514             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
10515             // semantics: { { start: 10, length: 70 }, newLength: 60 }
10516             //
10517             // The math then works out as follows.
10518             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
10519             // final result like so:
10520             //
10521             // {
10522             //      oldStart3: Min(oldStart1, oldStart2),
10523             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
10524             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
10525             // }
10526             var oldStart1 = oldStartN;
10527             var oldEnd1 = oldEndN;
10528             var newEnd1 = newEndN;
10529             var oldStart2 = nextChange.span.start;
10530             var oldEnd2 = textSpanEnd(nextChange.span);
10531             var newEnd2 = oldStart2 + nextChange.newLength;
10532             oldStartN = Math.min(oldStart1, oldStart2);
10533             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
10534             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
10535         }
10536         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
10537     }
10538     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
10539     function getTypeParameterOwner(d) {
10540         if (d && d.kind === 155 /* TypeParameter */) {
10541             for (var current = d; current; current = current.parent) {
10542                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 246 /* InterfaceDeclaration */) {
10543                     return current;
10544                 }
10545             }
10546         }
10547     }
10548     ts.getTypeParameterOwner = getTypeParameterOwner;
10549     function isParameterPropertyDeclaration(node, parent) {
10550         return ts.hasModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 162 /* Constructor */;
10551     }
10552     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
10553     function isEmptyBindingPattern(node) {
10554         if (isBindingPattern(node)) {
10555             return ts.every(node.elements, isEmptyBindingElement);
10556         }
10557         return false;
10558     }
10559     ts.isEmptyBindingPattern = isEmptyBindingPattern;
10560     function isEmptyBindingElement(node) {
10561         if (isOmittedExpression(node)) {
10562             return true;
10563         }
10564         return isEmptyBindingPattern(node.name);
10565     }
10566     ts.isEmptyBindingElement = isEmptyBindingElement;
10567     function walkUpBindingElementsAndPatterns(binding) {
10568         var node = binding.parent;
10569         while (isBindingElement(node.parent)) {
10570             node = node.parent.parent;
10571         }
10572         return node.parent;
10573     }
10574     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
10575     function getCombinedFlags(node, getFlags) {
10576         if (isBindingElement(node)) {
10577             node = walkUpBindingElementsAndPatterns(node);
10578         }
10579         var flags = getFlags(node);
10580         if (node.kind === 242 /* VariableDeclaration */) {
10581             node = node.parent;
10582         }
10583         if (node && node.kind === 243 /* VariableDeclarationList */) {
10584             flags |= getFlags(node);
10585             node = node.parent;
10586         }
10587         if (node && node.kind === 225 /* VariableStatement */) {
10588             flags |= getFlags(node);
10589         }
10590         return flags;
10591     }
10592     function getCombinedModifierFlags(node) {
10593         return getCombinedFlags(node, ts.getModifierFlags);
10594     }
10595     ts.getCombinedModifierFlags = getCombinedModifierFlags;
10596     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
10597     // nodes like variable declarations and binding elements can returned a view of their flags
10598     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
10599     // stored on the variable declaration directly, but on the containing variable statement
10600     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
10601     // list.  By calling this function, all those flags are combined so that the client can treat
10602     // the node as if it actually had those flags.
10603     function getCombinedNodeFlags(node) {
10604         return getCombinedFlags(node, function (n) { return n.flags; });
10605     }
10606     ts.getCombinedNodeFlags = getCombinedNodeFlags;
10607     /**
10608      * Checks to see if the locale is in the appropriate format,
10609      * and if it is, attempts to set the appropriate language.
10610      */
10611     function validateLocaleAndSetLanguage(locale, sys, errors) {
10612         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
10613         if (!matchResult) {
10614             if (errors) {
10615                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
10616             }
10617             return;
10618         }
10619         var language = matchResult[1];
10620         var territory = matchResult[3];
10621         // First try the entire locale, then fall back to just language if that's all we have.
10622         // Either ways do not fail, and fallback to the English diagnostic strings.
10623         if (!trySetLanguageAndTerritory(language, territory, errors)) {
10624             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
10625         }
10626         // Set the UI locale for string collation
10627         ts.setUILocale(locale);
10628         function trySetLanguageAndTerritory(language, territory, errors) {
10629             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
10630             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
10631             var filePath = ts.combinePaths(containingDirectoryPath, language);
10632             if (territory) {
10633                 filePath = filePath + "-" + territory;
10634             }
10635             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
10636             if (!sys.fileExists(filePath)) {
10637                 return false;
10638             }
10639             // TODO: Add codePage support for readFile?
10640             var fileContents = "";
10641             try {
10642                 fileContents = sys.readFile(filePath);
10643             }
10644             catch (e) {
10645                 if (errors) {
10646                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
10647                 }
10648                 return false;
10649             }
10650             try {
10651                 // this is a global mutation (or live binding update)!
10652                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
10653             }
10654             catch (_a) {
10655                 if (errors) {
10656                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
10657                 }
10658                 return false;
10659             }
10660             return true;
10661         }
10662     }
10663     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
10664     function getOriginalNode(node, nodeTest) {
10665         if (node) {
10666             while (node.original !== undefined) {
10667                 node = node.original;
10668             }
10669         }
10670         return !nodeTest || nodeTest(node) ? node : undefined;
10671     }
10672     ts.getOriginalNode = getOriginalNode;
10673     /**
10674      * Gets a value indicating whether a node originated in the parse tree.
10675      *
10676      * @param node The node to test.
10677      */
10678     function isParseTreeNode(node) {
10679         return (node.flags & 8 /* Synthesized */) === 0;
10680     }
10681     ts.isParseTreeNode = isParseTreeNode;
10682     function getParseTreeNode(node, nodeTest) {
10683         if (node === undefined || isParseTreeNode(node)) {
10684             return node;
10685         }
10686         node = getOriginalNode(node);
10687         if (isParseTreeNode(node) && (!nodeTest || nodeTest(node))) {
10688             return node;
10689         }
10690         return undefined;
10691     }
10692     ts.getParseTreeNode = getParseTreeNode;
10693     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
10694     function escapeLeadingUnderscores(identifier) {
10695         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
10696     }
10697     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
10698     /**
10699      * Remove extra underscore from escaped identifier text content.
10700      *
10701      * @param identifier The escaped identifier text.
10702      * @returns The unescaped identifier text.
10703      */
10704     function unescapeLeadingUnderscores(identifier) {
10705         var id = identifier;
10706         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
10707     }
10708     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
10709     function idText(identifierOrPrivateName) {
10710         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
10711     }
10712     ts.idText = idText;
10713     function symbolName(symbol) {
10714         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
10715             return idText(symbol.valueDeclaration.name);
10716         }
10717         return unescapeLeadingUnderscores(symbol.escapedName);
10718     }
10719     ts.symbolName = symbolName;
10720     /**
10721      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
10722      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
10723      * will be merged with)
10724      */
10725     function nameForNamelessJSDocTypedef(declaration) {
10726         var hostNode = declaration.parent.parent;
10727         if (!hostNode) {
10728             return undefined;
10729         }
10730         // Covers classes, functions - any named declaration host node
10731         if (isDeclaration(hostNode)) {
10732             return getDeclarationIdentifier(hostNode);
10733         }
10734         // Covers remaining cases (returning undefined if none match).
10735         switch (hostNode.kind) {
10736             case 225 /* VariableStatement */:
10737                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
10738                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
10739                 }
10740                 break;
10741             case 226 /* ExpressionStatement */:
10742                 var expr = hostNode.expression;
10743                 if (expr.kind === 209 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
10744                     expr = expr.left;
10745                 }
10746                 switch (expr.kind) {
10747                     case 194 /* PropertyAccessExpression */:
10748                         return expr.name;
10749                     case 195 /* ElementAccessExpression */:
10750                         var arg = expr.argumentExpression;
10751                         if (isIdentifier(arg)) {
10752                             return arg;
10753                         }
10754                 }
10755                 break;
10756             case 200 /* ParenthesizedExpression */: {
10757                 return getDeclarationIdentifier(hostNode.expression);
10758             }
10759             case 238 /* LabeledStatement */: {
10760                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
10761                     return getDeclarationIdentifier(hostNode.statement);
10762                 }
10763                 break;
10764             }
10765         }
10766     }
10767     function getDeclarationIdentifier(node) {
10768         var name = getNameOfDeclaration(node);
10769         return name && isIdentifier(name) ? name : undefined;
10770     }
10771     /** @internal */
10772     function nodeHasName(statement, name) {
10773         if (isNamedDeclaration(statement) && isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
10774             return true;
10775         }
10776         if (isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
10777             return true;
10778         }
10779         return false;
10780     }
10781     ts.nodeHasName = nodeHasName;
10782     function getNameOfJSDocTypedef(declaration) {
10783         return declaration.name || nameForNamelessJSDocTypedef(declaration);
10784     }
10785     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
10786     /** @internal */
10787     function isNamedDeclaration(node) {
10788         return !!node.name; // A 'name' property should always be a DeclarationName.
10789     }
10790     ts.isNamedDeclaration = isNamedDeclaration;
10791     /** @internal */
10792     function getNonAssignedNameOfDeclaration(declaration) {
10793         switch (declaration.kind) {
10794             case 75 /* Identifier */:
10795                 return declaration;
10796             case 323 /* JSDocPropertyTag */:
10797             case 317 /* JSDocParameterTag */: {
10798                 var name = declaration.name;
10799                 if (name.kind === 153 /* QualifiedName */) {
10800                     return name.right;
10801                 }
10802                 break;
10803             }
10804             case 196 /* CallExpression */:
10805             case 209 /* BinaryExpression */: {
10806                 var expr_1 = declaration;
10807                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
10808                     case 1 /* ExportsProperty */:
10809                     case 4 /* ThisProperty */:
10810                     case 5 /* Property */:
10811                     case 3 /* PrototypeProperty */:
10812                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
10813                     case 7 /* ObjectDefinePropertyValue */:
10814                     case 8 /* ObjectDefinePropertyExports */:
10815                     case 9 /* ObjectDefinePrototypeProperty */:
10816                         return expr_1.arguments[1];
10817                     default:
10818                         return undefined;
10819                 }
10820             }
10821             case 322 /* JSDocTypedefTag */:
10822                 return getNameOfJSDocTypedef(declaration);
10823             case 316 /* JSDocEnumTag */:
10824                 return nameForNamelessJSDocTypedef(declaration);
10825             case 259 /* ExportAssignment */: {
10826                 var expression = declaration.expression;
10827                 return isIdentifier(expression) ? expression : undefined;
10828             }
10829             case 195 /* ElementAccessExpression */:
10830                 var expr = declaration;
10831                 if (ts.isBindableStaticElementAccessExpression(expr)) {
10832                     return expr.argumentExpression;
10833                 }
10834         }
10835         return declaration.name;
10836     }
10837     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
10838     function getNameOfDeclaration(declaration) {
10839         if (declaration === undefined)
10840             return undefined;
10841         return getNonAssignedNameOfDeclaration(declaration) ||
10842             (isFunctionExpression(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
10843     }
10844     ts.getNameOfDeclaration = getNameOfDeclaration;
10845     function getAssignedName(node) {
10846         if (!node.parent) {
10847             return undefined;
10848         }
10849         else if (isPropertyAssignment(node.parent) || isBindingElement(node.parent)) {
10850             return node.parent.name;
10851         }
10852         else if (isBinaryExpression(node.parent) && node === node.parent.right) {
10853             if (isIdentifier(node.parent.left)) {
10854                 return node.parent.left;
10855             }
10856             else if (ts.isAccessExpression(node.parent.left)) {
10857                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
10858             }
10859         }
10860         else if (isVariableDeclaration(node.parent) && isIdentifier(node.parent.name)) {
10861             return node.parent.name;
10862         }
10863     }
10864     /**
10865      * Gets the JSDoc parameter tags for the node if present.
10866      *
10867      * @remarks Returns any JSDoc param tag whose name matches the provided
10868      * parameter, whether a param tag on a containing function
10869      * expression, or a param tag on a variable declaration whose
10870      * initializer is the containing function. The tags closest to the
10871      * node are returned first, so in the previous example, the param
10872      * tag on the containing function expression would be first.
10873      *
10874      * For binding patterns, parameter tags are matched by position.
10875      */
10876     function getJSDocParameterTags(param) {
10877         if (param.name) {
10878             if (isIdentifier(param.name)) {
10879                 var name_1 = param.name.escapedText;
10880                 return getJSDocTags(param.parent).filter(function (tag) { return isJSDocParameterTag(tag) && isIdentifier(tag.name) && tag.name.escapedText === name_1; });
10881             }
10882             else {
10883                 var i = param.parent.parameters.indexOf(param);
10884                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
10885                 var paramTags = getJSDocTags(param.parent).filter(isJSDocParameterTag);
10886                 if (i < paramTags.length) {
10887                     return [paramTags[i]];
10888                 }
10889             }
10890         }
10891         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
10892         return ts.emptyArray;
10893     }
10894     ts.getJSDocParameterTags = getJSDocParameterTags;
10895     /**
10896      * Gets the JSDoc type parameter tags for the node if present.
10897      *
10898      * @remarks Returns any JSDoc template tag whose names match the provided
10899      * parameter, whether a template tag on a containing function
10900      * expression, or a template tag on a variable declaration whose
10901      * initializer is the containing function. The tags closest to the
10902      * node are returned first, so in the previous example, the template
10903      * tag on the containing function expression would be first.
10904      */
10905     function getJSDocTypeParameterTags(param) {
10906         var name = param.name.escapedText;
10907         return getJSDocTags(param.parent).filter(function (tag) {
10908             return isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
10909         });
10910     }
10911     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
10912     /**
10913      * Return true if the node has JSDoc parameter tags.
10914      *
10915      * @remarks Includes parameter tags that are not directly on the node,
10916      * for example on a variable declaration whose initializer is a function expression.
10917      */
10918     function hasJSDocParameterTags(node) {
10919         return !!getFirstJSDocTag(node, isJSDocParameterTag);
10920     }
10921     ts.hasJSDocParameterTags = hasJSDocParameterTags;
10922     /** Gets the JSDoc augments tag for the node if present */
10923     function getJSDocAugmentsTag(node) {
10924         return getFirstJSDocTag(node, isJSDocAugmentsTag);
10925     }
10926     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
10927     /** Gets the JSDoc implements tags for the node if present */
10928     function getJSDocImplementsTags(node) {
10929         return getAllJSDocTags(node, isJSDocImplementsTag);
10930     }
10931     ts.getJSDocImplementsTags = getJSDocImplementsTags;
10932     /** Gets the JSDoc class tag for the node if present */
10933     function getJSDocClassTag(node) {
10934         return getFirstJSDocTag(node, isJSDocClassTag);
10935     }
10936     ts.getJSDocClassTag = getJSDocClassTag;
10937     /** Gets the JSDoc public tag for the node if present */
10938     function getJSDocPublicTag(node) {
10939         return getFirstJSDocTag(node, isJSDocPublicTag);
10940     }
10941     ts.getJSDocPublicTag = getJSDocPublicTag;
10942     /** Gets the JSDoc private tag for the node if present */
10943     function getJSDocPrivateTag(node) {
10944         return getFirstJSDocTag(node, isJSDocPrivateTag);
10945     }
10946     ts.getJSDocPrivateTag = getJSDocPrivateTag;
10947     /** Gets the JSDoc protected tag for the node if present */
10948     function getJSDocProtectedTag(node) {
10949         return getFirstJSDocTag(node, isJSDocProtectedTag);
10950     }
10951     ts.getJSDocProtectedTag = getJSDocProtectedTag;
10952     /** Gets the JSDoc protected tag for the node if present */
10953     function getJSDocReadonlyTag(node) {
10954         return getFirstJSDocTag(node, isJSDocReadonlyTag);
10955     }
10956     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
10957     /** Gets the JSDoc enum tag for the node if present */
10958     function getJSDocEnumTag(node) {
10959         return getFirstJSDocTag(node, isJSDocEnumTag);
10960     }
10961     ts.getJSDocEnumTag = getJSDocEnumTag;
10962     /** Gets the JSDoc this tag for the node if present */
10963     function getJSDocThisTag(node) {
10964         return getFirstJSDocTag(node, isJSDocThisTag);
10965     }
10966     ts.getJSDocThisTag = getJSDocThisTag;
10967     /** Gets the JSDoc return tag for the node if present */
10968     function getJSDocReturnTag(node) {
10969         return getFirstJSDocTag(node, isJSDocReturnTag);
10970     }
10971     ts.getJSDocReturnTag = getJSDocReturnTag;
10972     /** Gets the JSDoc template tag for the node if present */
10973     function getJSDocTemplateTag(node) {
10974         return getFirstJSDocTag(node, isJSDocTemplateTag);
10975     }
10976     ts.getJSDocTemplateTag = getJSDocTemplateTag;
10977     /** Gets the JSDoc type tag for the node if present and valid */
10978     function getJSDocTypeTag(node) {
10979         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
10980         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
10981         if (tag && tag.typeExpression && tag.typeExpression.type) {
10982             return tag;
10983         }
10984         return undefined;
10985     }
10986     ts.getJSDocTypeTag = getJSDocTypeTag;
10987     /**
10988      * Gets the type node for the node if provided via JSDoc.
10989      *
10990      * @remarks The search includes any JSDoc param tag that relates
10991      * to the provided parameter, for example a type tag on the
10992      * parameter itself, or a param tag on a containing function
10993      * expression, or a param tag on a variable declaration whose
10994      * initializer is the containing function. The tags closest to the
10995      * node are examined first, so in the previous example, the type
10996      * tag directly on the node would be returned.
10997      */
10998     function getJSDocType(node) {
10999         var tag = getFirstJSDocTag(node, isJSDocTypeTag);
11000         if (!tag && isParameter(node)) {
11001             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
11002         }
11003         return tag && tag.typeExpression && tag.typeExpression.type;
11004     }
11005     ts.getJSDocType = getJSDocType;
11006     /**
11007      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
11008      *
11009      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
11010      * gets the type from inside the braces, after the fat arrow, etc.
11011      */
11012     function getJSDocReturnType(node) {
11013         var returnTag = getJSDocReturnTag(node);
11014         if (returnTag && returnTag.typeExpression) {
11015             return returnTag.typeExpression.type;
11016         }
11017         var typeTag = getJSDocTypeTag(node);
11018         if (typeTag && typeTag.typeExpression) {
11019             var type = typeTag.typeExpression.type;
11020             if (isTypeLiteralNode(type)) {
11021                 var sig = ts.find(type.members, isCallSignatureDeclaration);
11022                 return sig && sig.type;
11023             }
11024             if (isFunctionTypeNode(type) || isJSDocFunctionType(type)) {
11025                 return type.type;
11026             }
11027         }
11028     }
11029     ts.getJSDocReturnType = getJSDocReturnType;
11030     /** Get all JSDoc tags related to a node, including those on parent nodes. */
11031     function getJSDocTags(node) {
11032         var tags = node.jsDocCache;
11033         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
11034         if (tags === undefined) {
11035             var comments = ts.getJSDocCommentsAndTags(node);
11036             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
11037             node.jsDocCache = tags = ts.flatMap(comments, function (j) { return isJSDoc(j) ? j.tags : j; });
11038         }
11039         return tags;
11040     }
11041     ts.getJSDocTags = getJSDocTags;
11042     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
11043     function getFirstJSDocTag(node, predicate) {
11044         return ts.find(getJSDocTags(node), predicate);
11045     }
11046     /** Gets all JSDoc tags that match a specified predicate */
11047     function getAllJSDocTags(node, predicate) {
11048         return getJSDocTags(node).filter(predicate);
11049     }
11050     ts.getAllJSDocTags = getAllJSDocTags;
11051     /** Gets all JSDoc tags of a specified kind */
11052     function getAllJSDocTagsOfKind(node, kind) {
11053         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
11054     }
11055     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
11056     /**
11057      * Gets the effective type parameters. If the node was parsed in a
11058      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
11059      */
11060     function getEffectiveTypeParameterDeclarations(node) {
11061         if (isJSDocSignature(node)) {
11062             return ts.emptyArray;
11063         }
11064         if (ts.isJSDocTypeAlias(node)) {
11065             ts.Debug.assert(node.parent.kind === 303 /* JSDocComment */);
11066             return ts.flatMap(node.parent.tags, function (tag) { return isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
11067         }
11068         if (node.typeParameters) {
11069             return node.typeParameters;
11070         }
11071         if (ts.isInJSFile(node)) {
11072             var decls = ts.getJSDocTypeParameterDeclarations(node);
11073             if (decls.length) {
11074                 return decls;
11075             }
11076             var typeTag = getJSDocType(node);
11077             if (typeTag && isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
11078                 return typeTag.typeParameters;
11079             }
11080         }
11081         return ts.emptyArray;
11082     }
11083     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
11084     function getEffectiveConstraintOfTypeParameter(node) {
11085         return node.constraint ? node.constraint :
11086             isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
11087                 undefined;
11088     }
11089     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
11090     // #region
11091     // Simple node tests of the form `node.kind === SyntaxKind.Foo`.
11092     // Literals
11093     function isNumericLiteral(node) {
11094         return node.kind === 8 /* NumericLiteral */;
11095     }
11096     ts.isNumericLiteral = isNumericLiteral;
11097     function isBigIntLiteral(node) {
11098         return node.kind === 9 /* BigIntLiteral */;
11099     }
11100     ts.isBigIntLiteral = isBigIntLiteral;
11101     function isStringLiteral(node) {
11102         return node.kind === 10 /* StringLiteral */;
11103     }
11104     ts.isStringLiteral = isStringLiteral;
11105     function isJsxText(node) {
11106         return node.kind === 11 /* JsxText */;
11107     }
11108     ts.isJsxText = isJsxText;
11109     function isRegularExpressionLiteral(node) {
11110         return node.kind === 13 /* RegularExpressionLiteral */;
11111     }
11112     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
11113     function isNoSubstitutionTemplateLiteral(node) {
11114         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
11115     }
11116     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
11117     // Pseudo-literals
11118     function isTemplateHead(node) {
11119         return node.kind === 15 /* TemplateHead */;
11120     }
11121     ts.isTemplateHead = isTemplateHead;
11122     function isTemplateMiddle(node) {
11123         return node.kind === 16 /* TemplateMiddle */;
11124     }
11125     ts.isTemplateMiddle = isTemplateMiddle;
11126     function isTemplateTail(node) {
11127         return node.kind === 17 /* TemplateTail */;
11128     }
11129     ts.isTemplateTail = isTemplateTail;
11130     function isIdentifier(node) {
11131         return node.kind === 75 /* Identifier */;
11132     }
11133     ts.isIdentifier = isIdentifier;
11134     // Names
11135     function isQualifiedName(node) {
11136         return node.kind === 153 /* QualifiedName */;
11137     }
11138     ts.isQualifiedName = isQualifiedName;
11139     function isComputedPropertyName(node) {
11140         return node.kind === 154 /* ComputedPropertyName */;
11141     }
11142     ts.isComputedPropertyName = isComputedPropertyName;
11143     function isPrivateIdentifier(node) {
11144         return node.kind === 76 /* PrivateIdentifier */;
11145     }
11146     ts.isPrivateIdentifier = isPrivateIdentifier;
11147     function isIdentifierOrPrivateIdentifier(node) {
11148         return node.kind === 75 /* Identifier */ || node.kind === 76 /* PrivateIdentifier */;
11149     }
11150     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
11151     // Signature elements
11152     function isTypeParameterDeclaration(node) {
11153         return node.kind === 155 /* TypeParameter */;
11154     }
11155     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
11156     function isParameter(node) {
11157         return node.kind === 156 /* Parameter */;
11158     }
11159     ts.isParameter = isParameter;
11160     function isDecorator(node) {
11161         return node.kind === 157 /* Decorator */;
11162     }
11163     ts.isDecorator = isDecorator;
11164     // TypeMember
11165     function isPropertySignature(node) {
11166         return node.kind === 158 /* PropertySignature */;
11167     }
11168     ts.isPropertySignature = isPropertySignature;
11169     function isPropertyDeclaration(node) {
11170         return node.kind === 159 /* PropertyDeclaration */;
11171     }
11172     ts.isPropertyDeclaration = isPropertyDeclaration;
11173     function isMethodSignature(node) {
11174         return node.kind === 160 /* MethodSignature */;
11175     }
11176     ts.isMethodSignature = isMethodSignature;
11177     function isMethodDeclaration(node) {
11178         return node.kind === 161 /* MethodDeclaration */;
11179     }
11180     ts.isMethodDeclaration = isMethodDeclaration;
11181     function isConstructorDeclaration(node) {
11182         return node.kind === 162 /* Constructor */;
11183     }
11184     ts.isConstructorDeclaration = isConstructorDeclaration;
11185     function isGetAccessorDeclaration(node) {
11186         return node.kind === 163 /* GetAccessor */;
11187     }
11188     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
11189     function isSetAccessorDeclaration(node) {
11190         return node.kind === 164 /* SetAccessor */;
11191     }
11192     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
11193     function isCallSignatureDeclaration(node) {
11194         return node.kind === 165 /* CallSignature */;
11195     }
11196     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
11197     function isConstructSignatureDeclaration(node) {
11198         return node.kind === 166 /* ConstructSignature */;
11199     }
11200     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
11201     function isIndexSignatureDeclaration(node) {
11202         return node.kind === 167 /* IndexSignature */;
11203     }
11204     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
11205     /* @internal */
11206     function isGetOrSetAccessorDeclaration(node) {
11207         return node.kind === 164 /* SetAccessor */ || node.kind === 163 /* GetAccessor */;
11208     }
11209     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
11210     // Type
11211     function isTypePredicateNode(node) {
11212         return node.kind === 168 /* TypePredicate */;
11213     }
11214     ts.isTypePredicateNode = isTypePredicateNode;
11215     function isTypeReferenceNode(node) {
11216         return node.kind === 169 /* TypeReference */;
11217     }
11218     ts.isTypeReferenceNode = isTypeReferenceNode;
11219     function isFunctionTypeNode(node) {
11220         return node.kind === 170 /* FunctionType */;
11221     }
11222     ts.isFunctionTypeNode = isFunctionTypeNode;
11223     function isConstructorTypeNode(node) {
11224         return node.kind === 171 /* ConstructorType */;
11225     }
11226     ts.isConstructorTypeNode = isConstructorTypeNode;
11227     function isTypeQueryNode(node) {
11228         return node.kind === 172 /* TypeQuery */;
11229     }
11230     ts.isTypeQueryNode = isTypeQueryNode;
11231     function isTypeLiteralNode(node) {
11232         return node.kind === 173 /* TypeLiteral */;
11233     }
11234     ts.isTypeLiteralNode = isTypeLiteralNode;
11235     function isArrayTypeNode(node) {
11236         return node.kind === 174 /* ArrayType */;
11237     }
11238     ts.isArrayTypeNode = isArrayTypeNode;
11239     function isTupleTypeNode(node) {
11240         return node.kind === 175 /* TupleType */;
11241     }
11242     ts.isTupleTypeNode = isTupleTypeNode;
11243     function isUnionTypeNode(node) {
11244         return node.kind === 178 /* UnionType */;
11245     }
11246     ts.isUnionTypeNode = isUnionTypeNode;
11247     function isIntersectionTypeNode(node) {
11248         return node.kind === 179 /* IntersectionType */;
11249     }
11250     ts.isIntersectionTypeNode = isIntersectionTypeNode;
11251     function isConditionalTypeNode(node) {
11252         return node.kind === 180 /* ConditionalType */;
11253     }
11254     ts.isConditionalTypeNode = isConditionalTypeNode;
11255     function isInferTypeNode(node) {
11256         return node.kind === 181 /* InferType */;
11257     }
11258     ts.isInferTypeNode = isInferTypeNode;
11259     function isParenthesizedTypeNode(node) {
11260         return node.kind === 182 /* ParenthesizedType */;
11261     }
11262     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
11263     function isThisTypeNode(node) {
11264         return node.kind === 183 /* ThisType */;
11265     }
11266     ts.isThisTypeNode = isThisTypeNode;
11267     function isTypeOperatorNode(node) {
11268         return node.kind === 184 /* TypeOperator */;
11269     }
11270     ts.isTypeOperatorNode = isTypeOperatorNode;
11271     function isIndexedAccessTypeNode(node) {
11272         return node.kind === 185 /* IndexedAccessType */;
11273     }
11274     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
11275     function isMappedTypeNode(node) {
11276         return node.kind === 186 /* MappedType */;
11277     }
11278     ts.isMappedTypeNode = isMappedTypeNode;
11279     function isLiteralTypeNode(node) {
11280         return node.kind === 187 /* LiteralType */;
11281     }
11282     ts.isLiteralTypeNode = isLiteralTypeNode;
11283     function isImportTypeNode(node) {
11284         return node.kind === 188 /* ImportType */;
11285     }
11286     ts.isImportTypeNode = isImportTypeNode;
11287     // Binding patterns
11288     function isObjectBindingPattern(node) {
11289         return node.kind === 189 /* ObjectBindingPattern */;
11290     }
11291     ts.isObjectBindingPattern = isObjectBindingPattern;
11292     function isArrayBindingPattern(node) {
11293         return node.kind === 190 /* ArrayBindingPattern */;
11294     }
11295     ts.isArrayBindingPattern = isArrayBindingPattern;
11296     function isBindingElement(node) {
11297         return node.kind === 191 /* BindingElement */;
11298     }
11299     ts.isBindingElement = isBindingElement;
11300     // Expression
11301     function isArrayLiteralExpression(node) {
11302         return node.kind === 192 /* ArrayLiteralExpression */;
11303     }
11304     ts.isArrayLiteralExpression = isArrayLiteralExpression;
11305     function isObjectLiteralExpression(node) {
11306         return node.kind === 193 /* ObjectLiteralExpression */;
11307     }
11308     ts.isObjectLiteralExpression = isObjectLiteralExpression;
11309     function isPropertyAccessExpression(node) {
11310         return node.kind === 194 /* PropertyAccessExpression */;
11311     }
11312     ts.isPropertyAccessExpression = isPropertyAccessExpression;
11313     function isPropertyAccessChain(node) {
11314         return isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11315     }
11316     ts.isPropertyAccessChain = isPropertyAccessChain;
11317     function isElementAccessExpression(node) {
11318         return node.kind === 195 /* ElementAccessExpression */;
11319     }
11320     ts.isElementAccessExpression = isElementAccessExpression;
11321     function isElementAccessChain(node) {
11322         return isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11323     }
11324     ts.isElementAccessChain = isElementAccessChain;
11325     function isCallExpression(node) {
11326         return node.kind === 196 /* CallExpression */;
11327     }
11328     ts.isCallExpression = isCallExpression;
11329     function isCallChain(node) {
11330         return isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11331     }
11332     ts.isCallChain = isCallChain;
11333     function isOptionalChain(node) {
11334         var kind = node.kind;
11335         return !!(node.flags & 32 /* OptionalChain */) &&
11336             (kind === 194 /* PropertyAccessExpression */
11337                 || kind === 195 /* ElementAccessExpression */
11338                 || kind === 196 /* CallExpression */
11339                 || kind === 218 /* NonNullExpression */);
11340     }
11341     ts.isOptionalChain = isOptionalChain;
11342     /* @internal */
11343     function isOptionalChainRoot(node) {
11344         return isOptionalChain(node) && !isNonNullExpression(node) && !!node.questionDotToken;
11345     }
11346     ts.isOptionalChainRoot = isOptionalChainRoot;
11347     /**
11348      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
11349      */
11350     /* @internal */
11351     function isExpressionOfOptionalChainRoot(node) {
11352         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
11353     }
11354     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
11355     /**
11356      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
11357      *
11358      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
11359      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
11360      * 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)
11361      * 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
11362      *   the end of the chain starting at `c?.`)
11363      * 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
11364      *   the end of the chain starting at `a?.`)
11365      */
11366     /* @internal */
11367     function isOutermostOptionalChain(node) {
11368         return !isOptionalChain(node.parent) // cases 1, 2, and 3
11369             || isOptionalChainRoot(node.parent) // case 4
11370             || node !== node.parent.expression; // case 5
11371     }
11372     ts.isOutermostOptionalChain = isOutermostOptionalChain;
11373     function isNullishCoalesce(node) {
11374         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
11375     }
11376     ts.isNullishCoalesce = isNullishCoalesce;
11377     function isNewExpression(node) {
11378         return node.kind === 197 /* NewExpression */;
11379     }
11380     ts.isNewExpression = isNewExpression;
11381     function isTaggedTemplateExpression(node) {
11382         return node.kind === 198 /* TaggedTemplateExpression */;
11383     }
11384     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
11385     function isTypeAssertion(node) {
11386         return node.kind === 199 /* TypeAssertionExpression */;
11387     }
11388     ts.isTypeAssertion = isTypeAssertion;
11389     function isConstTypeReference(node) {
11390         return isTypeReferenceNode(node) && isIdentifier(node.typeName) &&
11391             node.typeName.escapedText === "const" && !node.typeArguments;
11392     }
11393     ts.isConstTypeReference = isConstTypeReference;
11394     function isParenthesizedExpression(node) {
11395         return node.kind === 200 /* ParenthesizedExpression */;
11396     }
11397     ts.isParenthesizedExpression = isParenthesizedExpression;
11398     function skipPartiallyEmittedExpressions(node) {
11399         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
11400     }
11401     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
11402     function isFunctionExpression(node) {
11403         return node.kind === 201 /* FunctionExpression */;
11404     }
11405     ts.isFunctionExpression = isFunctionExpression;
11406     function isArrowFunction(node) {
11407         return node.kind === 202 /* ArrowFunction */;
11408     }
11409     ts.isArrowFunction = isArrowFunction;
11410     function isDeleteExpression(node) {
11411         return node.kind === 203 /* DeleteExpression */;
11412     }
11413     ts.isDeleteExpression = isDeleteExpression;
11414     function isTypeOfExpression(node) {
11415         return node.kind === 204 /* TypeOfExpression */;
11416     }
11417     ts.isTypeOfExpression = isTypeOfExpression;
11418     function isVoidExpression(node) {
11419         return node.kind === 205 /* VoidExpression */;
11420     }
11421     ts.isVoidExpression = isVoidExpression;
11422     function isAwaitExpression(node) {
11423         return node.kind === 206 /* AwaitExpression */;
11424     }
11425     ts.isAwaitExpression = isAwaitExpression;
11426     function isPrefixUnaryExpression(node) {
11427         return node.kind === 207 /* PrefixUnaryExpression */;
11428     }
11429     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
11430     function isPostfixUnaryExpression(node) {
11431         return node.kind === 208 /* PostfixUnaryExpression */;
11432     }
11433     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
11434     function isBinaryExpression(node) {
11435         return node.kind === 209 /* BinaryExpression */;
11436     }
11437     ts.isBinaryExpression = isBinaryExpression;
11438     function isConditionalExpression(node) {
11439         return node.kind === 210 /* ConditionalExpression */;
11440     }
11441     ts.isConditionalExpression = isConditionalExpression;
11442     function isTemplateExpression(node) {
11443         return node.kind === 211 /* TemplateExpression */;
11444     }
11445     ts.isTemplateExpression = isTemplateExpression;
11446     function isYieldExpression(node) {
11447         return node.kind === 212 /* YieldExpression */;
11448     }
11449     ts.isYieldExpression = isYieldExpression;
11450     function isSpreadElement(node) {
11451         return node.kind === 213 /* SpreadElement */;
11452     }
11453     ts.isSpreadElement = isSpreadElement;
11454     function isClassExpression(node) {
11455         return node.kind === 214 /* ClassExpression */;
11456     }
11457     ts.isClassExpression = isClassExpression;
11458     function isOmittedExpression(node) {
11459         return node.kind === 215 /* OmittedExpression */;
11460     }
11461     ts.isOmittedExpression = isOmittedExpression;
11462     function isExpressionWithTypeArguments(node) {
11463         return node.kind === 216 /* ExpressionWithTypeArguments */;
11464     }
11465     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
11466     function isAsExpression(node) {
11467         return node.kind === 217 /* AsExpression */;
11468     }
11469     ts.isAsExpression = isAsExpression;
11470     function isNonNullExpression(node) {
11471         return node.kind === 218 /* NonNullExpression */;
11472     }
11473     ts.isNonNullExpression = isNonNullExpression;
11474     function isNonNullChain(node) {
11475         return isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
11476     }
11477     ts.isNonNullChain = isNonNullChain;
11478     function isMetaProperty(node) {
11479         return node.kind === 219 /* MetaProperty */;
11480     }
11481     ts.isMetaProperty = isMetaProperty;
11482     // Misc
11483     function isTemplateSpan(node) {
11484         return node.kind === 221 /* TemplateSpan */;
11485     }
11486     ts.isTemplateSpan = isTemplateSpan;
11487     function isSemicolonClassElement(node) {
11488         return node.kind === 222 /* SemicolonClassElement */;
11489     }
11490     ts.isSemicolonClassElement = isSemicolonClassElement;
11491     // Block
11492     function isBlock(node) {
11493         return node.kind === 223 /* Block */;
11494     }
11495     ts.isBlock = isBlock;
11496     function isVariableStatement(node) {
11497         return node.kind === 225 /* VariableStatement */;
11498     }
11499     ts.isVariableStatement = isVariableStatement;
11500     function isEmptyStatement(node) {
11501         return node.kind === 224 /* EmptyStatement */;
11502     }
11503     ts.isEmptyStatement = isEmptyStatement;
11504     function isExpressionStatement(node) {
11505         return node.kind === 226 /* ExpressionStatement */;
11506     }
11507     ts.isExpressionStatement = isExpressionStatement;
11508     function isIfStatement(node) {
11509         return node.kind === 227 /* IfStatement */;
11510     }
11511     ts.isIfStatement = isIfStatement;
11512     function isDoStatement(node) {
11513         return node.kind === 228 /* DoStatement */;
11514     }
11515     ts.isDoStatement = isDoStatement;
11516     function isWhileStatement(node) {
11517         return node.kind === 229 /* WhileStatement */;
11518     }
11519     ts.isWhileStatement = isWhileStatement;
11520     function isForStatement(node) {
11521         return node.kind === 230 /* ForStatement */;
11522     }
11523     ts.isForStatement = isForStatement;
11524     function isForInStatement(node) {
11525         return node.kind === 231 /* ForInStatement */;
11526     }
11527     ts.isForInStatement = isForInStatement;
11528     function isForOfStatement(node) {
11529         return node.kind === 232 /* ForOfStatement */;
11530     }
11531     ts.isForOfStatement = isForOfStatement;
11532     function isContinueStatement(node) {
11533         return node.kind === 233 /* ContinueStatement */;
11534     }
11535     ts.isContinueStatement = isContinueStatement;
11536     function isBreakStatement(node) {
11537         return node.kind === 234 /* BreakStatement */;
11538     }
11539     ts.isBreakStatement = isBreakStatement;
11540     function isBreakOrContinueStatement(node) {
11541         return node.kind === 234 /* BreakStatement */ || node.kind === 233 /* ContinueStatement */;
11542     }
11543     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
11544     function isReturnStatement(node) {
11545         return node.kind === 235 /* ReturnStatement */;
11546     }
11547     ts.isReturnStatement = isReturnStatement;
11548     function isWithStatement(node) {
11549         return node.kind === 236 /* WithStatement */;
11550     }
11551     ts.isWithStatement = isWithStatement;
11552     function isSwitchStatement(node) {
11553         return node.kind === 237 /* SwitchStatement */;
11554     }
11555     ts.isSwitchStatement = isSwitchStatement;
11556     function isLabeledStatement(node) {
11557         return node.kind === 238 /* LabeledStatement */;
11558     }
11559     ts.isLabeledStatement = isLabeledStatement;
11560     function isThrowStatement(node) {
11561         return node.kind === 239 /* ThrowStatement */;
11562     }
11563     ts.isThrowStatement = isThrowStatement;
11564     function isTryStatement(node) {
11565         return node.kind === 240 /* TryStatement */;
11566     }
11567     ts.isTryStatement = isTryStatement;
11568     function isDebuggerStatement(node) {
11569         return node.kind === 241 /* DebuggerStatement */;
11570     }
11571     ts.isDebuggerStatement = isDebuggerStatement;
11572     function isVariableDeclaration(node) {
11573         return node.kind === 242 /* VariableDeclaration */;
11574     }
11575     ts.isVariableDeclaration = isVariableDeclaration;
11576     function isVariableDeclarationList(node) {
11577         return node.kind === 243 /* VariableDeclarationList */;
11578     }
11579     ts.isVariableDeclarationList = isVariableDeclarationList;
11580     function isFunctionDeclaration(node) {
11581         return node.kind === 244 /* FunctionDeclaration */;
11582     }
11583     ts.isFunctionDeclaration = isFunctionDeclaration;
11584     function isClassDeclaration(node) {
11585         return node.kind === 245 /* ClassDeclaration */;
11586     }
11587     ts.isClassDeclaration = isClassDeclaration;
11588     function isInterfaceDeclaration(node) {
11589         return node.kind === 246 /* InterfaceDeclaration */;
11590     }
11591     ts.isInterfaceDeclaration = isInterfaceDeclaration;
11592     function isTypeAliasDeclaration(node) {
11593         return node.kind === 247 /* TypeAliasDeclaration */;
11594     }
11595     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
11596     function isEnumDeclaration(node) {
11597         return node.kind === 248 /* EnumDeclaration */;
11598     }
11599     ts.isEnumDeclaration = isEnumDeclaration;
11600     function isModuleDeclaration(node) {
11601         return node.kind === 249 /* ModuleDeclaration */;
11602     }
11603     ts.isModuleDeclaration = isModuleDeclaration;
11604     function isModuleBlock(node) {
11605         return node.kind === 250 /* ModuleBlock */;
11606     }
11607     ts.isModuleBlock = isModuleBlock;
11608     function isCaseBlock(node) {
11609         return node.kind === 251 /* CaseBlock */;
11610     }
11611     ts.isCaseBlock = isCaseBlock;
11612     function isNamespaceExportDeclaration(node) {
11613         return node.kind === 252 /* NamespaceExportDeclaration */;
11614     }
11615     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
11616     function isImportEqualsDeclaration(node) {
11617         return node.kind === 253 /* ImportEqualsDeclaration */;
11618     }
11619     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
11620     function isImportDeclaration(node) {
11621         return node.kind === 254 /* ImportDeclaration */;
11622     }
11623     ts.isImportDeclaration = isImportDeclaration;
11624     function isImportClause(node) {
11625         return node.kind === 255 /* ImportClause */;
11626     }
11627     ts.isImportClause = isImportClause;
11628     function isNamespaceImport(node) {
11629         return node.kind === 256 /* NamespaceImport */;
11630     }
11631     ts.isNamespaceImport = isNamespaceImport;
11632     function isNamespaceExport(node) {
11633         return node.kind === 262 /* NamespaceExport */;
11634     }
11635     ts.isNamespaceExport = isNamespaceExport;
11636     function isNamedExportBindings(node) {
11637         return node.kind === 262 /* NamespaceExport */ || node.kind === 261 /* NamedExports */;
11638     }
11639     ts.isNamedExportBindings = isNamedExportBindings;
11640     function isNamedImports(node) {
11641         return node.kind === 257 /* NamedImports */;
11642     }
11643     ts.isNamedImports = isNamedImports;
11644     function isImportSpecifier(node) {
11645         return node.kind === 258 /* ImportSpecifier */;
11646     }
11647     ts.isImportSpecifier = isImportSpecifier;
11648     function isExportAssignment(node) {
11649         return node.kind === 259 /* ExportAssignment */;
11650     }
11651     ts.isExportAssignment = isExportAssignment;
11652     function isExportDeclaration(node) {
11653         return node.kind === 260 /* ExportDeclaration */;
11654     }
11655     ts.isExportDeclaration = isExportDeclaration;
11656     function isNamedExports(node) {
11657         return node.kind === 261 /* NamedExports */;
11658     }
11659     ts.isNamedExports = isNamedExports;
11660     function isExportSpecifier(node) {
11661         return node.kind === 263 /* ExportSpecifier */;
11662     }
11663     ts.isExportSpecifier = isExportSpecifier;
11664     function isMissingDeclaration(node) {
11665         return node.kind === 264 /* MissingDeclaration */;
11666     }
11667     ts.isMissingDeclaration = isMissingDeclaration;
11668     // Module References
11669     function isExternalModuleReference(node) {
11670         return node.kind === 265 /* ExternalModuleReference */;
11671     }
11672     ts.isExternalModuleReference = isExternalModuleReference;
11673     // JSX
11674     function isJsxElement(node) {
11675         return node.kind === 266 /* JsxElement */;
11676     }
11677     ts.isJsxElement = isJsxElement;
11678     function isJsxSelfClosingElement(node) {
11679         return node.kind === 267 /* JsxSelfClosingElement */;
11680     }
11681     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
11682     function isJsxOpeningElement(node) {
11683         return node.kind === 268 /* JsxOpeningElement */;
11684     }
11685     ts.isJsxOpeningElement = isJsxOpeningElement;
11686     function isJsxClosingElement(node) {
11687         return node.kind === 269 /* JsxClosingElement */;
11688     }
11689     ts.isJsxClosingElement = isJsxClosingElement;
11690     function isJsxFragment(node) {
11691         return node.kind === 270 /* JsxFragment */;
11692     }
11693     ts.isJsxFragment = isJsxFragment;
11694     function isJsxOpeningFragment(node) {
11695         return node.kind === 271 /* JsxOpeningFragment */;
11696     }
11697     ts.isJsxOpeningFragment = isJsxOpeningFragment;
11698     function isJsxClosingFragment(node) {
11699         return node.kind === 272 /* JsxClosingFragment */;
11700     }
11701     ts.isJsxClosingFragment = isJsxClosingFragment;
11702     function isJsxAttribute(node) {
11703         return node.kind === 273 /* JsxAttribute */;
11704     }
11705     ts.isJsxAttribute = isJsxAttribute;
11706     function isJsxAttributes(node) {
11707         return node.kind === 274 /* JsxAttributes */;
11708     }
11709     ts.isJsxAttributes = isJsxAttributes;
11710     function isJsxSpreadAttribute(node) {
11711         return node.kind === 275 /* JsxSpreadAttribute */;
11712     }
11713     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
11714     function isJsxExpression(node) {
11715         return node.kind === 276 /* JsxExpression */;
11716     }
11717     ts.isJsxExpression = isJsxExpression;
11718     // Clauses
11719     function isCaseClause(node) {
11720         return node.kind === 277 /* CaseClause */;
11721     }
11722     ts.isCaseClause = isCaseClause;
11723     function isDefaultClause(node) {
11724         return node.kind === 278 /* DefaultClause */;
11725     }
11726     ts.isDefaultClause = isDefaultClause;
11727     function isHeritageClause(node) {
11728         return node.kind === 279 /* HeritageClause */;
11729     }
11730     ts.isHeritageClause = isHeritageClause;
11731     function isCatchClause(node) {
11732         return node.kind === 280 /* CatchClause */;
11733     }
11734     ts.isCatchClause = isCatchClause;
11735     // Property assignments
11736     function isPropertyAssignment(node) {
11737         return node.kind === 281 /* PropertyAssignment */;
11738     }
11739     ts.isPropertyAssignment = isPropertyAssignment;
11740     function isShorthandPropertyAssignment(node) {
11741         return node.kind === 282 /* ShorthandPropertyAssignment */;
11742     }
11743     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
11744     function isSpreadAssignment(node) {
11745         return node.kind === 283 /* SpreadAssignment */;
11746     }
11747     ts.isSpreadAssignment = isSpreadAssignment;
11748     // Enum
11749     function isEnumMember(node) {
11750         return node.kind === 284 /* EnumMember */;
11751     }
11752     ts.isEnumMember = isEnumMember;
11753     // Top-level nodes
11754     function isSourceFile(node) {
11755         return node.kind === 290 /* SourceFile */;
11756     }
11757     ts.isSourceFile = isSourceFile;
11758     function isBundle(node) {
11759         return node.kind === 291 /* Bundle */;
11760     }
11761     ts.isBundle = isBundle;
11762     function isUnparsedSource(node) {
11763         return node.kind === 292 /* UnparsedSource */;
11764     }
11765     ts.isUnparsedSource = isUnparsedSource;
11766     function isUnparsedPrepend(node) {
11767         return node.kind === 286 /* UnparsedPrepend */;
11768     }
11769     ts.isUnparsedPrepend = isUnparsedPrepend;
11770     function isUnparsedTextLike(node) {
11771         switch (node.kind) {
11772             case 287 /* UnparsedText */:
11773             case 288 /* UnparsedInternalText */:
11774                 return true;
11775             default:
11776                 return false;
11777         }
11778     }
11779     ts.isUnparsedTextLike = isUnparsedTextLike;
11780     function isUnparsedNode(node) {
11781         return isUnparsedTextLike(node) ||
11782             node.kind === 285 /* UnparsedPrologue */ ||
11783             node.kind === 289 /* UnparsedSyntheticReference */;
11784     }
11785     ts.isUnparsedNode = isUnparsedNode;
11786     // JSDoc
11787     function isJSDocTypeExpression(node) {
11788         return node.kind === 294 /* JSDocTypeExpression */;
11789     }
11790     ts.isJSDocTypeExpression = isJSDocTypeExpression;
11791     function isJSDocAllType(node) {
11792         return node.kind === 295 /* JSDocAllType */;
11793     }
11794     ts.isJSDocAllType = isJSDocAllType;
11795     function isJSDocUnknownType(node) {
11796         return node.kind === 296 /* JSDocUnknownType */;
11797     }
11798     ts.isJSDocUnknownType = isJSDocUnknownType;
11799     function isJSDocNullableType(node) {
11800         return node.kind === 297 /* JSDocNullableType */;
11801     }
11802     ts.isJSDocNullableType = isJSDocNullableType;
11803     function isJSDocNonNullableType(node) {
11804         return node.kind === 298 /* JSDocNonNullableType */;
11805     }
11806     ts.isJSDocNonNullableType = isJSDocNonNullableType;
11807     function isJSDocOptionalType(node) {
11808         return node.kind === 299 /* JSDocOptionalType */;
11809     }
11810     ts.isJSDocOptionalType = isJSDocOptionalType;
11811     function isJSDocFunctionType(node) {
11812         return node.kind === 300 /* JSDocFunctionType */;
11813     }
11814     ts.isJSDocFunctionType = isJSDocFunctionType;
11815     function isJSDocVariadicType(node) {
11816         return node.kind === 301 /* JSDocVariadicType */;
11817     }
11818     ts.isJSDocVariadicType = isJSDocVariadicType;
11819     function isJSDoc(node) {
11820         return node.kind === 303 /* JSDocComment */;
11821     }
11822     ts.isJSDoc = isJSDoc;
11823     function isJSDocAuthorTag(node) {
11824         return node.kind === 309 /* JSDocAuthorTag */;
11825     }
11826     ts.isJSDocAuthorTag = isJSDocAuthorTag;
11827     function isJSDocAugmentsTag(node) {
11828         return node.kind === 307 /* JSDocAugmentsTag */;
11829     }
11830     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
11831     function isJSDocImplementsTag(node) {
11832         return node.kind === 308 /* JSDocImplementsTag */;
11833     }
11834     ts.isJSDocImplementsTag = isJSDocImplementsTag;
11835     function isJSDocClassTag(node) {
11836         return node.kind === 310 /* JSDocClassTag */;
11837     }
11838     ts.isJSDocClassTag = isJSDocClassTag;
11839     function isJSDocPublicTag(node) {
11840         return node.kind === 311 /* JSDocPublicTag */;
11841     }
11842     ts.isJSDocPublicTag = isJSDocPublicTag;
11843     function isJSDocPrivateTag(node) {
11844         return node.kind === 312 /* JSDocPrivateTag */;
11845     }
11846     ts.isJSDocPrivateTag = isJSDocPrivateTag;
11847     function isJSDocProtectedTag(node) {
11848         return node.kind === 313 /* JSDocProtectedTag */;
11849     }
11850     ts.isJSDocProtectedTag = isJSDocProtectedTag;
11851     function isJSDocReadonlyTag(node) {
11852         return node.kind === 314 /* JSDocReadonlyTag */;
11853     }
11854     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
11855     function isJSDocEnumTag(node) {
11856         return node.kind === 316 /* JSDocEnumTag */;
11857     }
11858     ts.isJSDocEnumTag = isJSDocEnumTag;
11859     function isJSDocThisTag(node) {
11860         return node.kind === 319 /* JSDocThisTag */;
11861     }
11862     ts.isJSDocThisTag = isJSDocThisTag;
11863     function isJSDocParameterTag(node) {
11864         return node.kind === 317 /* JSDocParameterTag */;
11865     }
11866     ts.isJSDocParameterTag = isJSDocParameterTag;
11867     function isJSDocReturnTag(node) {
11868         return node.kind === 318 /* JSDocReturnTag */;
11869     }
11870     ts.isJSDocReturnTag = isJSDocReturnTag;
11871     function isJSDocTypeTag(node) {
11872         return node.kind === 320 /* JSDocTypeTag */;
11873     }
11874     ts.isJSDocTypeTag = isJSDocTypeTag;
11875     function isJSDocTemplateTag(node) {
11876         return node.kind === 321 /* JSDocTemplateTag */;
11877     }
11878     ts.isJSDocTemplateTag = isJSDocTemplateTag;
11879     function isJSDocTypedefTag(node) {
11880         return node.kind === 322 /* JSDocTypedefTag */;
11881     }
11882     ts.isJSDocTypedefTag = isJSDocTypedefTag;
11883     function isJSDocPropertyTag(node) {
11884         return node.kind === 323 /* JSDocPropertyTag */;
11885     }
11886     ts.isJSDocPropertyTag = isJSDocPropertyTag;
11887     function isJSDocPropertyLikeTag(node) {
11888         return node.kind === 323 /* JSDocPropertyTag */ || node.kind === 317 /* JSDocParameterTag */;
11889     }
11890     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
11891     function isJSDocTypeLiteral(node) {
11892         return node.kind === 304 /* JSDocTypeLiteral */;
11893     }
11894     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
11895     function isJSDocCallbackTag(node) {
11896         return node.kind === 315 /* JSDocCallbackTag */;
11897     }
11898     ts.isJSDocCallbackTag = isJSDocCallbackTag;
11899     function isJSDocSignature(node) {
11900         return node.kind === 305 /* JSDocSignature */;
11901     }
11902     ts.isJSDocSignature = isJSDocSignature;
11903     // #endregion
11904     // #region
11905     // Node tests
11906     //
11907     // All node tests in the following list should *not* reference parent pointers so that
11908     // they may be used with transformations.
11909     /* @internal */
11910     function isSyntaxList(n) {
11911         return n.kind === 324 /* SyntaxList */;
11912     }
11913     ts.isSyntaxList = isSyntaxList;
11914     /* @internal */
11915     function isNode(node) {
11916         return isNodeKind(node.kind);
11917     }
11918     ts.isNode = isNode;
11919     /* @internal */
11920     function isNodeKind(kind) {
11921         return kind >= 153 /* FirstNode */;
11922     }
11923     ts.isNodeKind = isNodeKind;
11924     /**
11925      * True if node is of some token syntax kind.
11926      * For example, this is true for an IfKeyword but not for an IfStatement.
11927      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
11928      */
11929     function isToken(n) {
11930         return n.kind >= 0 /* FirstToken */ && n.kind <= 152 /* LastToken */;
11931     }
11932     ts.isToken = isToken;
11933     // Node Arrays
11934     /* @internal */
11935     function isNodeArray(array) {
11936         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
11937     }
11938     ts.isNodeArray = isNodeArray;
11939     // Literals
11940     /* @internal */
11941     function isLiteralKind(kind) {
11942         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
11943     }
11944     ts.isLiteralKind = isLiteralKind;
11945     function isLiteralExpression(node) {
11946         return isLiteralKind(node.kind);
11947     }
11948     ts.isLiteralExpression = isLiteralExpression;
11949     // Pseudo-literals
11950     /* @internal */
11951     function isTemplateLiteralKind(kind) {
11952         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
11953     }
11954     ts.isTemplateLiteralKind = isTemplateLiteralKind;
11955     function isTemplateLiteralToken(node) {
11956         return isTemplateLiteralKind(node.kind);
11957     }
11958     ts.isTemplateLiteralToken = isTemplateLiteralToken;
11959     function isTemplateMiddleOrTemplateTail(node) {
11960         var kind = node.kind;
11961         return kind === 16 /* TemplateMiddle */
11962             || kind === 17 /* TemplateTail */;
11963     }
11964     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
11965     function isImportOrExportSpecifier(node) {
11966         return isImportSpecifier(node) || isExportSpecifier(node);
11967     }
11968     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
11969     function isTypeOnlyImportOrExportDeclaration(node) {
11970         switch (node.kind) {
11971             case 258 /* ImportSpecifier */:
11972             case 263 /* ExportSpecifier */:
11973                 return node.parent.parent.isTypeOnly;
11974             case 256 /* NamespaceImport */:
11975                 return node.parent.isTypeOnly;
11976             case 255 /* ImportClause */:
11977                 return node.isTypeOnly;
11978             default:
11979                 return false;
11980         }
11981     }
11982     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
11983     function isStringTextContainingNode(node) {
11984         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
11985     }
11986     ts.isStringTextContainingNode = isStringTextContainingNode;
11987     // Identifiers
11988     /* @internal */
11989     function isGeneratedIdentifier(node) {
11990         return isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
11991     }
11992     ts.isGeneratedIdentifier = isGeneratedIdentifier;
11993     // Private Identifiers
11994     /*@internal*/
11995     function isPrivateIdentifierPropertyDeclaration(node) {
11996         return isPropertyDeclaration(node) && isPrivateIdentifier(node.name);
11997     }
11998     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
11999     /*@internal*/
12000     function isPrivateIdentifierPropertyAccessExpression(node) {
12001         return isPropertyAccessExpression(node) && isPrivateIdentifier(node.name);
12002     }
12003     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12004     // Keywords
12005     /* @internal */
12006     function isModifierKind(token) {
12007         switch (token) {
12008             case 122 /* AbstractKeyword */:
12009             case 126 /* AsyncKeyword */:
12010             case 81 /* ConstKeyword */:
12011             case 130 /* DeclareKeyword */:
12012             case 84 /* DefaultKeyword */:
12013             case 89 /* ExportKeyword */:
12014             case 119 /* PublicKeyword */:
12015             case 117 /* PrivateKeyword */:
12016             case 118 /* ProtectedKeyword */:
12017             case 138 /* ReadonlyKeyword */:
12018             case 120 /* StaticKeyword */:
12019                 return true;
12020         }
12021         return false;
12022     }
12023     ts.isModifierKind = isModifierKind;
12024     /* @internal */
12025     function isParameterPropertyModifier(kind) {
12026         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12027     }
12028     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12029     /* @internal */
12030     function isClassMemberModifier(idToken) {
12031         return isParameterPropertyModifier(idToken) || idToken === 120 /* StaticKeyword */;
12032     }
12033     ts.isClassMemberModifier = isClassMemberModifier;
12034     function isModifier(node) {
12035         return isModifierKind(node.kind);
12036     }
12037     ts.isModifier = isModifier;
12038     function isEntityName(node) {
12039         var kind = node.kind;
12040         return kind === 153 /* QualifiedName */
12041             || kind === 75 /* Identifier */;
12042     }
12043     ts.isEntityName = isEntityName;
12044     function isPropertyName(node) {
12045         var kind = node.kind;
12046         return kind === 75 /* Identifier */
12047             || kind === 76 /* PrivateIdentifier */
12048             || kind === 10 /* StringLiteral */
12049             || kind === 8 /* NumericLiteral */
12050             || kind === 154 /* ComputedPropertyName */;
12051     }
12052     ts.isPropertyName = isPropertyName;
12053     function isBindingName(node) {
12054         var kind = node.kind;
12055         return kind === 75 /* Identifier */
12056             || kind === 189 /* ObjectBindingPattern */
12057             || kind === 190 /* ArrayBindingPattern */;
12058     }
12059     ts.isBindingName = isBindingName;
12060     // Functions
12061     function isFunctionLike(node) {
12062         return node && isFunctionLikeKind(node.kind);
12063     }
12064     ts.isFunctionLike = isFunctionLike;
12065     /* @internal */
12066     function isFunctionLikeDeclaration(node) {
12067         return node && isFunctionLikeDeclarationKind(node.kind);
12068     }
12069     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12070     function isFunctionLikeDeclarationKind(kind) {
12071         switch (kind) {
12072             case 244 /* FunctionDeclaration */:
12073             case 161 /* MethodDeclaration */:
12074             case 162 /* Constructor */:
12075             case 163 /* GetAccessor */:
12076             case 164 /* SetAccessor */:
12077             case 201 /* FunctionExpression */:
12078             case 202 /* ArrowFunction */:
12079                 return true;
12080             default:
12081                 return false;
12082         }
12083     }
12084     /* @internal */
12085     function isFunctionLikeKind(kind) {
12086         switch (kind) {
12087             case 160 /* MethodSignature */:
12088             case 165 /* CallSignature */:
12089             case 305 /* JSDocSignature */:
12090             case 166 /* ConstructSignature */:
12091             case 167 /* IndexSignature */:
12092             case 170 /* FunctionType */:
12093             case 300 /* JSDocFunctionType */:
12094             case 171 /* ConstructorType */:
12095                 return true;
12096             default:
12097                 return isFunctionLikeDeclarationKind(kind);
12098         }
12099     }
12100     ts.isFunctionLikeKind = isFunctionLikeKind;
12101     /* @internal */
12102     function isFunctionOrModuleBlock(node) {
12103         return isSourceFile(node) || isModuleBlock(node) || isBlock(node) && isFunctionLike(node.parent);
12104     }
12105     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12106     // Classes
12107     function isClassElement(node) {
12108         var kind = node.kind;
12109         return kind === 162 /* Constructor */
12110             || kind === 159 /* PropertyDeclaration */
12111             || kind === 161 /* MethodDeclaration */
12112             || kind === 163 /* GetAccessor */
12113             || kind === 164 /* SetAccessor */
12114             || kind === 167 /* IndexSignature */
12115             || kind === 222 /* SemicolonClassElement */;
12116     }
12117     ts.isClassElement = isClassElement;
12118     function isClassLike(node) {
12119         return node && (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */);
12120     }
12121     ts.isClassLike = isClassLike;
12122     function isAccessor(node) {
12123         return node && (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */);
12124     }
12125     ts.isAccessor = isAccessor;
12126     /* @internal */
12127     function isMethodOrAccessor(node) {
12128         switch (node.kind) {
12129             case 161 /* MethodDeclaration */:
12130             case 163 /* GetAccessor */:
12131             case 164 /* SetAccessor */:
12132                 return true;
12133             default:
12134                 return false;
12135         }
12136     }
12137     ts.isMethodOrAccessor = isMethodOrAccessor;
12138     // Type members
12139     function isTypeElement(node) {
12140         var kind = node.kind;
12141         return kind === 166 /* ConstructSignature */
12142             || kind === 165 /* CallSignature */
12143             || kind === 158 /* PropertySignature */
12144             || kind === 160 /* MethodSignature */
12145             || kind === 167 /* IndexSignature */;
12146     }
12147     ts.isTypeElement = isTypeElement;
12148     function isClassOrTypeElement(node) {
12149         return isTypeElement(node) || isClassElement(node);
12150     }
12151     ts.isClassOrTypeElement = isClassOrTypeElement;
12152     function isObjectLiteralElementLike(node) {
12153         var kind = node.kind;
12154         return kind === 281 /* PropertyAssignment */
12155             || kind === 282 /* ShorthandPropertyAssignment */
12156             || kind === 283 /* SpreadAssignment */
12157             || kind === 161 /* MethodDeclaration */
12158             || kind === 163 /* GetAccessor */
12159             || kind === 164 /* SetAccessor */;
12160     }
12161     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12162     // Type
12163     /**
12164      * Node test that determines whether a node is a valid type node.
12165      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12166      * of a TypeNode.
12167      */
12168     function isTypeNode(node) {
12169         return ts.isTypeNodeKind(node.kind);
12170     }
12171     ts.isTypeNode = isTypeNode;
12172     function isFunctionOrConstructorTypeNode(node) {
12173         switch (node.kind) {
12174             case 170 /* FunctionType */:
12175             case 171 /* ConstructorType */:
12176                 return true;
12177         }
12178         return false;
12179     }
12180     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12181     // Binding patterns
12182     /* @internal */
12183     function isBindingPattern(node) {
12184         if (node) {
12185             var kind = node.kind;
12186             return kind === 190 /* ArrayBindingPattern */
12187                 || kind === 189 /* ObjectBindingPattern */;
12188         }
12189         return false;
12190     }
12191     ts.isBindingPattern = isBindingPattern;
12192     /* @internal */
12193     function isAssignmentPattern(node) {
12194         var kind = node.kind;
12195         return kind === 192 /* ArrayLiteralExpression */
12196             || kind === 193 /* ObjectLiteralExpression */;
12197     }
12198     ts.isAssignmentPattern = isAssignmentPattern;
12199     /* @internal */
12200     function isArrayBindingElement(node) {
12201         var kind = node.kind;
12202         return kind === 191 /* BindingElement */
12203             || kind === 215 /* OmittedExpression */;
12204     }
12205     ts.isArrayBindingElement = isArrayBindingElement;
12206     /**
12207      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12208      */
12209     /* @internal */
12210     function isDeclarationBindingElement(bindingElement) {
12211         switch (bindingElement.kind) {
12212             case 242 /* VariableDeclaration */:
12213             case 156 /* Parameter */:
12214             case 191 /* BindingElement */:
12215                 return true;
12216         }
12217         return false;
12218     }
12219     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12220     /**
12221      * Determines whether a node is a BindingOrAssignmentPattern
12222      */
12223     /* @internal */
12224     function isBindingOrAssignmentPattern(node) {
12225         return isObjectBindingOrAssignmentPattern(node)
12226             || isArrayBindingOrAssignmentPattern(node);
12227     }
12228     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12229     /**
12230      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12231      */
12232     /* @internal */
12233     function isObjectBindingOrAssignmentPattern(node) {
12234         switch (node.kind) {
12235             case 189 /* ObjectBindingPattern */:
12236             case 193 /* ObjectLiteralExpression */:
12237                 return true;
12238         }
12239         return false;
12240     }
12241     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12242     /**
12243      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12244      */
12245     /* @internal */
12246     function isArrayBindingOrAssignmentPattern(node) {
12247         switch (node.kind) {
12248             case 190 /* ArrayBindingPattern */:
12249             case 192 /* ArrayLiteralExpression */:
12250                 return true;
12251         }
12252         return false;
12253     }
12254     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12255     /* @internal */
12256     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12257         var kind = node.kind;
12258         return kind === 194 /* PropertyAccessExpression */
12259             || kind === 153 /* QualifiedName */
12260             || kind === 188 /* ImportType */;
12261     }
12262     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12263     // Expression
12264     function isPropertyAccessOrQualifiedName(node) {
12265         var kind = node.kind;
12266         return kind === 194 /* PropertyAccessExpression */
12267             || kind === 153 /* QualifiedName */;
12268     }
12269     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12270     function isCallLikeExpression(node) {
12271         switch (node.kind) {
12272             case 268 /* JsxOpeningElement */:
12273             case 267 /* JsxSelfClosingElement */:
12274             case 196 /* CallExpression */:
12275             case 197 /* NewExpression */:
12276             case 198 /* TaggedTemplateExpression */:
12277             case 157 /* Decorator */:
12278                 return true;
12279             default:
12280                 return false;
12281         }
12282     }
12283     ts.isCallLikeExpression = isCallLikeExpression;
12284     function isCallOrNewExpression(node) {
12285         return node.kind === 196 /* CallExpression */ || node.kind === 197 /* NewExpression */;
12286     }
12287     ts.isCallOrNewExpression = isCallOrNewExpression;
12288     function isTemplateLiteral(node) {
12289         var kind = node.kind;
12290         return kind === 211 /* TemplateExpression */
12291             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12292     }
12293     ts.isTemplateLiteral = isTemplateLiteral;
12294     /* @internal */
12295     function isLeftHandSideExpression(node) {
12296         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12297     }
12298     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12299     function isLeftHandSideExpressionKind(kind) {
12300         switch (kind) {
12301             case 194 /* PropertyAccessExpression */:
12302             case 195 /* ElementAccessExpression */:
12303             case 197 /* NewExpression */:
12304             case 196 /* CallExpression */:
12305             case 266 /* JsxElement */:
12306             case 267 /* JsxSelfClosingElement */:
12307             case 270 /* JsxFragment */:
12308             case 198 /* TaggedTemplateExpression */:
12309             case 192 /* ArrayLiteralExpression */:
12310             case 200 /* ParenthesizedExpression */:
12311             case 193 /* ObjectLiteralExpression */:
12312             case 214 /* ClassExpression */:
12313             case 201 /* FunctionExpression */:
12314             case 75 /* Identifier */:
12315             case 13 /* RegularExpressionLiteral */:
12316             case 8 /* NumericLiteral */:
12317             case 9 /* BigIntLiteral */:
12318             case 10 /* StringLiteral */:
12319             case 14 /* NoSubstitutionTemplateLiteral */:
12320             case 211 /* TemplateExpression */:
12321             case 91 /* FalseKeyword */:
12322             case 100 /* NullKeyword */:
12323             case 104 /* ThisKeyword */:
12324             case 106 /* TrueKeyword */:
12325             case 102 /* SuperKeyword */:
12326             case 218 /* NonNullExpression */:
12327             case 219 /* MetaProperty */:
12328             case 96 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12329                 return true;
12330             default:
12331                 return false;
12332         }
12333     }
12334     /* @internal */
12335     function isUnaryExpression(node) {
12336         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12337     }
12338     ts.isUnaryExpression = isUnaryExpression;
12339     function isUnaryExpressionKind(kind) {
12340         switch (kind) {
12341             case 207 /* PrefixUnaryExpression */:
12342             case 208 /* PostfixUnaryExpression */:
12343             case 203 /* DeleteExpression */:
12344             case 204 /* TypeOfExpression */:
12345             case 205 /* VoidExpression */:
12346             case 206 /* AwaitExpression */:
12347             case 199 /* TypeAssertionExpression */:
12348                 return true;
12349             default:
12350                 return isLeftHandSideExpressionKind(kind);
12351         }
12352     }
12353     /* @internal */
12354     function isUnaryExpressionWithWrite(expr) {
12355         switch (expr.kind) {
12356             case 208 /* PostfixUnaryExpression */:
12357                 return true;
12358             case 207 /* PrefixUnaryExpression */:
12359                 return expr.operator === 45 /* PlusPlusToken */ ||
12360                     expr.operator === 46 /* MinusMinusToken */;
12361             default:
12362                 return false;
12363         }
12364     }
12365     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12366     /* @internal */
12367     /**
12368      * Determines whether a node is an expression based only on its kind.
12369      * Use `isExpressionNode` if not in transforms.
12370      */
12371     function isExpression(node) {
12372         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12373     }
12374     ts.isExpression = isExpression;
12375     function isExpressionKind(kind) {
12376         switch (kind) {
12377             case 210 /* ConditionalExpression */:
12378             case 212 /* YieldExpression */:
12379             case 202 /* ArrowFunction */:
12380             case 209 /* BinaryExpression */:
12381             case 213 /* SpreadElement */:
12382             case 217 /* AsExpression */:
12383             case 215 /* OmittedExpression */:
12384             case 327 /* CommaListExpression */:
12385             case 326 /* PartiallyEmittedExpression */:
12386                 return true;
12387             default:
12388                 return isUnaryExpressionKind(kind);
12389         }
12390     }
12391     function isAssertionExpression(node) {
12392         var kind = node.kind;
12393         return kind === 199 /* TypeAssertionExpression */
12394             || kind === 217 /* AsExpression */;
12395     }
12396     ts.isAssertionExpression = isAssertionExpression;
12397     /* @internal */
12398     function isPartiallyEmittedExpression(node) {
12399         return node.kind === 326 /* PartiallyEmittedExpression */;
12400     }
12401     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
12402     /* @internal */
12403     function isNotEmittedStatement(node) {
12404         return node.kind === 325 /* NotEmittedStatement */;
12405     }
12406     ts.isNotEmittedStatement = isNotEmittedStatement;
12407     /* @internal */
12408     function isSyntheticReference(node) {
12409         return node.kind === 330 /* SyntheticReferenceExpression */;
12410     }
12411     ts.isSyntheticReference = isSyntheticReference;
12412     /* @internal */
12413     function isNotEmittedOrPartiallyEmittedNode(node) {
12414         return isNotEmittedStatement(node)
12415             || isPartiallyEmittedExpression(node);
12416     }
12417     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12418     function isIterationStatement(node, lookInLabeledStatements) {
12419         switch (node.kind) {
12420             case 230 /* ForStatement */:
12421             case 231 /* ForInStatement */:
12422             case 232 /* ForOfStatement */:
12423             case 228 /* DoStatement */:
12424             case 229 /* WhileStatement */:
12425                 return true;
12426             case 238 /* LabeledStatement */:
12427                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12428         }
12429         return false;
12430     }
12431     ts.isIterationStatement = isIterationStatement;
12432     /* @internal */
12433     function isScopeMarker(node) {
12434         return isExportAssignment(node) || isExportDeclaration(node);
12435     }
12436     ts.isScopeMarker = isScopeMarker;
12437     /* @internal */
12438     function hasScopeMarker(statements) {
12439         return ts.some(statements, isScopeMarker);
12440     }
12441     ts.hasScopeMarker = hasScopeMarker;
12442     /* @internal */
12443     function needsScopeMarker(result) {
12444         return !ts.isAnyImportOrReExport(result) && !isExportAssignment(result) && !ts.hasModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12445     }
12446     ts.needsScopeMarker = needsScopeMarker;
12447     /* @internal */
12448     function isExternalModuleIndicator(result) {
12449         // Exported top-level member indicates moduleness
12450         return ts.isAnyImportOrReExport(result) || isExportAssignment(result) || ts.hasModifier(result, 1 /* Export */);
12451     }
12452     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12453     /* @internal */
12454     function isForInOrOfStatement(node) {
12455         return node.kind === 231 /* ForInStatement */ || node.kind === 232 /* ForOfStatement */;
12456     }
12457     ts.isForInOrOfStatement = isForInOrOfStatement;
12458     // Element
12459     /* @internal */
12460     function isConciseBody(node) {
12461         return isBlock(node)
12462             || isExpression(node);
12463     }
12464     ts.isConciseBody = isConciseBody;
12465     /* @internal */
12466     function isFunctionBody(node) {
12467         return isBlock(node);
12468     }
12469     ts.isFunctionBody = isFunctionBody;
12470     /* @internal */
12471     function isForInitializer(node) {
12472         return isVariableDeclarationList(node)
12473             || isExpression(node);
12474     }
12475     ts.isForInitializer = isForInitializer;
12476     /* @internal */
12477     function isModuleBody(node) {
12478         var kind = node.kind;
12479         return kind === 250 /* ModuleBlock */
12480             || kind === 249 /* ModuleDeclaration */
12481             || kind === 75 /* Identifier */;
12482     }
12483     ts.isModuleBody = isModuleBody;
12484     /* @internal */
12485     function isNamespaceBody(node) {
12486         var kind = node.kind;
12487         return kind === 250 /* ModuleBlock */
12488             || kind === 249 /* ModuleDeclaration */;
12489     }
12490     ts.isNamespaceBody = isNamespaceBody;
12491     /* @internal */
12492     function isJSDocNamespaceBody(node) {
12493         var kind = node.kind;
12494         return kind === 75 /* Identifier */
12495             || kind === 249 /* ModuleDeclaration */;
12496     }
12497     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12498     /* @internal */
12499     function isNamedImportBindings(node) {
12500         var kind = node.kind;
12501         return kind === 257 /* NamedImports */
12502             || kind === 256 /* NamespaceImport */;
12503     }
12504     ts.isNamedImportBindings = isNamedImportBindings;
12505     /* @internal */
12506     function isModuleOrEnumDeclaration(node) {
12507         return node.kind === 249 /* ModuleDeclaration */ || node.kind === 248 /* EnumDeclaration */;
12508     }
12509     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12510     function isDeclarationKind(kind) {
12511         return kind === 202 /* ArrowFunction */
12512             || kind === 191 /* BindingElement */
12513             || kind === 245 /* ClassDeclaration */
12514             || kind === 214 /* ClassExpression */
12515             || kind === 162 /* Constructor */
12516             || kind === 248 /* EnumDeclaration */
12517             || kind === 284 /* EnumMember */
12518             || kind === 263 /* ExportSpecifier */
12519             || kind === 244 /* FunctionDeclaration */
12520             || kind === 201 /* FunctionExpression */
12521             || kind === 163 /* GetAccessor */
12522             || kind === 255 /* ImportClause */
12523             || kind === 253 /* ImportEqualsDeclaration */
12524             || kind === 258 /* ImportSpecifier */
12525             || kind === 246 /* InterfaceDeclaration */
12526             || kind === 273 /* JsxAttribute */
12527             || kind === 161 /* MethodDeclaration */
12528             || kind === 160 /* MethodSignature */
12529             || kind === 249 /* ModuleDeclaration */
12530             || kind === 252 /* NamespaceExportDeclaration */
12531             || kind === 256 /* NamespaceImport */
12532             || kind === 262 /* NamespaceExport */
12533             || kind === 156 /* Parameter */
12534             || kind === 281 /* PropertyAssignment */
12535             || kind === 159 /* PropertyDeclaration */
12536             || kind === 158 /* PropertySignature */
12537             || kind === 164 /* SetAccessor */
12538             || kind === 282 /* ShorthandPropertyAssignment */
12539             || kind === 247 /* TypeAliasDeclaration */
12540             || kind === 155 /* TypeParameter */
12541             || kind === 242 /* VariableDeclaration */
12542             || kind === 322 /* JSDocTypedefTag */
12543             || kind === 315 /* JSDocCallbackTag */
12544             || kind === 323 /* JSDocPropertyTag */;
12545     }
12546     function isDeclarationStatementKind(kind) {
12547         return kind === 244 /* FunctionDeclaration */
12548             || kind === 264 /* MissingDeclaration */
12549             || kind === 245 /* ClassDeclaration */
12550             || kind === 246 /* InterfaceDeclaration */
12551             || kind === 247 /* TypeAliasDeclaration */
12552             || kind === 248 /* EnumDeclaration */
12553             || kind === 249 /* ModuleDeclaration */
12554             || kind === 254 /* ImportDeclaration */
12555             || kind === 253 /* ImportEqualsDeclaration */
12556             || kind === 260 /* ExportDeclaration */
12557             || kind === 259 /* ExportAssignment */
12558             || kind === 252 /* NamespaceExportDeclaration */;
12559     }
12560     function isStatementKindButNotDeclarationKind(kind) {
12561         return kind === 234 /* BreakStatement */
12562             || kind === 233 /* ContinueStatement */
12563             || kind === 241 /* DebuggerStatement */
12564             || kind === 228 /* DoStatement */
12565             || kind === 226 /* ExpressionStatement */
12566             || kind === 224 /* EmptyStatement */
12567             || kind === 231 /* ForInStatement */
12568             || kind === 232 /* ForOfStatement */
12569             || kind === 230 /* ForStatement */
12570             || kind === 227 /* IfStatement */
12571             || kind === 238 /* LabeledStatement */
12572             || kind === 235 /* ReturnStatement */
12573             || kind === 237 /* SwitchStatement */
12574             || kind === 239 /* ThrowStatement */
12575             || kind === 240 /* TryStatement */
12576             || kind === 225 /* VariableStatement */
12577             || kind === 229 /* WhileStatement */
12578             || kind === 236 /* WithStatement */
12579             || kind === 325 /* NotEmittedStatement */
12580             || kind === 329 /* EndOfDeclarationMarker */
12581             || kind === 328 /* MergeDeclarationMarker */;
12582     }
12583     /* @internal */
12584     function isDeclaration(node) {
12585         if (node.kind === 155 /* TypeParameter */) {
12586             return (node.parent && node.parent.kind !== 321 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12587         }
12588         return isDeclarationKind(node.kind);
12589     }
12590     ts.isDeclaration = isDeclaration;
12591     /* @internal */
12592     function isDeclarationStatement(node) {
12593         return isDeclarationStatementKind(node.kind);
12594     }
12595     ts.isDeclarationStatement = isDeclarationStatement;
12596     /**
12597      * Determines whether the node is a statement that is not also a declaration
12598      */
12599     /* @internal */
12600     function isStatementButNotDeclaration(node) {
12601         return isStatementKindButNotDeclarationKind(node.kind);
12602     }
12603     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12604     /* @internal */
12605     function isStatement(node) {
12606         var kind = node.kind;
12607         return isStatementKindButNotDeclarationKind(kind)
12608             || isDeclarationStatementKind(kind)
12609             || isBlockStatement(node);
12610     }
12611     ts.isStatement = isStatement;
12612     function isBlockStatement(node) {
12613         if (node.kind !== 223 /* Block */)
12614             return false;
12615         if (node.parent !== undefined) {
12616             if (node.parent.kind === 240 /* TryStatement */ || node.parent.kind === 280 /* CatchClause */) {
12617                 return false;
12618             }
12619         }
12620         return !ts.isFunctionBlock(node);
12621     }
12622     // Module references
12623     /* @internal */
12624     function isModuleReference(node) {
12625         var kind = node.kind;
12626         return kind === 265 /* ExternalModuleReference */
12627             || kind === 153 /* QualifiedName */
12628             || kind === 75 /* Identifier */;
12629     }
12630     ts.isModuleReference = isModuleReference;
12631     // JSX
12632     /* @internal */
12633     function isJsxTagNameExpression(node) {
12634         var kind = node.kind;
12635         return kind === 104 /* ThisKeyword */
12636             || kind === 75 /* Identifier */
12637             || kind === 194 /* PropertyAccessExpression */;
12638     }
12639     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12640     /* @internal */
12641     function isJsxChild(node) {
12642         var kind = node.kind;
12643         return kind === 266 /* JsxElement */
12644             || kind === 276 /* JsxExpression */
12645             || kind === 267 /* JsxSelfClosingElement */
12646             || kind === 11 /* JsxText */
12647             || kind === 270 /* JsxFragment */;
12648     }
12649     ts.isJsxChild = isJsxChild;
12650     /* @internal */
12651     function isJsxAttributeLike(node) {
12652         var kind = node.kind;
12653         return kind === 273 /* JsxAttribute */
12654             || kind === 275 /* JsxSpreadAttribute */;
12655     }
12656     ts.isJsxAttributeLike = isJsxAttributeLike;
12657     /* @internal */
12658     function isStringLiteralOrJsxExpression(node) {
12659         var kind = node.kind;
12660         return kind === 10 /* StringLiteral */
12661             || kind === 276 /* JsxExpression */;
12662     }
12663     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12664     function isJsxOpeningLikeElement(node) {
12665         var kind = node.kind;
12666         return kind === 268 /* JsxOpeningElement */
12667             || kind === 267 /* JsxSelfClosingElement */;
12668     }
12669     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12670     // Clauses
12671     function isCaseOrDefaultClause(node) {
12672         var kind = node.kind;
12673         return kind === 277 /* CaseClause */
12674             || kind === 278 /* DefaultClause */;
12675     }
12676     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12677     // JSDoc
12678     /** True if node is of some JSDoc syntax kind. */
12679     /* @internal */
12680     function isJSDocNode(node) {
12681         return node.kind >= 294 /* FirstJSDocNode */ && node.kind <= 323 /* LastJSDocNode */;
12682     }
12683     ts.isJSDocNode = isJSDocNode;
12684     /** True if node is of a kind that may contain comment text. */
12685     function isJSDocCommentContainingNode(node) {
12686         return node.kind === 303 /* JSDocComment */ || node.kind === 302 /* JSDocNamepathType */ || isJSDocTag(node) || isJSDocTypeLiteral(node) || isJSDocSignature(node);
12687     }
12688     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12689     // TODO: determine what this does before making it public.
12690     /* @internal */
12691     function isJSDocTag(node) {
12692         return node.kind >= 306 /* FirstJSDocTagNode */ && node.kind <= 323 /* LastJSDocTagNode */;
12693     }
12694     ts.isJSDocTag = isJSDocTag;
12695     function isSetAccessor(node) {
12696         return node.kind === 164 /* SetAccessor */;
12697     }
12698     ts.isSetAccessor = isSetAccessor;
12699     function isGetAccessor(node) {
12700         return node.kind === 163 /* GetAccessor */;
12701     }
12702     ts.isGetAccessor = isGetAccessor;
12703     /** True if has jsdoc nodes attached to it. */
12704     /* @internal */
12705     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
12706     function hasJSDocNodes(node) {
12707         var jsDoc = node.jsDoc;
12708         return !!jsDoc && jsDoc.length > 0;
12709     }
12710     ts.hasJSDocNodes = hasJSDocNodes;
12711     /** True if has type node attached to it. */
12712     /* @internal */
12713     function hasType(node) {
12714         return !!node.type;
12715     }
12716     ts.hasType = hasType;
12717     /** True if has initializer node attached to it. */
12718     /* @internal */
12719     function hasInitializer(node) {
12720         return !!node.initializer;
12721     }
12722     ts.hasInitializer = hasInitializer;
12723     /** True if has initializer node attached to it. */
12724     function hasOnlyExpressionInitializer(node) {
12725         switch (node.kind) {
12726             case 242 /* VariableDeclaration */:
12727             case 156 /* Parameter */:
12728             case 191 /* BindingElement */:
12729             case 158 /* PropertySignature */:
12730             case 159 /* PropertyDeclaration */:
12731             case 281 /* PropertyAssignment */:
12732             case 284 /* EnumMember */:
12733                 return true;
12734             default:
12735                 return false;
12736         }
12737     }
12738     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
12739     function isObjectLiteralElement(node) {
12740         return node.kind === 273 /* JsxAttribute */ || node.kind === 275 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
12741     }
12742     ts.isObjectLiteralElement = isObjectLiteralElement;
12743     /* @internal */
12744     function isTypeReferenceType(node) {
12745         return node.kind === 169 /* TypeReference */ || node.kind === 216 /* ExpressionWithTypeArguments */;
12746     }
12747     ts.isTypeReferenceType = isTypeReferenceType;
12748     var MAX_SMI_X86 = 1073741823;
12749     /* @internal */
12750     function guessIndentation(lines) {
12751         var indentation = MAX_SMI_X86;
12752         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
12753             var line = lines_1[_i];
12754             if (!line.length) {
12755                 continue;
12756             }
12757             var i = 0;
12758             for (; i < line.length && i < indentation; i++) {
12759                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
12760                     break;
12761                 }
12762             }
12763             if (i < indentation) {
12764                 indentation = i;
12765             }
12766             if (indentation === 0) {
12767                 return 0;
12768             }
12769         }
12770         return indentation === MAX_SMI_X86 ? undefined : indentation;
12771     }
12772     ts.guessIndentation = guessIndentation;
12773     function isStringLiteralLike(node) {
12774         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
12775     }
12776     ts.isStringLiteralLike = isStringLiteralLike;
12777     // #endregion
12778 })(ts || (ts = {}));
12779 /* @internal */
12780 var ts;
12781 (function (ts) {
12782     ts.resolvingEmptyArray = [];
12783     ts.emptyMap = ts.createMap();
12784     ts.emptyUnderscoreEscapedMap = ts.emptyMap;
12785     ts.externalHelpersModuleNameText = "tslib";
12786     ts.defaultMaximumTruncationLength = 160;
12787     ts.noTruncationMaximumTruncationLength = 1000000;
12788     function getDeclarationOfKind(symbol, kind) {
12789         var declarations = symbol.declarations;
12790         if (declarations) {
12791             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
12792                 var declaration = declarations_1[_i];
12793                 if (declaration.kind === kind) {
12794                     return declaration;
12795                 }
12796             }
12797         }
12798         return undefined;
12799     }
12800     ts.getDeclarationOfKind = getDeclarationOfKind;
12801     /** Create a new escaped identifier map. */
12802     function createUnderscoreEscapedMap() {
12803         return new ts.Map();
12804     }
12805     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
12806     function hasEntries(map) {
12807         return !!map && !!map.size;
12808     }
12809     ts.hasEntries = hasEntries;
12810     function createSymbolTable(symbols) {
12811         var result = ts.createMap();
12812         if (symbols) {
12813             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
12814                 var symbol = symbols_1[_i];
12815                 result.set(symbol.escapedName, symbol);
12816             }
12817         }
12818         return result;
12819     }
12820     ts.createSymbolTable = createSymbolTable;
12821     function isTransientSymbol(symbol) {
12822         return (symbol.flags & 33554432 /* Transient */) !== 0;
12823     }
12824     ts.isTransientSymbol = isTransientSymbol;
12825     var stringWriter = createSingleLineStringWriter();
12826     function createSingleLineStringWriter() {
12827         var str = "";
12828         var writeText = function (text) { return str += text; };
12829         return {
12830             getText: function () { return str; },
12831             write: writeText,
12832             rawWrite: writeText,
12833             writeKeyword: writeText,
12834             writeOperator: writeText,
12835             writePunctuation: writeText,
12836             writeSpace: writeText,
12837             writeStringLiteral: writeText,
12838             writeLiteral: writeText,
12839             writeParameter: writeText,
12840             writeProperty: writeText,
12841             writeSymbol: function (s, _) { return writeText(s); },
12842             writeTrailingSemicolon: writeText,
12843             writeComment: writeText,
12844             getTextPos: function () { return str.length; },
12845             getLine: function () { return 0; },
12846             getColumn: function () { return 0; },
12847             getIndent: function () { return 0; },
12848             isAtStartOfLine: function () { return false; },
12849             hasTrailingComment: function () { return false; },
12850             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
12851             // Completely ignore indentation for string writers.  And map newlines to
12852             // a single space.
12853             writeLine: function () { return str += " "; },
12854             increaseIndent: ts.noop,
12855             decreaseIndent: ts.noop,
12856             clear: function () { return str = ""; },
12857             trackSymbol: ts.noop,
12858             reportInaccessibleThisError: ts.noop,
12859             reportInaccessibleUniqueSymbolError: ts.noop,
12860             reportPrivateInBaseOfClassExpression: ts.noop,
12861         };
12862     }
12863     function changesAffectModuleResolution(oldOptions, newOptions) {
12864         return oldOptions.configFilePath !== newOptions.configFilePath ||
12865             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
12866     }
12867     ts.changesAffectModuleResolution = changesAffectModuleResolution;
12868     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
12869         return ts.moduleResolutionOptionDeclarations.some(function (o) {
12870             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
12871         });
12872     }
12873     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
12874     function findAncestor(node, callback) {
12875         while (node) {
12876             var result = callback(node);
12877             if (result === "quit") {
12878                 return undefined;
12879             }
12880             else if (result) {
12881                 return node;
12882             }
12883             node = node.parent;
12884         }
12885         return undefined;
12886     }
12887     ts.findAncestor = findAncestor;
12888     function forEachAncestor(node, callback) {
12889         while (true) {
12890             var res = callback(node);
12891             if (res === "quit")
12892                 return undefined;
12893             if (res !== undefined)
12894                 return res;
12895             if (ts.isSourceFile(node))
12896                 return undefined;
12897             node = node.parent;
12898         }
12899     }
12900     ts.forEachAncestor = forEachAncestor;
12901     function forEachEntry(map, callback) {
12902         var iterator = map.entries();
12903         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12904             var _a = iterResult.value, key = _a[0], value = _a[1];
12905             var result = callback(value, key);
12906             if (result) {
12907                 return result;
12908             }
12909         }
12910         return undefined;
12911     }
12912     ts.forEachEntry = forEachEntry;
12913     function forEachKey(map, callback) {
12914         var iterator = map.keys();
12915         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
12916             var result = callback(iterResult.value);
12917             if (result) {
12918                 return result;
12919             }
12920         }
12921         return undefined;
12922     }
12923     ts.forEachKey = forEachKey;
12924     function copyEntries(source, target) {
12925         source.forEach(function (value, key) {
12926             target.set(key, value);
12927         });
12928     }
12929     ts.copyEntries = copyEntries;
12930     function arrayToSet(array, makeKey) {
12931         return ts.arrayToMap(array, makeKey || (function (s) { return s; }), ts.returnTrue);
12932     }
12933     ts.arrayToSet = arrayToSet;
12934     function cloneMap(map) {
12935         var clone = ts.createMap();
12936         copyEntries(map, clone);
12937         return clone;
12938     }
12939     ts.cloneMap = cloneMap;
12940     function usingSingleLineStringWriter(action) {
12941         var oldString = stringWriter.getText();
12942         try {
12943             action(stringWriter);
12944             return stringWriter.getText();
12945         }
12946         finally {
12947             stringWriter.clear();
12948             stringWriter.writeKeyword(oldString);
12949         }
12950     }
12951     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
12952     function getFullWidth(node) {
12953         return node.end - node.pos;
12954     }
12955     ts.getFullWidth = getFullWidth;
12956     function getResolvedModule(sourceFile, moduleNameText) {
12957         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
12958     }
12959     ts.getResolvedModule = getResolvedModule;
12960     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
12961         if (!sourceFile.resolvedModules) {
12962             sourceFile.resolvedModules = ts.createMap();
12963         }
12964         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
12965     }
12966     ts.setResolvedModule = setResolvedModule;
12967     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
12968         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
12969             sourceFile.resolvedTypeReferenceDirectiveNames = ts.createMap();
12970         }
12971         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
12972     }
12973     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
12974     function projectReferenceIsEqualTo(oldRef, newRef) {
12975         return oldRef.path === newRef.path &&
12976             !oldRef.prepend === !newRef.prepend &&
12977             !oldRef.circular === !newRef.circular;
12978     }
12979     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
12980     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
12981         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
12982             oldResolution.extension === newResolution.extension &&
12983             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
12984             oldResolution.originalPath === newResolution.originalPath &&
12985             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
12986     }
12987     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
12988     function packageIdIsEqual(a, b) {
12989         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
12990     }
12991     function packageIdToString(_a) {
12992         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
12993         var fullName = subModuleName ? name + "/" + subModuleName : name;
12994         return fullName + "@" + version;
12995     }
12996     ts.packageIdToString = packageIdToString;
12997     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
12998         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
12999     }
13000     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13001     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13002         ts.Debug.assert(names.length === newResolutions.length);
13003         for (var i = 0; i < names.length; i++) {
13004             var newResolution = newResolutions[i];
13005             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13006             var changed = oldResolution
13007                 ? !newResolution || !comparer(oldResolution, newResolution)
13008                 : newResolution;
13009             if (changed) {
13010                 return true;
13011             }
13012         }
13013         return false;
13014     }
13015     ts.hasChangesInResolutions = hasChangesInResolutions;
13016     // Returns true if this node contains a parse error anywhere underneath it.
13017     function containsParseError(node) {
13018         aggregateChildData(node);
13019         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13020     }
13021     ts.containsParseError = containsParseError;
13022     function aggregateChildData(node) {
13023         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13024             // A node is considered to contain a parse error if:
13025             //  a) the parser explicitly marked that it had an error
13026             //  b) any of it's children reported that it had an error.
13027             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13028                 ts.forEachChild(node, containsParseError);
13029             // If so, mark ourselves accordingly.
13030             if (thisNodeOrAnySubNodesHasError) {
13031                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13032             }
13033             // Also mark that we've propagated the child information to this node.  This way we can
13034             // always consult the bit directly on this node without needing to check its children
13035             // again.
13036             node.flags |= 524288 /* HasAggregatedChildData */;
13037         }
13038     }
13039     function getSourceFileOfNode(node) {
13040         while (node && node.kind !== 290 /* SourceFile */) {
13041             node = node.parent;
13042         }
13043         return node;
13044     }
13045     ts.getSourceFileOfNode = getSourceFileOfNode;
13046     function isStatementWithLocals(node) {
13047         switch (node.kind) {
13048             case 223 /* Block */:
13049             case 251 /* CaseBlock */:
13050             case 230 /* ForStatement */:
13051             case 231 /* ForInStatement */:
13052             case 232 /* ForOfStatement */:
13053                 return true;
13054         }
13055         return false;
13056     }
13057     ts.isStatementWithLocals = isStatementWithLocals;
13058     function getStartPositionOfLine(line, sourceFile) {
13059         ts.Debug.assert(line >= 0);
13060         return ts.getLineStarts(sourceFile)[line];
13061     }
13062     ts.getStartPositionOfLine = getStartPositionOfLine;
13063     // This is a useful function for debugging purposes.
13064     function nodePosToString(node) {
13065         var file = getSourceFileOfNode(node);
13066         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13067         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13068     }
13069     ts.nodePosToString = nodePosToString;
13070     function getEndLinePosition(line, sourceFile) {
13071         ts.Debug.assert(line >= 0);
13072         var lineStarts = ts.getLineStarts(sourceFile);
13073         var lineIndex = line;
13074         var sourceText = sourceFile.text;
13075         if (lineIndex + 1 === lineStarts.length) {
13076             // last line - return EOF
13077             return sourceText.length - 1;
13078         }
13079         else {
13080             // current line start
13081             var start = lineStarts[lineIndex];
13082             // take the start position of the next line - 1 = it should be some line break
13083             var pos = lineStarts[lineIndex + 1] - 1;
13084             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13085             // walk backwards skipping line breaks, stop the the beginning of current line.
13086             // i.e:
13087             // <some text>
13088             // $ <- end of line for this position should match the start position
13089             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13090                 pos--;
13091             }
13092             return pos;
13093         }
13094     }
13095     ts.getEndLinePosition = getEndLinePosition;
13096     /**
13097      * Returns a value indicating whether a name is unique globally or within the current file.
13098      * 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`.
13099      */
13100     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13101         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13102     }
13103     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13104     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13105     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13106     // in the tree), it is definitely missing. However, a node may be defined, but still be
13107     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13108     // get anything in the source code that it expects at that location. For example:
13109     //
13110     //          let a: ;
13111     //
13112     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13113     // code). So the parser will attempt to parse out a type, and will create an actual node.
13114     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13115     // contained within it.
13116     function nodeIsMissing(node) {
13117         if (node === undefined) {
13118             return true;
13119         }
13120         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13121     }
13122     ts.nodeIsMissing = nodeIsMissing;
13123     function nodeIsPresent(node) {
13124         return !nodeIsMissing(node);
13125     }
13126     ts.nodeIsPresent = nodeIsPresent;
13127     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13128         if (from === undefined || from.length === 0)
13129             return to;
13130         var statementIndex = 0;
13131         // skip all prologue directives to insert at the correct position
13132         for (; statementIndex < to.length; ++statementIndex) {
13133             if (!isPrologueDirective(to[statementIndex])) {
13134                 break;
13135             }
13136         }
13137         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13138         return to;
13139     }
13140     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13141         if (statement === undefined)
13142             return to;
13143         var statementIndex = 0;
13144         // skip all prologue directives to insert at the correct position
13145         for (; statementIndex < to.length; ++statementIndex) {
13146             if (!isPrologueDirective(to[statementIndex])) {
13147                 break;
13148             }
13149         }
13150         to.splice(statementIndex, 0, statement);
13151         return to;
13152     }
13153     function isAnyPrologueDirective(node) {
13154         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13155     }
13156     /**
13157      * Prepends statements to an array while taking care of prologue directives.
13158      */
13159     function insertStatementsAfterStandardPrologue(to, from) {
13160         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13161     }
13162     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13163     function insertStatementsAfterCustomPrologue(to, from) {
13164         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13165     }
13166     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13167     /**
13168      * Prepends statements to an array while taking care of prologue directives.
13169      */
13170     function insertStatementAfterStandardPrologue(to, statement) {
13171         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13172     }
13173     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13174     function insertStatementAfterCustomPrologue(to, statement) {
13175         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13176     }
13177     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13178     /**
13179      * Determine if the given comment is a triple-slash
13180      *
13181      * @return true if the comment is a triple-slash comment else false
13182      */
13183     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13184         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13185         // so that we don't end up computing comment string and doing match for all // comments
13186         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13187             commentPos + 2 < commentEnd &&
13188             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13189             var textSubStr = text.substring(commentPos, commentEnd);
13190             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13191                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13192                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13193                 textSubStr.match(defaultLibReferenceRegEx) ?
13194                 true : false;
13195         }
13196         return false;
13197     }
13198     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13199     function isPinnedComment(text, start) {
13200         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13201             text.charCodeAt(start + 2) === 33 /* exclamation */;
13202     }
13203     ts.isPinnedComment = isPinnedComment;
13204     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13205         var directivesByLine = ts.createMapFromEntries(commentDirectives.map(function (commentDirective) { return ([
13206             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13207             commentDirective,
13208         ]); }));
13209         var usedLines = ts.createMap();
13210         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13211         function getUnusedExpectations() {
13212             return ts.arrayFrom(directivesByLine.entries())
13213                 .filter(function (_a) {
13214                 var line = _a[0], directive = _a[1];
13215                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13216             })
13217                 .map(function (_a) {
13218                 var _ = _a[0], directive = _a[1];
13219                 return directive;
13220             });
13221         }
13222         function markUsed(line) {
13223             if (!directivesByLine.has("" + line)) {
13224                 return false;
13225             }
13226             usedLines.set("" + line, true);
13227             return true;
13228         }
13229     }
13230     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13231     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13232         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13233         // want to skip trivia because this will launch us forward to the next token.
13234         if (nodeIsMissing(node)) {
13235             return node.pos;
13236         }
13237         if (ts.isJSDocNode(node)) {
13238             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13239         }
13240         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13241             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13242         }
13243         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13244         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13245         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13246         // first child to determine the actual position of its first token.
13247         if (node.kind === 324 /* SyntaxList */ && node._children.length > 0) {
13248             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13249         }
13250         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13251     }
13252     ts.getTokenPosOfNode = getTokenPosOfNode;
13253     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13254         if (nodeIsMissing(node) || !node.decorators) {
13255             return getTokenPosOfNode(node, sourceFile);
13256         }
13257         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13258     }
13259     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13260     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13261         if (includeTrivia === void 0) { includeTrivia = false; }
13262         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13263     }
13264     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13265     function isJSDocTypeExpressionOrChild(node) {
13266         return !!findAncestor(node, ts.isJSDocTypeExpression);
13267     }
13268     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13269         if (includeTrivia === void 0) { includeTrivia = false; }
13270         if (nodeIsMissing(node)) {
13271             return "";
13272         }
13273         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13274         if (isJSDocTypeExpressionOrChild(node)) {
13275             // strip space + asterisk at line start
13276             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13277         }
13278         return text;
13279     }
13280     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13281     function getTextOfNode(node, includeTrivia) {
13282         if (includeTrivia === void 0) { includeTrivia = false; }
13283         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13284     }
13285     ts.getTextOfNode = getTextOfNode;
13286     function getPos(range) {
13287         return range.pos;
13288     }
13289     /**
13290      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13291      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13292      */
13293     function indexOfNode(nodeArray, node) {
13294         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13295     }
13296     ts.indexOfNode = indexOfNode;
13297     /**
13298      * Gets flags that control emit behavior of a node.
13299      */
13300     function getEmitFlags(node) {
13301         var emitNode = node.emitNode;
13302         return emitNode && emitNode.flags || 0;
13303     }
13304     ts.getEmitFlags = getEmitFlags;
13305     function getLiteralText(node, sourceFile, neverAsciiEscape, jsxAttributeEscape) {
13306         // If we don't need to downlevel and we can reach the original source text using
13307         // the node's parent reference, then simply get the text as it was originally written.
13308         if (!nodeIsSynthesized(node) && node.parent && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13309             ts.isBigIntLiteral(node))) {
13310             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13311         }
13312         // If we can't reach the original source text, use the canonical form if it's a number,
13313         // or a (possibly escaped) quoted form of the original text if it's string-like.
13314         switch (node.kind) {
13315             case 10 /* StringLiteral */: {
13316                 var escapeText = jsxAttributeEscape ? escapeJsxAttributeString :
13317                     neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13318                         escapeNonAsciiString;
13319                 if (node.singleQuote) {
13320                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13321                 }
13322                 else {
13323                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13324                 }
13325             }
13326             case 14 /* NoSubstitutionTemplateLiteral */:
13327             case 15 /* TemplateHead */:
13328             case 16 /* TemplateMiddle */:
13329             case 17 /* TemplateTail */: {
13330                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13331                 // had to include a backslash: `not \${a} substitution`.
13332                 var escapeText = neverAsciiEscape || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13333                     escapeNonAsciiString;
13334                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13335                 switch (node.kind) {
13336                     case 14 /* NoSubstitutionTemplateLiteral */:
13337                         return "`" + rawText + "`";
13338                     case 15 /* TemplateHead */:
13339                         return "`" + rawText + "${";
13340                     case 16 /* TemplateMiddle */:
13341                         return "}" + rawText + "${";
13342                     case 17 /* TemplateTail */:
13343                         return "}" + rawText + "`";
13344                 }
13345                 break;
13346             }
13347             case 8 /* NumericLiteral */:
13348             case 9 /* BigIntLiteral */:
13349             case 13 /* RegularExpressionLiteral */:
13350                 return node.text;
13351         }
13352         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13353     }
13354     ts.getLiteralText = getLiteralText;
13355     function getTextOfConstantValue(value) {
13356         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13357     }
13358     ts.getTextOfConstantValue = getTextOfConstantValue;
13359     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13360     // all non-alphanumeric characters with underscores
13361     function makeIdentifierFromModuleName(moduleName) {
13362         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13363     }
13364     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13365     function isBlockOrCatchScoped(declaration) {
13366         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13367             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13368     }
13369     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13370     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13371         var node = getRootDeclaration(declaration);
13372         return node.kind === 242 /* VariableDeclaration */ && node.parent.kind === 280 /* CatchClause */;
13373     }
13374     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13375     function isAmbientModule(node) {
13376         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13377     }
13378     ts.isAmbientModule = isAmbientModule;
13379     function isModuleWithStringLiteralName(node) {
13380         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13381     }
13382     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13383     function isNonGlobalAmbientModule(node) {
13384         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13385     }
13386     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13387     /**
13388      * An effective module (namespace) declaration is either
13389      * 1. An actual declaration: namespace X { ... }
13390      * 2. A Javascript declaration, which is:
13391      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13392      */
13393     function isEffectiveModuleDeclaration(node) {
13394         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13395     }
13396     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13397     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13398     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13399         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13400     }
13401     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13402     function isShorthandAmbientModule(node) {
13403         // The only kind of module that can be missing a body is a shorthand ambient module.
13404         return node && node.kind === 249 /* ModuleDeclaration */ && (!node.body);
13405     }
13406     function isBlockScopedContainerTopLevel(node) {
13407         return node.kind === 290 /* SourceFile */ ||
13408             node.kind === 249 /* ModuleDeclaration */ ||
13409             ts.isFunctionLike(node);
13410     }
13411     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13412     function isGlobalScopeAugmentation(module) {
13413         return !!(module.flags & 1024 /* GlobalAugmentation */);
13414     }
13415     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13416     function isExternalModuleAugmentation(node) {
13417         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13418     }
13419     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13420     function isModuleAugmentationExternal(node) {
13421         // external module augmentation is a ambient module declaration that is either:
13422         // - defined in the top level scope and source file is an external module
13423         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13424         switch (node.parent.kind) {
13425             case 290 /* SourceFile */:
13426                 return ts.isExternalModule(node.parent);
13427             case 250 /* ModuleBlock */:
13428                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13429         }
13430         return false;
13431     }
13432     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13433     function getNonAugmentationDeclaration(symbol) {
13434         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13435     }
13436     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13437     function isEffectiveExternalModule(node, compilerOptions) {
13438         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13439     }
13440     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13441     /**
13442      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13443      */
13444     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13445         // We can only verify strict mode for JS/TS files
13446         switch (node.scriptKind) {
13447             case 1 /* JS */:
13448             case 3 /* TS */:
13449             case 2 /* JSX */:
13450             case 4 /* TSX */:
13451                 break;
13452             default:
13453                 return false;
13454         }
13455         // Strict mode does not matter for declaration files.
13456         if (node.isDeclarationFile) {
13457             return false;
13458         }
13459         // If `alwaysStrict` is set, then treat the file as strict.
13460         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13461             return true;
13462         }
13463         // Starting with a "use strict" directive indicates the file is strict.
13464         if (ts.startsWithUseStrict(node.statements)) {
13465             return true;
13466         }
13467         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13468             // ECMAScript Modules are always strict.
13469             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13470                 return true;
13471             }
13472             // Other modules are strict unless otherwise specified.
13473             return !compilerOptions.noImplicitUseStrict;
13474         }
13475         return false;
13476     }
13477     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13478     function isBlockScope(node, parentNode) {
13479         switch (node.kind) {
13480             case 290 /* SourceFile */:
13481             case 251 /* CaseBlock */:
13482             case 280 /* CatchClause */:
13483             case 249 /* ModuleDeclaration */:
13484             case 230 /* ForStatement */:
13485             case 231 /* ForInStatement */:
13486             case 232 /* ForOfStatement */:
13487             case 162 /* Constructor */:
13488             case 161 /* MethodDeclaration */:
13489             case 163 /* GetAccessor */:
13490             case 164 /* SetAccessor */:
13491             case 244 /* FunctionDeclaration */:
13492             case 201 /* FunctionExpression */:
13493             case 202 /* ArrowFunction */:
13494                 return true;
13495             case 223 /* Block */:
13496                 // function block is not considered block-scope container
13497                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13498                 return !ts.isFunctionLike(parentNode);
13499         }
13500         return false;
13501     }
13502     ts.isBlockScope = isBlockScope;
13503     function isDeclarationWithTypeParameters(node) {
13504         switch (node.kind) {
13505             case 315 /* JSDocCallbackTag */:
13506             case 322 /* JSDocTypedefTag */:
13507             case 305 /* JSDocSignature */:
13508                 return true;
13509             default:
13510                 ts.assertType(node);
13511                 return isDeclarationWithTypeParameterChildren(node);
13512         }
13513     }
13514     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13515     function isDeclarationWithTypeParameterChildren(node) {
13516         switch (node.kind) {
13517             case 165 /* CallSignature */:
13518             case 166 /* ConstructSignature */:
13519             case 160 /* MethodSignature */:
13520             case 167 /* IndexSignature */:
13521             case 170 /* FunctionType */:
13522             case 171 /* ConstructorType */:
13523             case 300 /* JSDocFunctionType */:
13524             case 245 /* ClassDeclaration */:
13525             case 214 /* ClassExpression */:
13526             case 246 /* InterfaceDeclaration */:
13527             case 247 /* TypeAliasDeclaration */:
13528             case 321 /* JSDocTemplateTag */:
13529             case 244 /* FunctionDeclaration */:
13530             case 161 /* MethodDeclaration */:
13531             case 162 /* Constructor */:
13532             case 163 /* GetAccessor */:
13533             case 164 /* SetAccessor */:
13534             case 201 /* FunctionExpression */:
13535             case 202 /* ArrowFunction */:
13536                 return true;
13537             default:
13538                 ts.assertType(node);
13539                 return false;
13540         }
13541     }
13542     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13543     function isAnyImportSyntax(node) {
13544         switch (node.kind) {
13545             case 254 /* ImportDeclaration */:
13546             case 253 /* ImportEqualsDeclaration */:
13547                 return true;
13548             default:
13549                 return false;
13550         }
13551     }
13552     ts.isAnyImportSyntax = isAnyImportSyntax;
13553     function isLateVisibilityPaintedStatement(node) {
13554         switch (node.kind) {
13555             case 254 /* ImportDeclaration */:
13556             case 253 /* ImportEqualsDeclaration */:
13557             case 225 /* VariableStatement */:
13558             case 245 /* ClassDeclaration */:
13559             case 244 /* FunctionDeclaration */:
13560             case 249 /* ModuleDeclaration */:
13561             case 247 /* TypeAliasDeclaration */:
13562             case 246 /* InterfaceDeclaration */:
13563             case 248 /* EnumDeclaration */:
13564                 return true;
13565             default:
13566                 return false;
13567         }
13568     }
13569     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13570     function isAnyImportOrReExport(node) {
13571         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13572     }
13573     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13574     // Gets the nearest enclosing block scope container that has the provided node
13575     // as a descendant, that is not the provided node.
13576     function getEnclosingBlockScopeContainer(node) {
13577         return findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13578     }
13579     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13580     // Return display name of an identifier
13581     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13582     // text of the expression in the computed property.
13583     function declarationNameToString(name) {
13584         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13585     }
13586     ts.declarationNameToString = declarationNameToString;
13587     function getNameFromIndexInfo(info) {
13588         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13589     }
13590     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13591     function isComputedNonLiteralName(name) {
13592         return name.kind === 154 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13593     }
13594     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13595     function getTextOfPropertyName(name) {
13596         switch (name.kind) {
13597             case 75 /* Identifier */:
13598             case 76 /* PrivateIdentifier */:
13599                 return name.escapedText;
13600             case 10 /* StringLiteral */:
13601             case 8 /* NumericLiteral */:
13602             case 14 /* NoSubstitutionTemplateLiteral */:
13603                 return ts.escapeLeadingUnderscores(name.text);
13604             case 154 /* ComputedPropertyName */:
13605                 if (isStringOrNumericLiteralLike(name.expression))
13606                     return ts.escapeLeadingUnderscores(name.expression.text);
13607                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13608             default:
13609                 return ts.Debug.assertNever(name);
13610         }
13611     }
13612     ts.getTextOfPropertyName = getTextOfPropertyName;
13613     function entityNameToString(name) {
13614         switch (name.kind) {
13615             case 104 /* ThisKeyword */:
13616                 return "this";
13617             case 76 /* PrivateIdentifier */:
13618             case 75 /* Identifier */:
13619                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13620             case 153 /* QualifiedName */:
13621                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13622             case 194 /* PropertyAccessExpression */:
13623                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13624                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13625                 }
13626                 else {
13627                     return ts.Debug.assertNever(name.name);
13628                 }
13629             default:
13630                 return ts.Debug.assertNever(name);
13631         }
13632     }
13633     ts.entityNameToString = entityNameToString;
13634     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
13635         var sourceFile = getSourceFileOfNode(node);
13636         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
13637     }
13638     ts.createDiagnosticForNode = createDiagnosticForNode;
13639     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
13640         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
13641         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
13642     }
13643     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
13644     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
13645         var span = getErrorSpanForNode(sourceFile, node);
13646         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
13647     }
13648     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
13649     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
13650         var sourceFile = getSourceFileOfNode(node);
13651         var span = getErrorSpanForNode(sourceFile, node);
13652         return {
13653             file: sourceFile,
13654             start: span.start,
13655             length: span.length,
13656             code: messageChain.code,
13657             category: messageChain.category,
13658             messageText: messageChain.next ? messageChain : messageChain.messageText,
13659             relatedInformation: relatedInformation
13660         };
13661     }
13662     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
13663     function createDiagnosticForRange(sourceFile, range, message) {
13664         return {
13665             file: sourceFile,
13666             start: range.pos,
13667             length: range.end - range.pos,
13668             code: message.code,
13669             category: message.category,
13670             messageText: message.message,
13671         };
13672     }
13673     ts.createDiagnosticForRange = createDiagnosticForRange;
13674     function getSpanOfTokenAtPosition(sourceFile, pos) {
13675         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
13676         scanner.scan();
13677         var start = scanner.getTokenPos();
13678         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
13679     }
13680     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
13681     function getErrorSpanForArrowFunction(sourceFile, node) {
13682         var pos = ts.skipTrivia(sourceFile.text, node.pos);
13683         if (node.body && node.body.kind === 223 /* Block */) {
13684             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
13685             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
13686             if (startLine < endLine) {
13687                 // The arrow function spans multiple lines,
13688                 // make the error span be the first line, inclusive.
13689                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
13690             }
13691         }
13692         return ts.createTextSpanFromBounds(pos, node.end);
13693     }
13694     function getErrorSpanForNode(sourceFile, node) {
13695         var errorNode = node;
13696         switch (node.kind) {
13697             case 290 /* SourceFile */:
13698                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
13699                 if (pos_1 === sourceFile.text.length) {
13700                     // file is empty - return span for the beginning of the file
13701                     return ts.createTextSpan(0, 0);
13702                 }
13703                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
13704             // This list is a work in progress. Add missing node kinds to improve their error
13705             // spans.
13706             case 242 /* VariableDeclaration */:
13707             case 191 /* BindingElement */:
13708             case 245 /* ClassDeclaration */:
13709             case 214 /* ClassExpression */:
13710             case 246 /* InterfaceDeclaration */:
13711             case 249 /* ModuleDeclaration */:
13712             case 248 /* EnumDeclaration */:
13713             case 284 /* EnumMember */:
13714             case 244 /* FunctionDeclaration */:
13715             case 201 /* FunctionExpression */:
13716             case 161 /* MethodDeclaration */:
13717             case 163 /* GetAccessor */:
13718             case 164 /* SetAccessor */:
13719             case 247 /* TypeAliasDeclaration */:
13720             case 159 /* PropertyDeclaration */:
13721             case 158 /* PropertySignature */:
13722                 errorNode = node.name;
13723                 break;
13724             case 202 /* ArrowFunction */:
13725                 return getErrorSpanForArrowFunction(sourceFile, node);
13726             case 277 /* CaseClause */:
13727             case 278 /* DefaultClause */:
13728                 var start = ts.skipTrivia(sourceFile.text, node.pos);
13729                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
13730                 return ts.createTextSpanFromBounds(start, end);
13731         }
13732         if (errorNode === undefined) {
13733             // If we don't have a better node, then just set the error on the first token of
13734             // construct.
13735             return getSpanOfTokenAtPosition(sourceFile, node.pos);
13736         }
13737         ts.Debug.assert(!ts.isJSDoc(errorNode));
13738         var isMissing = nodeIsMissing(errorNode);
13739         var pos = isMissing || ts.isJsxText(node)
13740             ? errorNode.pos
13741             : ts.skipTrivia(sourceFile.text, errorNode.pos);
13742         // These asserts should all be satisfied for a properly constructed `errorNode`.
13743         if (isMissing) {
13744             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13745             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13746         }
13747         else {
13748             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13749             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
13750         }
13751         return ts.createTextSpanFromBounds(pos, errorNode.end);
13752     }
13753     ts.getErrorSpanForNode = getErrorSpanForNode;
13754     function isExternalOrCommonJsModule(file) {
13755         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
13756     }
13757     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
13758     function isJsonSourceFile(file) {
13759         return file.scriptKind === 6 /* JSON */;
13760     }
13761     ts.isJsonSourceFile = isJsonSourceFile;
13762     function isEnumConst(node) {
13763         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
13764     }
13765     ts.isEnumConst = isEnumConst;
13766     function isDeclarationReadonly(declaration) {
13767         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
13768     }
13769     ts.isDeclarationReadonly = isDeclarationReadonly;
13770     function isVarConst(node) {
13771         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
13772     }
13773     ts.isVarConst = isVarConst;
13774     function isLet(node) {
13775         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
13776     }
13777     ts.isLet = isLet;
13778     function isSuperCall(n) {
13779         return n.kind === 196 /* CallExpression */ && n.expression.kind === 102 /* SuperKeyword */;
13780     }
13781     ts.isSuperCall = isSuperCall;
13782     function isImportCall(n) {
13783         return n.kind === 196 /* CallExpression */ && n.expression.kind === 96 /* ImportKeyword */;
13784     }
13785     ts.isImportCall = isImportCall;
13786     function isImportMeta(n) {
13787         return ts.isMetaProperty(n)
13788             && n.keywordToken === 96 /* ImportKeyword */
13789             && n.name.escapedText === "meta";
13790     }
13791     ts.isImportMeta = isImportMeta;
13792     function isLiteralImportTypeNode(n) {
13793         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
13794     }
13795     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
13796     function isPrologueDirective(node) {
13797         return node.kind === 226 /* ExpressionStatement */
13798             && node.expression.kind === 10 /* StringLiteral */;
13799     }
13800     ts.isPrologueDirective = isPrologueDirective;
13801     function isCustomPrologue(node) {
13802         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13803     }
13804     ts.isCustomPrologue = isCustomPrologue;
13805     function isHoistedFunction(node) {
13806         return isCustomPrologue(node)
13807             && ts.isFunctionDeclaration(node);
13808     }
13809     ts.isHoistedFunction = isHoistedFunction;
13810     function isHoistedVariable(node) {
13811         return ts.isIdentifier(node.name)
13812             && !node.initializer;
13813     }
13814     function isHoistedVariableStatement(node) {
13815         return isCustomPrologue(node)
13816             && ts.isVariableStatement(node)
13817             && ts.every(node.declarationList.declarations, isHoistedVariable);
13818     }
13819     ts.isHoistedVariableStatement = isHoistedVariableStatement;
13820     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
13821         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
13822     }
13823     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
13824     function getJSDocCommentRanges(node, text) {
13825         var commentRanges = (node.kind === 156 /* Parameter */ ||
13826             node.kind === 155 /* TypeParameter */ ||
13827             node.kind === 201 /* FunctionExpression */ ||
13828             node.kind === 202 /* ArrowFunction */ ||
13829             node.kind === 200 /* ParenthesizedExpression */) ?
13830             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
13831             ts.getLeadingCommentRanges(text, node.pos);
13832         // True if the comment starts with '/**' but not if it is '/**/'
13833         return ts.filter(commentRanges, function (comment) {
13834             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
13835                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
13836                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
13837         });
13838     }
13839     ts.getJSDocCommentRanges = getJSDocCommentRanges;
13840     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13841     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
13842     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
13843     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
13844     function isPartOfTypeNode(node) {
13845         if (168 /* FirstTypeNode */ <= node.kind && node.kind <= 188 /* LastTypeNode */) {
13846             return true;
13847         }
13848         switch (node.kind) {
13849             case 125 /* AnyKeyword */:
13850             case 148 /* UnknownKeyword */:
13851             case 140 /* NumberKeyword */:
13852             case 151 /* BigIntKeyword */:
13853             case 143 /* StringKeyword */:
13854             case 128 /* BooleanKeyword */:
13855             case 144 /* SymbolKeyword */:
13856             case 141 /* ObjectKeyword */:
13857             case 146 /* UndefinedKeyword */:
13858             case 137 /* NeverKeyword */:
13859                 return true;
13860             case 110 /* VoidKeyword */:
13861                 return node.parent.kind !== 205 /* VoidExpression */;
13862             case 216 /* ExpressionWithTypeArguments */:
13863                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
13864             case 155 /* TypeParameter */:
13865                 return node.parent.kind === 186 /* MappedType */ || node.parent.kind === 181 /* InferType */;
13866             // Identifiers and qualified names may be type nodes, depending on their context. Climb
13867             // above them to find the lowest container
13868             case 75 /* Identifier */:
13869                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
13870                 if (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) {
13871                     node = node.parent;
13872                 }
13873                 else if (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node) {
13874                     node = node.parent;
13875                 }
13876                 // At this point, node is either a qualified name or an identifier
13877                 ts.Debug.assert(node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */ || node.kind === 194 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
13878             // falls through
13879             case 153 /* QualifiedName */:
13880             case 194 /* PropertyAccessExpression */:
13881             case 104 /* ThisKeyword */: {
13882                 var parent = node.parent;
13883                 if (parent.kind === 172 /* TypeQuery */) {
13884                     return false;
13885                 }
13886                 if (parent.kind === 188 /* ImportType */) {
13887                     return !parent.isTypeOf;
13888                 }
13889                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
13890                 //
13891                 //     let a: A.B.C;
13892                 //
13893                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
13894                 // Only C and A.B.C are type nodes.
13895                 if (168 /* FirstTypeNode */ <= parent.kind && parent.kind <= 188 /* LastTypeNode */) {
13896                     return true;
13897                 }
13898                 switch (parent.kind) {
13899                     case 216 /* ExpressionWithTypeArguments */:
13900                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
13901                     case 155 /* TypeParameter */:
13902                         return node === parent.constraint;
13903                     case 321 /* JSDocTemplateTag */:
13904                         return node === parent.constraint;
13905                     case 159 /* PropertyDeclaration */:
13906                     case 158 /* PropertySignature */:
13907                     case 156 /* Parameter */:
13908                     case 242 /* VariableDeclaration */:
13909                         return node === parent.type;
13910                     case 244 /* FunctionDeclaration */:
13911                     case 201 /* FunctionExpression */:
13912                     case 202 /* ArrowFunction */:
13913                     case 162 /* Constructor */:
13914                     case 161 /* MethodDeclaration */:
13915                     case 160 /* MethodSignature */:
13916                     case 163 /* GetAccessor */:
13917                     case 164 /* SetAccessor */:
13918                         return node === parent.type;
13919                     case 165 /* CallSignature */:
13920                     case 166 /* ConstructSignature */:
13921                     case 167 /* IndexSignature */:
13922                         return node === parent.type;
13923                     case 199 /* TypeAssertionExpression */:
13924                         return node === parent.type;
13925                     case 196 /* CallExpression */:
13926                     case 197 /* NewExpression */:
13927                         return ts.contains(parent.typeArguments, node);
13928                     case 198 /* TaggedTemplateExpression */:
13929                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
13930                         return false;
13931                 }
13932             }
13933         }
13934         return false;
13935     }
13936     ts.isPartOfTypeNode = isPartOfTypeNode;
13937     function isChildOfNodeWithKind(node, kind) {
13938         while (node) {
13939             if (node.kind === kind) {
13940                 return true;
13941             }
13942             node = node.parent;
13943         }
13944         return false;
13945     }
13946     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
13947     // Warning: This has the same semantics as the forEach family of functions,
13948     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
13949     function forEachReturnStatement(body, visitor) {
13950         return traverse(body);
13951         function traverse(node) {
13952             switch (node.kind) {
13953                 case 235 /* ReturnStatement */:
13954                     return visitor(node);
13955                 case 251 /* CaseBlock */:
13956                 case 223 /* Block */:
13957                 case 227 /* IfStatement */:
13958                 case 228 /* DoStatement */:
13959                 case 229 /* WhileStatement */:
13960                 case 230 /* ForStatement */:
13961                 case 231 /* ForInStatement */:
13962                 case 232 /* ForOfStatement */:
13963                 case 236 /* WithStatement */:
13964                 case 237 /* SwitchStatement */:
13965                 case 277 /* CaseClause */:
13966                 case 278 /* DefaultClause */:
13967                 case 238 /* LabeledStatement */:
13968                 case 240 /* TryStatement */:
13969                 case 280 /* CatchClause */:
13970                     return ts.forEachChild(node, traverse);
13971             }
13972         }
13973     }
13974     ts.forEachReturnStatement = forEachReturnStatement;
13975     function forEachYieldExpression(body, visitor) {
13976         return traverse(body);
13977         function traverse(node) {
13978             switch (node.kind) {
13979                 case 212 /* YieldExpression */:
13980                     visitor(node);
13981                     var operand = node.expression;
13982                     if (operand) {
13983                         traverse(operand);
13984                     }
13985                     return;
13986                 case 248 /* EnumDeclaration */:
13987                 case 246 /* InterfaceDeclaration */:
13988                 case 249 /* ModuleDeclaration */:
13989                 case 247 /* TypeAliasDeclaration */:
13990                     // These are not allowed inside a generator now, but eventually they may be allowed
13991                     // as local types. Regardless, skip them to avoid the work.
13992                     return;
13993                 default:
13994                     if (ts.isFunctionLike(node)) {
13995                         if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
13996                             // Note that we will not include methods/accessors of a class because they would require
13997                             // first descending into the class. This is by design.
13998                             traverse(node.name.expression);
13999                             return;
14000                         }
14001                     }
14002                     else if (!isPartOfTypeNode(node)) {
14003                         // This is the general case, which should include mostly expressions and statements.
14004                         // Also includes NodeArrays.
14005                         ts.forEachChild(node, traverse);
14006                     }
14007             }
14008         }
14009     }
14010     ts.forEachYieldExpression = forEachYieldExpression;
14011     /**
14012      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14013      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14014      *
14015      * @param node The type node.
14016      */
14017     function getRestParameterElementType(node) {
14018         if (node && node.kind === 174 /* ArrayType */) {
14019             return node.elementType;
14020         }
14021         else if (node && node.kind === 169 /* TypeReference */) {
14022             return ts.singleOrUndefined(node.typeArguments);
14023         }
14024         else {
14025             return undefined;
14026         }
14027     }
14028     ts.getRestParameterElementType = getRestParameterElementType;
14029     function getMembersOfDeclaration(node) {
14030         switch (node.kind) {
14031             case 246 /* InterfaceDeclaration */:
14032             case 245 /* ClassDeclaration */:
14033             case 214 /* ClassExpression */:
14034             case 173 /* TypeLiteral */:
14035                 return node.members;
14036             case 193 /* ObjectLiteralExpression */:
14037                 return node.properties;
14038         }
14039     }
14040     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14041     function isVariableLike(node) {
14042         if (node) {
14043             switch (node.kind) {
14044                 case 191 /* BindingElement */:
14045                 case 284 /* EnumMember */:
14046                 case 156 /* Parameter */:
14047                 case 281 /* PropertyAssignment */:
14048                 case 159 /* PropertyDeclaration */:
14049                 case 158 /* PropertySignature */:
14050                 case 282 /* ShorthandPropertyAssignment */:
14051                 case 242 /* VariableDeclaration */:
14052                     return true;
14053             }
14054         }
14055         return false;
14056     }
14057     ts.isVariableLike = isVariableLike;
14058     function isVariableLikeOrAccessor(node) {
14059         return isVariableLike(node) || ts.isAccessor(node);
14060     }
14061     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14062     function isVariableDeclarationInVariableStatement(node) {
14063         return node.parent.kind === 243 /* VariableDeclarationList */
14064             && node.parent.parent.kind === 225 /* VariableStatement */;
14065     }
14066     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14067     function isValidESSymbolDeclaration(node) {
14068         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14069             ts.isPropertyDeclaration(node) ? hasReadonlyModifier(node) && hasStaticModifier(node) :
14070                 ts.isPropertySignature(node) && hasReadonlyModifier(node);
14071     }
14072     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14073     function introducesArgumentsExoticObject(node) {
14074         switch (node.kind) {
14075             case 161 /* MethodDeclaration */:
14076             case 160 /* MethodSignature */:
14077             case 162 /* Constructor */:
14078             case 163 /* GetAccessor */:
14079             case 164 /* SetAccessor */:
14080             case 244 /* FunctionDeclaration */:
14081             case 201 /* FunctionExpression */:
14082                 return true;
14083         }
14084         return false;
14085     }
14086     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14087     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14088         while (true) {
14089             if (beforeUnwrapLabelCallback) {
14090                 beforeUnwrapLabelCallback(node);
14091             }
14092             if (node.statement.kind !== 238 /* LabeledStatement */) {
14093                 return node.statement;
14094             }
14095             node = node.statement;
14096         }
14097     }
14098     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14099     function isFunctionBlock(node) {
14100         return node && node.kind === 223 /* Block */ && ts.isFunctionLike(node.parent);
14101     }
14102     ts.isFunctionBlock = isFunctionBlock;
14103     function isObjectLiteralMethod(node) {
14104         return node && node.kind === 161 /* MethodDeclaration */ && node.parent.kind === 193 /* ObjectLiteralExpression */;
14105     }
14106     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14107     function isObjectLiteralOrClassExpressionMethod(node) {
14108         return node.kind === 161 /* MethodDeclaration */ &&
14109             (node.parent.kind === 193 /* ObjectLiteralExpression */ ||
14110                 node.parent.kind === 214 /* ClassExpression */);
14111     }
14112     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14113     function isIdentifierTypePredicate(predicate) {
14114         return predicate && predicate.kind === 1 /* Identifier */;
14115     }
14116     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14117     function isThisTypePredicate(predicate) {
14118         return predicate && predicate.kind === 0 /* This */;
14119     }
14120     ts.isThisTypePredicate = isThisTypePredicate;
14121     function getPropertyAssignment(objectLiteral, key, key2) {
14122         return objectLiteral.properties.filter(function (property) {
14123             if (property.kind === 281 /* PropertyAssignment */) {
14124                 var propName = getTextOfPropertyName(property.name);
14125                 return key === propName || (!!key2 && key2 === propName);
14126             }
14127             return false;
14128         });
14129     }
14130     ts.getPropertyAssignment = getPropertyAssignment;
14131     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14132         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14133             var expression = tsConfigSourceFile.statements[0].expression;
14134             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14135         }
14136     }
14137     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14138     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14139         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14140             return ts.isArrayLiteralExpression(property.initializer) ?
14141                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14142                 undefined;
14143         });
14144     }
14145     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14146     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14147         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14148         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14149     }
14150     ts.getTsConfigPropArray = getTsConfigPropArray;
14151     function getContainingFunction(node) {
14152         return findAncestor(node.parent, ts.isFunctionLike);
14153     }
14154     ts.getContainingFunction = getContainingFunction;
14155     function getContainingFunctionDeclaration(node) {
14156         return findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14157     }
14158     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14159     function getContainingClass(node) {
14160         return findAncestor(node.parent, ts.isClassLike);
14161     }
14162     ts.getContainingClass = getContainingClass;
14163     function getThisContainer(node, includeArrowFunctions) {
14164         ts.Debug.assert(node.kind !== 290 /* SourceFile */);
14165         while (true) {
14166             node = node.parent;
14167             if (!node) {
14168                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14169             }
14170             switch (node.kind) {
14171                 case 154 /* ComputedPropertyName */:
14172                     // If the grandparent node is an object literal (as opposed to a class),
14173                     // then the computed property is not a 'this' container.
14174                     // A computed property name in a class needs to be a this container
14175                     // so that we can error on it.
14176                     if (ts.isClassLike(node.parent.parent)) {
14177                         return node;
14178                     }
14179                     // If this is a computed property, then the parent should not
14180                     // make it a this container. The parent might be a property
14181                     // in an object literal, like a method or accessor. But in order for
14182                     // such a parent to be a this container, the reference must be in
14183                     // the *body* of the container.
14184                     node = node.parent;
14185                     break;
14186                 case 157 /* Decorator */:
14187                     // Decorators are always applied outside of the body of a class or method.
14188                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14189                         // If the decorator's parent is a Parameter, we resolve the this container from
14190                         // the grandparent class declaration.
14191                         node = node.parent.parent;
14192                     }
14193                     else if (ts.isClassElement(node.parent)) {
14194                         // If the decorator's parent is a class element, we resolve the 'this' container
14195                         // from the parent class declaration.
14196                         node = node.parent;
14197                     }
14198                     break;
14199                 case 202 /* ArrowFunction */:
14200                     if (!includeArrowFunctions) {
14201                         continue;
14202                     }
14203                 // falls through
14204                 case 244 /* FunctionDeclaration */:
14205                 case 201 /* FunctionExpression */:
14206                 case 249 /* ModuleDeclaration */:
14207                 case 159 /* PropertyDeclaration */:
14208                 case 158 /* PropertySignature */:
14209                 case 161 /* MethodDeclaration */:
14210                 case 160 /* MethodSignature */:
14211                 case 162 /* Constructor */:
14212                 case 163 /* GetAccessor */:
14213                 case 164 /* SetAccessor */:
14214                 case 165 /* CallSignature */:
14215                 case 166 /* ConstructSignature */:
14216                 case 167 /* IndexSignature */:
14217                 case 248 /* EnumDeclaration */:
14218                 case 290 /* SourceFile */:
14219                     return node;
14220             }
14221         }
14222     }
14223     ts.getThisContainer = getThisContainer;
14224     function getNewTargetContainer(node) {
14225         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14226         if (container) {
14227             switch (container.kind) {
14228                 case 162 /* Constructor */:
14229                 case 244 /* FunctionDeclaration */:
14230                 case 201 /* FunctionExpression */:
14231                     return container;
14232             }
14233         }
14234         return undefined;
14235     }
14236     ts.getNewTargetContainer = getNewTargetContainer;
14237     /**
14238      * Given an super call/property node, returns the closest node where
14239      * - a super call/property access is legal in the node and not legal in the parent node the node.
14240      *   i.e. super call is legal in constructor but not legal in the class body.
14241      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14242      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14243      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14244      */
14245     function getSuperContainer(node, stopOnFunctions) {
14246         while (true) {
14247             node = node.parent;
14248             if (!node) {
14249                 return node;
14250             }
14251             switch (node.kind) {
14252                 case 154 /* ComputedPropertyName */:
14253                     node = node.parent;
14254                     break;
14255                 case 244 /* FunctionDeclaration */:
14256                 case 201 /* FunctionExpression */:
14257                 case 202 /* ArrowFunction */:
14258                     if (!stopOnFunctions) {
14259                         continue;
14260                     }
14261                 // falls through
14262                 case 159 /* PropertyDeclaration */:
14263                 case 158 /* PropertySignature */:
14264                 case 161 /* MethodDeclaration */:
14265                 case 160 /* MethodSignature */:
14266                 case 162 /* Constructor */:
14267                 case 163 /* GetAccessor */:
14268                 case 164 /* SetAccessor */:
14269                     return node;
14270                 case 157 /* Decorator */:
14271                     // Decorators are always applied outside of the body of a class or method.
14272                     if (node.parent.kind === 156 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14273                         // If the decorator's parent is a Parameter, we resolve the this container from
14274                         // the grandparent class declaration.
14275                         node = node.parent.parent;
14276                     }
14277                     else if (ts.isClassElement(node.parent)) {
14278                         // If the decorator's parent is a class element, we resolve the 'this' container
14279                         // from the parent class declaration.
14280                         node = node.parent;
14281                     }
14282                     break;
14283             }
14284         }
14285     }
14286     ts.getSuperContainer = getSuperContainer;
14287     function getImmediatelyInvokedFunctionExpression(func) {
14288         if (func.kind === 201 /* FunctionExpression */ || func.kind === 202 /* ArrowFunction */) {
14289             var prev = func;
14290             var parent = func.parent;
14291             while (parent.kind === 200 /* ParenthesizedExpression */) {
14292                 prev = parent;
14293                 parent = parent.parent;
14294             }
14295             if (parent.kind === 196 /* CallExpression */ && parent.expression === prev) {
14296                 return parent;
14297             }
14298         }
14299     }
14300     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14301     function isSuperOrSuperProperty(node) {
14302         return node.kind === 102 /* SuperKeyword */
14303             || isSuperProperty(node);
14304     }
14305     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14306     /**
14307      * Determines whether a node is a property or element access expression for `super`.
14308      */
14309     function isSuperProperty(node) {
14310         var kind = node.kind;
14311         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14312             && node.expression.kind === 102 /* SuperKeyword */;
14313     }
14314     ts.isSuperProperty = isSuperProperty;
14315     /**
14316      * Determines whether a node is a property or element access expression for `this`.
14317      */
14318     function isThisProperty(node) {
14319         var kind = node.kind;
14320         return (kind === 194 /* PropertyAccessExpression */ || kind === 195 /* ElementAccessExpression */)
14321             && node.expression.kind === 104 /* ThisKeyword */;
14322     }
14323     ts.isThisProperty = isThisProperty;
14324     function getEntityNameFromTypeNode(node) {
14325         switch (node.kind) {
14326             case 169 /* TypeReference */:
14327                 return node.typeName;
14328             case 216 /* ExpressionWithTypeArguments */:
14329                 return isEntityNameExpression(node.expression)
14330                     ? node.expression
14331                     : undefined;
14332             case 75 /* Identifier */:
14333             case 153 /* QualifiedName */:
14334                 return node;
14335         }
14336         return undefined;
14337     }
14338     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14339     function getInvokedExpression(node) {
14340         switch (node.kind) {
14341             case 198 /* TaggedTemplateExpression */:
14342                 return node.tag;
14343             case 268 /* JsxOpeningElement */:
14344             case 267 /* JsxSelfClosingElement */:
14345                 return node.tagName;
14346             default:
14347                 return node.expression;
14348         }
14349     }
14350     ts.getInvokedExpression = getInvokedExpression;
14351     function nodeCanBeDecorated(node, parent, grandparent) {
14352         // private names cannot be used with decorators yet
14353         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14354             return false;
14355         }
14356         switch (node.kind) {
14357             case 245 /* ClassDeclaration */:
14358                 // classes are valid targets
14359                 return true;
14360             case 159 /* PropertyDeclaration */:
14361                 // property declarations are valid if their parent is a class declaration.
14362                 return parent.kind === 245 /* ClassDeclaration */;
14363             case 163 /* GetAccessor */:
14364             case 164 /* SetAccessor */:
14365             case 161 /* MethodDeclaration */:
14366                 // if this method has a body and its parent is a class declaration, this is a valid target.
14367                 return node.body !== undefined
14368                     && parent.kind === 245 /* ClassDeclaration */;
14369             case 156 /* Parameter */:
14370                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14371                 return parent.body !== undefined
14372                     && (parent.kind === 162 /* Constructor */
14373                         || parent.kind === 161 /* MethodDeclaration */
14374                         || parent.kind === 164 /* SetAccessor */)
14375                     && grandparent.kind === 245 /* ClassDeclaration */;
14376         }
14377         return false;
14378     }
14379     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14380     function nodeIsDecorated(node, parent, grandparent) {
14381         return node.decorators !== undefined
14382             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14383     }
14384     ts.nodeIsDecorated = nodeIsDecorated;
14385     function nodeOrChildIsDecorated(node, parent, grandparent) {
14386         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14387     }
14388     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14389     function childIsDecorated(node, parent) {
14390         switch (node.kind) {
14391             case 245 /* ClassDeclaration */:
14392                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14393             case 161 /* MethodDeclaration */:
14394             case 164 /* SetAccessor */:
14395                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14396             default:
14397                 return false;
14398         }
14399     }
14400     ts.childIsDecorated = childIsDecorated;
14401     function isJSXTagName(node) {
14402         var parent = node.parent;
14403         if (parent.kind === 268 /* JsxOpeningElement */ ||
14404             parent.kind === 267 /* JsxSelfClosingElement */ ||
14405             parent.kind === 269 /* JsxClosingElement */) {
14406             return parent.tagName === node;
14407         }
14408         return false;
14409     }
14410     ts.isJSXTagName = isJSXTagName;
14411     function isExpressionNode(node) {
14412         switch (node.kind) {
14413             case 102 /* SuperKeyword */:
14414             case 100 /* NullKeyword */:
14415             case 106 /* TrueKeyword */:
14416             case 91 /* FalseKeyword */:
14417             case 13 /* RegularExpressionLiteral */:
14418             case 192 /* ArrayLiteralExpression */:
14419             case 193 /* ObjectLiteralExpression */:
14420             case 194 /* PropertyAccessExpression */:
14421             case 195 /* ElementAccessExpression */:
14422             case 196 /* CallExpression */:
14423             case 197 /* NewExpression */:
14424             case 198 /* TaggedTemplateExpression */:
14425             case 217 /* AsExpression */:
14426             case 199 /* TypeAssertionExpression */:
14427             case 218 /* NonNullExpression */:
14428             case 200 /* ParenthesizedExpression */:
14429             case 201 /* FunctionExpression */:
14430             case 214 /* ClassExpression */:
14431             case 202 /* ArrowFunction */:
14432             case 205 /* VoidExpression */:
14433             case 203 /* DeleteExpression */:
14434             case 204 /* TypeOfExpression */:
14435             case 207 /* PrefixUnaryExpression */:
14436             case 208 /* PostfixUnaryExpression */:
14437             case 209 /* BinaryExpression */:
14438             case 210 /* ConditionalExpression */:
14439             case 213 /* SpreadElement */:
14440             case 211 /* TemplateExpression */:
14441             case 215 /* OmittedExpression */:
14442             case 266 /* JsxElement */:
14443             case 267 /* JsxSelfClosingElement */:
14444             case 270 /* JsxFragment */:
14445             case 212 /* YieldExpression */:
14446             case 206 /* AwaitExpression */:
14447             case 219 /* MetaProperty */:
14448                 return true;
14449             case 153 /* QualifiedName */:
14450                 while (node.parent.kind === 153 /* QualifiedName */) {
14451                     node = node.parent;
14452                 }
14453                 return node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node);
14454             case 75 /* Identifier */:
14455                 if (node.parent.kind === 172 /* TypeQuery */ || isJSXTagName(node)) {
14456                     return true;
14457                 }
14458             // falls through
14459             case 8 /* NumericLiteral */:
14460             case 9 /* BigIntLiteral */:
14461             case 10 /* StringLiteral */:
14462             case 14 /* NoSubstitutionTemplateLiteral */:
14463             case 104 /* ThisKeyword */:
14464                 return isInExpressionContext(node);
14465             default:
14466                 return false;
14467         }
14468     }
14469     ts.isExpressionNode = isExpressionNode;
14470     function isInExpressionContext(node) {
14471         var parent = node.parent;
14472         switch (parent.kind) {
14473             case 242 /* VariableDeclaration */:
14474             case 156 /* Parameter */:
14475             case 159 /* PropertyDeclaration */:
14476             case 158 /* PropertySignature */:
14477             case 284 /* EnumMember */:
14478             case 281 /* PropertyAssignment */:
14479             case 191 /* BindingElement */:
14480                 return parent.initializer === node;
14481             case 226 /* ExpressionStatement */:
14482             case 227 /* IfStatement */:
14483             case 228 /* DoStatement */:
14484             case 229 /* WhileStatement */:
14485             case 235 /* ReturnStatement */:
14486             case 236 /* WithStatement */:
14487             case 237 /* SwitchStatement */:
14488             case 277 /* CaseClause */:
14489             case 239 /* ThrowStatement */:
14490                 return parent.expression === node;
14491             case 230 /* ForStatement */:
14492                 var forStatement = parent;
14493                 return (forStatement.initializer === node && forStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14494                     forStatement.condition === node ||
14495                     forStatement.incrementor === node;
14496             case 231 /* ForInStatement */:
14497             case 232 /* ForOfStatement */:
14498                 var forInStatement = parent;
14499                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 243 /* VariableDeclarationList */) ||
14500                     forInStatement.expression === node;
14501             case 199 /* TypeAssertionExpression */:
14502             case 217 /* AsExpression */:
14503                 return node === parent.expression;
14504             case 221 /* TemplateSpan */:
14505                 return node === parent.expression;
14506             case 154 /* ComputedPropertyName */:
14507                 return node === parent.expression;
14508             case 157 /* Decorator */:
14509             case 276 /* JsxExpression */:
14510             case 275 /* JsxSpreadAttribute */:
14511             case 283 /* SpreadAssignment */:
14512                 return true;
14513             case 216 /* ExpressionWithTypeArguments */:
14514                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14515             case 282 /* ShorthandPropertyAssignment */:
14516                 return parent.objectAssignmentInitializer === node;
14517             default:
14518                 return isExpressionNode(parent);
14519         }
14520     }
14521     ts.isInExpressionContext = isInExpressionContext;
14522     function isPartOfTypeQuery(node) {
14523         while (node.kind === 153 /* QualifiedName */ || node.kind === 75 /* Identifier */) {
14524             node = node.parent;
14525         }
14526         return node.kind === 172 /* TypeQuery */;
14527     }
14528     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14529     function isExternalModuleImportEqualsDeclaration(node) {
14530         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */;
14531     }
14532     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14533     function getExternalModuleImportEqualsDeclarationExpression(node) {
14534         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14535         return node.moduleReference.expression;
14536     }
14537     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14538     function isInternalModuleImportEqualsDeclaration(node) {
14539         return node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 265 /* ExternalModuleReference */;
14540     }
14541     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14542     function isSourceFileJS(file) {
14543         return isInJSFile(file);
14544     }
14545     ts.isSourceFileJS = isSourceFileJS;
14546     function isSourceFileNotJS(file) {
14547         return !isInJSFile(file);
14548     }
14549     ts.isSourceFileNotJS = isSourceFileNotJS;
14550     function isInJSFile(node) {
14551         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14552     }
14553     ts.isInJSFile = isInJSFile;
14554     function isInJsonFile(node) {
14555         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14556     }
14557     ts.isInJsonFile = isInJsonFile;
14558     function isSourceFileNotJson(file) {
14559         return !isJsonSourceFile(file);
14560     }
14561     ts.isSourceFileNotJson = isSourceFileNotJson;
14562     function isInJSDoc(node) {
14563         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14564     }
14565     ts.isInJSDoc = isInJSDoc;
14566     function isJSDocIndexSignature(node) {
14567         return ts.isTypeReferenceNode(node) &&
14568             ts.isIdentifier(node.typeName) &&
14569             node.typeName.escapedText === "Object" &&
14570             node.typeArguments && node.typeArguments.length === 2 &&
14571             (node.typeArguments[0].kind === 143 /* StringKeyword */ || node.typeArguments[0].kind === 140 /* NumberKeyword */);
14572     }
14573     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14574     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14575         if (callExpression.kind !== 196 /* CallExpression */) {
14576             return false;
14577         }
14578         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14579         if (expression.kind !== 75 /* Identifier */ || expression.escapedText !== "require") {
14580             return false;
14581         }
14582         if (args.length !== 1) {
14583             return false;
14584         }
14585         var arg = args[0];
14586         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14587     }
14588     ts.isRequireCall = isRequireCall;
14589     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14590         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(node.initializer, requireStringLiteralLikeArgument);
14591     }
14592     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
14593     function isRequireVariableDeclarationStatement(node, requireStringLiteralLikeArgument) {
14594         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
14595         return ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
14596     }
14597     ts.isRequireVariableDeclarationStatement = isRequireVariableDeclarationStatement;
14598     function isSingleOrDoubleQuote(charCode) {
14599         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
14600     }
14601     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
14602     function isStringDoubleQuoted(str, sourceFile) {
14603         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
14604     }
14605     ts.isStringDoubleQuoted = isStringDoubleQuoted;
14606     function getDeclarationOfExpando(node) {
14607         if (!node.parent) {
14608             return undefined;
14609         }
14610         var name;
14611         var decl;
14612         if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
14613             if (!isInJSFile(node) && !isVarConst(node.parent)) {
14614                 return undefined;
14615             }
14616             name = node.parent.name;
14617             decl = node.parent;
14618         }
14619         else if (ts.isBinaryExpression(node.parent)) {
14620             var parentNode = node.parent;
14621             var parentNodeOperator = node.parent.operatorToken.kind;
14622             if (parentNodeOperator === 62 /* EqualsToken */ && parentNode.right === node) {
14623                 name = parentNode.left;
14624                 decl = name;
14625             }
14626             else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
14627                 if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
14628                     name = parentNode.parent.name;
14629                     decl = parentNode.parent;
14630                 }
14631                 else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && parentNode.parent.right === parentNode) {
14632                     name = parentNode.parent.left;
14633                     decl = name;
14634                 }
14635                 if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
14636                     return undefined;
14637                 }
14638             }
14639         }
14640         if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) {
14641             return undefined;
14642         }
14643         return decl;
14644     }
14645     ts.getDeclarationOfExpando = getDeclarationOfExpando;
14646     function isAssignmentDeclaration(decl) {
14647         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
14648     }
14649     ts.isAssignmentDeclaration = isAssignmentDeclaration;
14650     /** Get the initializer, taking into account defaulted Javascript initializers */
14651     function getEffectiveInitializer(node) {
14652         if (isInJSFile(node) && node.initializer &&
14653             ts.isBinaryExpression(node.initializer) &&
14654             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
14655             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
14656             return node.initializer.right;
14657         }
14658         return node.initializer;
14659     }
14660     ts.getEffectiveInitializer = getEffectiveInitializer;
14661     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
14662     function getDeclaredExpandoInitializer(node) {
14663         var init = getEffectiveInitializer(node);
14664         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
14665     }
14666     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
14667     function hasExpandoValueProperty(node, isPrototypeAssignment) {
14668         return ts.forEach(node.properties, function (p) {
14669             return ts.isPropertyAssignment(p) &&
14670                 ts.isIdentifier(p.name) &&
14671                 p.name.escapedText === "value" &&
14672                 p.initializer &&
14673                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
14674         });
14675     }
14676     /**
14677      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
14678      * We treat the right hand side of assignments with container-like initalizers as declarations.
14679      */
14680     function getAssignedExpandoInitializer(node) {
14681         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
14682             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
14683             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
14684                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
14685         }
14686         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
14687             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
14688             if (result) {
14689                 return result;
14690             }
14691         }
14692     }
14693     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
14694     /**
14695      * Recognized expando initializers are:
14696      * 1. (function() {})() -- IIFEs
14697      * 2. function() { } -- Function expressions
14698      * 3. class { } -- Class expressions
14699      * 4. {} -- Empty object literals
14700      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
14701      *
14702      * This function returns the provided initializer, or undefined if it is not valid.
14703      */
14704     function getExpandoInitializer(initializer, isPrototypeAssignment) {
14705         if (ts.isCallExpression(initializer)) {
14706             var e = skipParentheses(initializer.expression);
14707             return e.kind === 201 /* FunctionExpression */ || e.kind === 202 /* ArrowFunction */ ? initializer : undefined;
14708         }
14709         if (initializer.kind === 201 /* FunctionExpression */ ||
14710             initializer.kind === 214 /* ClassExpression */ ||
14711             initializer.kind === 202 /* ArrowFunction */) {
14712             return initializer;
14713         }
14714         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
14715             return initializer;
14716         }
14717     }
14718     ts.getExpandoInitializer = getExpandoInitializer;
14719     /**
14720      * A defaulted expando initializer matches the pattern
14721      * `Lhs = Lhs || ExpandoInitializer`
14722      * or `var Lhs = Lhs || ExpandoInitializer`
14723      *
14724      * The second Lhs is required to be the same as the first except that it may be prefixed with
14725      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
14726      */
14727     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
14728         var e = ts.isBinaryExpression(initializer)
14729             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
14730             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
14731         if (e && isSameEntityName(name, initializer.left)) {
14732             return e;
14733         }
14734     }
14735     function isDefaultedExpandoInitializer(node) {
14736         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
14737             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
14738                 undefined;
14739         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
14740     }
14741     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
14742     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
14743     function getNameOfExpando(node) {
14744         if (ts.isBinaryExpression(node.parent)) {
14745             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
14746             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
14747                 return parent.left;
14748             }
14749         }
14750         else if (ts.isVariableDeclaration(node.parent)) {
14751             return node.parent.name;
14752         }
14753     }
14754     ts.getNameOfExpando = getNameOfExpando;
14755     /**
14756      * Is the 'declared' name the same as the one in the initializer?
14757      * @return true for identical entity names, as well as ones where the initializer is prefixed with
14758      * 'window', 'self' or 'global'. For example:
14759      *
14760      * var my = my || {}
14761      * var min = window.min || {}
14762      * my.app = self.my.app || class { }
14763      */
14764     function isSameEntityName(name, initializer) {
14765         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
14766             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(name);
14767         }
14768         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
14769             (initializer.expression.kind === 104 /* ThisKeyword */ ||
14770                 ts.isIdentifier(initializer.expression) &&
14771                     (initializer.expression.escapedText === "window" ||
14772                         initializer.expression.escapedText === "self" ||
14773                         initializer.expression.escapedText === "global"))) {
14774             var nameOrArgument = getNameOrArgument(initializer);
14775             if (ts.isPrivateIdentifier(nameOrArgument)) {
14776                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
14777             }
14778             return isSameEntityName(name, nameOrArgument);
14779         }
14780         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
14781             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
14782                 && isSameEntityName(name.expression, initializer.expression);
14783         }
14784         return false;
14785     }
14786     function getRightMostAssignedExpression(node) {
14787         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
14788             node = node.right;
14789         }
14790         return node;
14791     }
14792     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
14793     function isExportsIdentifier(node) {
14794         return ts.isIdentifier(node) && node.escapedText === "exports";
14795     }
14796     ts.isExportsIdentifier = isExportsIdentifier;
14797     function isModuleIdentifier(node) {
14798         return ts.isIdentifier(node) && node.escapedText === "module";
14799     }
14800     ts.isModuleIdentifier = isModuleIdentifier;
14801     function isModuleExportsAccessExpression(node) {
14802         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
14803             && isModuleIdentifier(node.expression)
14804             && getElementOrPropertyAccessName(node) === "exports";
14805     }
14806     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
14807     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
14808     /// assignments we treat as special in the binder
14809     function getAssignmentDeclarationKind(expr) {
14810         var special = getAssignmentDeclarationKindWorker(expr);
14811         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
14812     }
14813     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
14814     function isBindableObjectDefinePropertyCall(expr) {
14815         return ts.length(expr.arguments) === 3 &&
14816             ts.isPropertyAccessExpression(expr.expression) &&
14817             ts.isIdentifier(expr.expression.expression) &&
14818             ts.idText(expr.expression.expression) === "Object" &&
14819             ts.idText(expr.expression.name) === "defineProperty" &&
14820             isStringOrNumericLiteralLike(expr.arguments[1]) &&
14821             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
14822     }
14823     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
14824     /** x.y OR x[0] */
14825     function isLiteralLikeAccess(node) {
14826         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
14827     }
14828     ts.isLiteralLikeAccess = isLiteralLikeAccess;
14829     /** x[0] OR x['a'] OR x[Symbol.y] */
14830     function isLiteralLikeElementAccess(node) {
14831         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
14832             isWellKnownSymbolSyntactically(node.argumentExpression));
14833     }
14834     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
14835     /** Any series of property and element accesses. */
14836     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
14837         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
14838             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
14839     }
14840     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
14841     /** Any series of property and element accesses, ending in a literal element access */
14842     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
14843         return isLiteralLikeElementAccess(node)
14844             && ((!excludeThisKeyword && node.expression.kind === 104 /* ThisKeyword */) ||
14845                 isEntityNameExpression(node.expression) ||
14846                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
14847     }
14848     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
14849     function isBindableStaticNameExpression(node, excludeThisKeyword) {
14850         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
14851     }
14852     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
14853     function getNameOrArgument(expr) {
14854         if (ts.isPropertyAccessExpression(expr)) {
14855             return expr.name;
14856         }
14857         return expr.argumentExpression;
14858     }
14859     ts.getNameOrArgument = getNameOrArgument;
14860     function getAssignmentDeclarationKindWorker(expr) {
14861         if (ts.isCallExpression(expr)) {
14862             if (!isBindableObjectDefinePropertyCall(expr)) {
14863                 return 0 /* None */;
14864             }
14865             var entityName = expr.arguments[0];
14866             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
14867                 return 8 /* ObjectDefinePropertyExports */;
14868             }
14869             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
14870                 return 9 /* ObjectDefinePrototypeProperty */;
14871             }
14872             return 7 /* ObjectDefinePropertyValue */;
14873         }
14874         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left)) {
14875             return 0 /* None */;
14876         }
14877         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
14878             // F.prototype = { ... }
14879             return 6 /* Prototype */;
14880         }
14881         return getAssignmentDeclarationPropertyAccessKind(expr.left);
14882     }
14883     /**
14884      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
14885      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
14886      */
14887     /* @internal */
14888     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
14889         if (ts.isPropertyAccessExpression(node)) {
14890             return node.name;
14891         }
14892         var arg = skipParentheses(node.argumentExpression);
14893         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
14894             return arg;
14895         }
14896         return node;
14897     }
14898     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
14899     function getElementOrPropertyAccessName(node) {
14900         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
14901         if (name) {
14902             if (ts.isIdentifier(name)) {
14903                 return name.escapedText;
14904             }
14905             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
14906                 return ts.escapeLeadingUnderscores(name.text);
14907             }
14908         }
14909         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
14910             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
14911         }
14912         return undefined;
14913     }
14914     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
14915     function getAssignmentDeclarationPropertyAccessKind(lhs) {
14916         if (lhs.expression.kind === 104 /* ThisKeyword */) {
14917             return 4 /* ThisProperty */;
14918         }
14919         else if (isModuleExportsAccessExpression(lhs)) {
14920             // module.exports = expr
14921             return 2 /* ModuleExports */;
14922         }
14923         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
14924             if (isPrototypeAccess(lhs.expression)) {
14925                 // F.G....prototype.x = expr
14926                 return 3 /* PrototypeProperty */;
14927             }
14928             var nextToLast = lhs;
14929             while (!ts.isIdentifier(nextToLast.expression)) {
14930                 nextToLast = nextToLast.expression;
14931             }
14932             var id = nextToLast.expression;
14933             if ((id.escapedText === "exports" ||
14934                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
14935                 // ExportsProperty does not support binding with computed names
14936                 isBindableStaticAccessExpression(lhs)) {
14937                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
14938                 return 1 /* ExportsProperty */;
14939             }
14940             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
14941                 // F.G...x = expr
14942                 return 5 /* Property */;
14943             }
14944         }
14945         return 0 /* None */;
14946     }
14947     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
14948     function getInitializerOfBinaryExpression(expr) {
14949         while (ts.isBinaryExpression(expr.right)) {
14950             expr = expr.right;
14951         }
14952         return expr.right;
14953     }
14954     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
14955     function isPrototypePropertyAssignment(node) {
14956         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
14957     }
14958     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
14959     function isSpecialPropertyDeclaration(expr) {
14960         return isInJSFile(expr) &&
14961             expr.parent && expr.parent.kind === 226 /* ExpressionStatement */ &&
14962             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
14963             !!ts.getJSDocTypeTag(expr.parent);
14964     }
14965     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
14966     function setValueDeclaration(symbol, node) {
14967         var valueDeclaration = symbol.valueDeclaration;
14968         if (!valueDeclaration ||
14969             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
14970                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
14971             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
14972             // other kinds of value declarations take precedence over modules and assignment declarations
14973             symbol.valueDeclaration = node;
14974         }
14975     }
14976     ts.setValueDeclaration = setValueDeclaration;
14977     function isFunctionSymbol(symbol) {
14978         if (!symbol || !symbol.valueDeclaration) {
14979             return false;
14980         }
14981         var decl = symbol.valueDeclaration;
14982         return decl.kind === 244 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
14983     }
14984     ts.isFunctionSymbol = isFunctionSymbol;
14985     function importFromModuleSpecifier(node) {
14986         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
14987     }
14988     ts.importFromModuleSpecifier = importFromModuleSpecifier;
14989     function tryGetImportFromModuleSpecifier(node) {
14990         switch (node.parent.kind) {
14991             case 254 /* ImportDeclaration */:
14992             case 260 /* ExportDeclaration */:
14993                 return node.parent;
14994             case 265 /* ExternalModuleReference */:
14995                 return node.parent.parent;
14996             case 196 /* CallExpression */:
14997                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
14998             case 187 /* LiteralType */:
14999                 ts.Debug.assert(ts.isStringLiteral(node));
15000                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15001             default:
15002                 return undefined;
15003         }
15004     }
15005     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15006     function getExternalModuleName(node) {
15007         switch (node.kind) {
15008             case 254 /* ImportDeclaration */:
15009             case 260 /* ExportDeclaration */:
15010                 return node.moduleSpecifier;
15011             case 253 /* ImportEqualsDeclaration */:
15012                 return node.moduleReference.kind === 265 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15013             case 188 /* ImportType */:
15014                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15015             default:
15016                 return ts.Debug.assertNever(node);
15017         }
15018     }
15019     ts.getExternalModuleName = getExternalModuleName;
15020     function getNamespaceDeclarationNode(node) {
15021         switch (node.kind) {
15022             case 254 /* ImportDeclaration */:
15023                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15024             case 253 /* ImportEqualsDeclaration */:
15025                 return node;
15026             case 260 /* ExportDeclaration */:
15027                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15028             default:
15029                 return ts.Debug.assertNever(node);
15030         }
15031     }
15032     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15033     function isDefaultImport(node) {
15034         return node.kind === 254 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15035     }
15036     ts.isDefaultImport = isDefaultImport;
15037     function forEachImportClauseDeclaration(node, action) {
15038         if (node.name) {
15039             var result = action(node);
15040             if (result)
15041                 return result;
15042         }
15043         if (node.namedBindings) {
15044             var result = ts.isNamespaceImport(node.namedBindings)
15045                 ? action(node.namedBindings)
15046                 : ts.forEach(node.namedBindings.elements, action);
15047             if (result)
15048                 return result;
15049         }
15050     }
15051     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15052     function hasQuestionToken(node) {
15053         if (node) {
15054             switch (node.kind) {
15055                 case 156 /* Parameter */:
15056                 case 161 /* MethodDeclaration */:
15057                 case 160 /* MethodSignature */:
15058                 case 282 /* ShorthandPropertyAssignment */:
15059                 case 281 /* PropertyAssignment */:
15060                 case 159 /* PropertyDeclaration */:
15061                 case 158 /* PropertySignature */:
15062                     return node.questionToken !== undefined;
15063             }
15064         }
15065         return false;
15066     }
15067     ts.hasQuestionToken = hasQuestionToken;
15068     function isJSDocConstructSignature(node) {
15069         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15070         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15071         return !!name && name.escapedText === "new";
15072     }
15073     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15074     function isJSDocTypeAlias(node) {
15075         return node.kind === 322 /* JSDocTypedefTag */ || node.kind === 315 /* JSDocCallbackTag */ || node.kind === 316 /* JSDocEnumTag */;
15076     }
15077     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15078     function isTypeAlias(node) {
15079         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15080     }
15081     ts.isTypeAlias = isTypeAlias;
15082     function getSourceOfAssignment(node) {
15083         return ts.isExpressionStatement(node) &&
15084             ts.isBinaryExpression(node.expression) &&
15085             node.expression.operatorToken.kind === 62 /* EqualsToken */
15086             ? getRightMostAssignedExpression(node.expression)
15087             : undefined;
15088     }
15089     function getSourceOfDefaultedAssignment(node) {
15090         return ts.isExpressionStatement(node) &&
15091             ts.isBinaryExpression(node.expression) &&
15092             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15093             ts.isBinaryExpression(node.expression.right) &&
15094             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15095             ? node.expression.right.right
15096             : undefined;
15097     }
15098     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15099         switch (node.kind) {
15100             case 225 /* VariableStatement */:
15101                 var v = getSingleVariableOfVariableStatement(node);
15102                 return v && v.initializer;
15103             case 159 /* PropertyDeclaration */:
15104                 return node.initializer;
15105             case 281 /* PropertyAssignment */:
15106                 return node.initializer;
15107         }
15108     }
15109     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15110     function getSingleVariableOfVariableStatement(node) {
15111         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15112     }
15113     function getNestedModuleDeclaration(node) {
15114         return ts.isModuleDeclaration(node) &&
15115             node.body &&
15116             node.body.kind === 249 /* ModuleDeclaration */
15117             ? node.body
15118             : undefined;
15119     }
15120     function getJSDocCommentsAndTags(hostNode) {
15121         var result;
15122         // Pull parameter comments from declaring function as well
15123         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15124             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15125         }
15126         var node = hostNode;
15127         while (node && node.parent) {
15128             if (ts.hasJSDocNodes(node)) {
15129                 result = ts.append(result, ts.last(node.jsDoc));
15130             }
15131             if (node.kind === 156 /* Parameter */) {
15132                 result = ts.addRange(result, ts.getJSDocParameterTags(node));
15133                 break;
15134             }
15135             if (node.kind === 155 /* TypeParameter */) {
15136                 result = ts.addRange(result, ts.getJSDocTypeParameterTags(node));
15137                 break;
15138             }
15139             node = getNextJSDocCommentLocation(node);
15140         }
15141         return result || ts.emptyArray;
15142     }
15143     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15144     function getNextJSDocCommentLocation(node) {
15145         var parent = node.parent;
15146         if (parent.kind === 281 /* PropertyAssignment */ ||
15147             parent.kind === 259 /* ExportAssignment */ ||
15148             parent.kind === 159 /* PropertyDeclaration */ ||
15149             parent.kind === 226 /* ExpressionStatement */ && node.kind === 194 /* PropertyAccessExpression */ ||
15150             getNestedModuleDeclaration(parent) ||
15151             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15152             return parent;
15153         }
15154         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15155         // /**
15156         //   * @param {number} name
15157         //   * @returns {number}
15158         //   */
15159         // var x = function(name) { return name.length; }
15160         else if (parent.parent &&
15161             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15162                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15163             return parent.parent;
15164         }
15165         else if (parent.parent && parent.parent.parent &&
15166             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15167                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15168                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15169             return parent.parent.parent;
15170         }
15171     }
15172     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15173     function getParameterSymbolFromJSDoc(node) {
15174         if (node.symbol) {
15175             return node.symbol;
15176         }
15177         if (!ts.isIdentifier(node.name)) {
15178             return undefined;
15179         }
15180         var name = node.name.escapedText;
15181         var decl = getHostSignatureFromJSDoc(node);
15182         if (!decl) {
15183             return undefined;
15184         }
15185         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 75 /* Identifier */ && p.name.escapedText === name; });
15186         return parameter && parameter.symbol;
15187     }
15188     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15189     function getHostSignatureFromJSDoc(node) {
15190         var host = getEffectiveJSDocHost(node);
15191         return host && ts.isFunctionLike(host) ? host : undefined;
15192     }
15193     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15194     function getEffectiveJSDocHost(node) {
15195         var host = getJSDocHost(node);
15196         var decl = getSourceOfDefaultedAssignment(host) ||
15197             getSourceOfAssignment(host) ||
15198             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15199             getSingleVariableOfVariableStatement(host) ||
15200             getNestedModuleDeclaration(host) ||
15201             host;
15202         return decl;
15203     }
15204     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15205     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15206     function getJSDocHost(node) {
15207         return ts.Debug.checkDefined(findAncestor(node.parent, ts.isJSDoc)).parent;
15208     }
15209     ts.getJSDocHost = getJSDocHost;
15210     function getTypeParameterFromJsDoc(node) {
15211         var name = node.name.escapedText;
15212         var typeParameters = node.parent.parent.parent.typeParameters;
15213         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15214     }
15215     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15216     function hasRestParameter(s) {
15217         var last = ts.lastOrUndefined(s.parameters);
15218         return !!last && isRestParameter(last);
15219     }
15220     ts.hasRestParameter = hasRestParameter;
15221     function isRestParameter(node) {
15222         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15223         return node.dotDotDotToken !== undefined || !!type && type.kind === 301 /* JSDocVariadicType */;
15224     }
15225     ts.isRestParameter = isRestParameter;
15226     function hasTypeArguments(node) {
15227         return !!node.typeArguments;
15228     }
15229     ts.hasTypeArguments = hasTypeArguments;
15230     var AssignmentKind;
15231     (function (AssignmentKind) {
15232         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15233         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15234         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15235     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15236     function getAssignmentTargetKind(node) {
15237         var parent = node.parent;
15238         while (true) {
15239             switch (parent.kind) {
15240                 case 209 /* BinaryExpression */:
15241                     var binaryOperator = parent.operatorToken.kind;
15242                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15243                         binaryOperator === 62 /* EqualsToken */ ? 1 /* Definite */ : 2 /* Compound */ :
15244                         0 /* None */;
15245                 case 207 /* PrefixUnaryExpression */:
15246                 case 208 /* PostfixUnaryExpression */:
15247                     var unaryOperator = parent.operator;
15248                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15249                 case 231 /* ForInStatement */:
15250                 case 232 /* ForOfStatement */:
15251                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15252                 case 200 /* ParenthesizedExpression */:
15253                 case 192 /* ArrayLiteralExpression */:
15254                 case 213 /* SpreadElement */:
15255                 case 218 /* NonNullExpression */:
15256                     node = parent;
15257                     break;
15258                 case 282 /* ShorthandPropertyAssignment */:
15259                     if (parent.name !== node) {
15260                         return 0 /* None */;
15261                     }
15262                     node = parent.parent;
15263                     break;
15264                 case 281 /* PropertyAssignment */:
15265                     if (parent.name === node) {
15266                         return 0 /* None */;
15267                     }
15268                     node = parent.parent;
15269                     break;
15270                 default:
15271                     return 0 /* None */;
15272             }
15273             parent = node.parent;
15274         }
15275     }
15276     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15277     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15278     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15279     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15280     // (Note that `p` is not a target in the above examples, only `a`.)
15281     function isAssignmentTarget(node) {
15282         return getAssignmentTargetKind(node) !== 0 /* None */;
15283     }
15284     ts.isAssignmentTarget = isAssignmentTarget;
15285     /**
15286      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15287      * the same `var` declaration scope as the node's parent.
15288      */
15289     function isNodeWithPossibleHoistedDeclaration(node) {
15290         switch (node.kind) {
15291             case 223 /* Block */:
15292             case 225 /* VariableStatement */:
15293             case 236 /* WithStatement */:
15294             case 227 /* IfStatement */:
15295             case 237 /* SwitchStatement */:
15296             case 251 /* CaseBlock */:
15297             case 277 /* CaseClause */:
15298             case 278 /* DefaultClause */:
15299             case 238 /* LabeledStatement */:
15300             case 230 /* ForStatement */:
15301             case 231 /* ForInStatement */:
15302             case 232 /* ForOfStatement */:
15303             case 228 /* DoStatement */:
15304             case 229 /* WhileStatement */:
15305             case 240 /* TryStatement */:
15306             case 280 /* CatchClause */:
15307                 return true;
15308         }
15309         return false;
15310     }
15311     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15312     function isValueSignatureDeclaration(node) {
15313         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15314     }
15315     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15316     function walkUp(node, kind) {
15317         while (node && node.kind === kind) {
15318             node = node.parent;
15319         }
15320         return node;
15321     }
15322     function walkUpParenthesizedTypes(node) {
15323         return walkUp(node, 182 /* ParenthesizedType */);
15324     }
15325     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15326     function walkUpParenthesizedExpressions(node) {
15327         return walkUp(node, 200 /* ParenthesizedExpression */);
15328     }
15329     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15330     function skipParentheses(node) {
15331         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15332     }
15333     ts.skipParentheses = skipParentheses;
15334     function skipParenthesesUp(node) {
15335         while (node.kind === 200 /* ParenthesizedExpression */) {
15336             node = node.parent;
15337         }
15338         return node;
15339     }
15340     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15341     function isDeleteTarget(node) {
15342         if (node.kind !== 194 /* PropertyAccessExpression */ && node.kind !== 195 /* ElementAccessExpression */) {
15343             return false;
15344         }
15345         node = walkUpParenthesizedExpressions(node.parent);
15346         return node && node.kind === 203 /* DeleteExpression */;
15347     }
15348     ts.isDeleteTarget = isDeleteTarget;
15349     function isNodeDescendantOf(node, ancestor) {
15350         while (node) {
15351             if (node === ancestor)
15352                 return true;
15353             node = node.parent;
15354         }
15355         return false;
15356     }
15357     ts.isNodeDescendantOf = isNodeDescendantOf;
15358     // True if `name` is the name of a declaration node
15359     function isDeclarationName(name) {
15360         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15361     }
15362     ts.isDeclarationName = isDeclarationName;
15363     // See GH#16030
15364     function getDeclarationFromName(name) {
15365         var parent = name.parent;
15366         switch (name.kind) {
15367             case 10 /* StringLiteral */:
15368             case 14 /* NoSubstitutionTemplateLiteral */:
15369             case 8 /* NumericLiteral */:
15370                 if (ts.isComputedPropertyName(parent))
15371                     return parent.parent;
15372             // falls through
15373             case 75 /* Identifier */:
15374                 if (ts.isDeclaration(parent)) {
15375                     return parent.name === name ? parent : undefined;
15376                 }
15377                 else if (ts.isQualifiedName(parent)) {
15378                     var tag = parent.parent;
15379                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15380                 }
15381                 else {
15382                     var binExp = parent.parent;
15383                     return ts.isBinaryExpression(binExp) &&
15384                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15385                         (binExp.left.symbol || binExp.symbol) &&
15386                         ts.getNameOfDeclaration(binExp) === name
15387                         ? binExp
15388                         : undefined;
15389                 }
15390             case 76 /* PrivateIdentifier */:
15391                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15392             default:
15393                 return undefined;
15394         }
15395     }
15396     ts.getDeclarationFromName = getDeclarationFromName;
15397     function isLiteralComputedPropertyDeclarationName(node) {
15398         return isStringOrNumericLiteralLike(node) &&
15399             node.parent.kind === 154 /* ComputedPropertyName */ &&
15400             ts.isDeclaration(node.parent.parent);
15401     }
15402     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15403     // Return true if the given identifier is classified as an IdentifierName
15404     function isIdentifierName(node) {
15405         var parent = node.parent;
15406         switch (parent.kind) {
15407             case 159 /* PropertyDeclaration */:
15408             case 158 /* PropertySignature */:
15409             case 161 /* MethodDeclaration */:
15410             case 160 /* MethodSignature */:
15411             case 163 /* GetAccessor */:
15412             case 164 /* SetAccessor */:
15413             case 284 /* EnumMember */:
15414             case 281 /* PropertyAssignment */:
15415             case 194 /* PropertyAccessExpression */:
15416                 // Name in member declaration or property name in property access
15417                 return parent.name === node;
15418             case 153 /* QualifiedName */:
15419                 // Name on right hand side of dot in a type query or type reference
15420                 if (parent.right === node) {
15421                     while (parent.kind === 153 /* QualifiedName */) {
15422                         parent = parent.parent;
15423                     }
15424                     return parent.kind === 172 /* TypeQuery */ || parent.kind === 169 /* TypeReference */;
15425                 }
15426                 return false;
15427             case 191 /* BindingElement */:
15428             case 258 /* ImportSpecifier */:
15429                 // Property name in binding element or import specifier
15430                 return parent.propertyName === node;
15431             case 263 /* ExportSpecifier */:
15432             case 273 /* JsxAttribute */:
15433                 // Any name in an export specifier or JSX Attribute
15434                 return true;
15435         }
15436         return false;
15437     }
15438     ts.isIdentifierName = isIdentifierName;
15439     // An alias symbol is created by one of the following declarations:
15440     // import <symbol> = ...
15441     // import <symbol> from ...
15442     // import * as <symbol> from ...
15443     // import { x as <symbol> } from ...
15444     // export { x as <symbol> } from ...
15445     // export * as ns <symbol> from ...
15446     // export = <EntityNameExpression>
15447     // export default <EntityNameExpression>
15448     // module.exports = <EntityNameExpression>
15449     // {<Identifier>}
15450     // {name: <EntityNameExpression>}
15451     function isAliasSymbolDeclaration(node) {
15452         return node.kind === 253 /* ImportEqualsDeclaration */ ||
15453             node.kind === 252 /* NamespaceExportDeclaration */ ||
15454             node.kind === 255 /* ImportClause */ && !!node.name ||
15455             node.kind === 256 /* NamespaceImport */ ||
15456             node.kind === 262 /* NamespaceExport */ ||
15457             node.kind === 258 /* ImportSpecifier */ ||
15458             node.kind === 263 /* ExportSpecifier */ ||
15459             node.kind === 259 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15460             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15461             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15462             node.kind === 282 /* ShorthandPropertyAssignment */ ||
15463             node.kind === 281 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15464     }
15465     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15466     function getAliasDeclarationFromName(node) {
15467         switch (node.parent.kind) {
15468             case 255 /* ImportClause */:
15469             case 258 /* ImportSpecifier */:
15470             case 256 /* NamespaceImport */:
15471             case 263 /* ExportSpecifier */:
15472             case 259 /* ExportAssignment */:
15473             case 253 /* ImportEqualsDeclaration */:
15474                 return node.parent;
15475             case 153 /* QualifiedName */:
15476                 do {
15477                     node = node.parent;
15478                 } while (node.parent.kind === 153 /* QualifiedName */);
15479                 return getAliasDeclarationFromName(node);
15480         }
15481     }
15482     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15483     function isAliasableExpression(e) {
15484         return isEntityNameExpression(e) || ts.isClassExpression(e);
15485     }
15486     ts.isAliasableExpression = isAliasableExpression;
15487     function exportAssignmentIsAlias(node) {
15488         var e = getExportAssignmentExpression(node);
15489         return isAliasableExpression(e);
15490     }
15491     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15492     function getExportAssignmentExpression(node) {
15493         return ts.isExportAssignment(node) ? node.expression : node.right;
15494     }
15495     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15496     function getPropertyAssignmentAliasLikeExpression(node) {
15497         return node.kind === 282 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 281 /* PropertyAssignment */ ? node.initializer :
15498             node.parent.right;
15499     }
15500     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15501     function getEffectiveBaseTypeNode(node) {
15502         var baseType = getClassExtendsHeritageElement(node);
15503         if (baseType && isInJSFile(node)) {
15504             // Prefer an @augments tag because it may have type parameters.
15505             var tag = ts.getJSDocAugmentsTag(node);
15506             if (tag) {
15507                 return tag.class;
15508             }
15509         }
15510         return baseType;
15511     }
15512     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15513     function getClassExtendsHeritageElement(node) {
15514         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15515         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15516     }
15517     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15518     function getEffectiveImplementsTypeNodes(node) {
15519         if (isInJSFile(node)) {
15520             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15521         }
15522         else {
15523             var heritageClause = getHeritageClause(node.heritageClauses, 113 /* ImplementsKeyword */);
15524             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15525         }
15526     }
15527     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15528     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15529     function getAllSuperTypeNodes(node) {
15530         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15531             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15532                 ts.emptyArray;
15533     }
15534     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15535     function getInterfaceBaseTypeNodes(node) {
15536         var heritageClause = getHeritageClause(node.heritageClauses, 90 /* ExtendsKeyword */);
15537         return heritageClause ? heritageClause.types : undefined;
15538     }
15539     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15540     function getHeritageClause(clauses, kind) {
15541         if (clauses) {
15542             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15543                 var clause = clauses_1[_i];
15544                 if (clause.token === kind) {
15545                     return clause;
15546                 }
15547             }
15548         }
15549         return undefined;
15550     }
15551     ts.getHeritageClause = getHeritageClause;
15552     function getAncestor(node, kind) {
15553         while (node) {
15554             if (node.kind === kind) {
15555                 return node;
15556             }
15557             node = node.parent;
15558         }
15559         return undefined;
15560     }
15561     ts.getAncestor = getAncestor;
15562     function isKeyword(token) {
15563         return 77 /* FirstKeyword */ <= token && token <= 152 /* LastKeyword */;
15564     }
15565     ts.isKeyword = isKeyword;
15566     function isContextualKeyword(token) {
15567         return 122 /* FirstContextualKeyword */ <= token && token <= 152 /* LastContextualKeyword */;
15568     }
15569     ts.isContextualKeyword = isContextualKeyword;
15570     function isNonContextualKeyword(token) {
15571         return isKeyword(token) && !isContextualKeyword(token);
15572     }
15573     ts.isNonContextualKeyword = isNonContextualKeyword;
15574     function isFutureReservedKeyword(token) {
15575         return 113 /* FirstFutureReservedWord */ <= token && token <= 121 /* LastFutureReservedWord */;
15576     }
15577     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15578     function isStringANonContextualKeyword(name) {
15579         var token = ts.stringToToken(name);
15580         return token !== undefined && isNonContextualKeyword(token);
15581     }
15582     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15583     function isStringAKeyword(name) {
15584         var token = ts.stringToToken(name);
15585         return token !== undefined && isKeyword(token);
15586     }
15587     ts.isStringAKeyword = isStringAKeyword;
15588     function isIdentifierANonContextualKeyword(_a) {
15589         var originalKeywordKind = _a.originalKeywordKind;
15590         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15591     }
15592     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15593     function isTrivia(token) {
15594         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15595     }
15596     ts.isTrivia = isTrivia;
15597     var FunctionFlags;
15598     (function (FunctionFlags) {
15599         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15600         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15601         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15602         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15603         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15604     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15605     function getFunctionFlags(node) {
15606         if (!node) {
15607             return 4 /* Invalid */;
15608         }
15609         var flags = 0 /* Normal */;
15610         switch (node.kind) {
15611             case 244 /* FunctionDeclaration */:
15612             case 201 /* FunctionExpression */:
15613             case 161 /* MethodDeclaration */:
15614                 if (node.asteriskToken) {
15615                     flags |= 1 /* Generator */;
15616                 }
15617             // falls through
15618             case 202 /* ArrowFunction */:
15619                 if (hasModifier(node, 256 /* Async */)) {
15620                     flags |= 2 /* Async */;
15621                 }
15622                 break;
15623         }
15624         if (!node.body) {
15625             flags |= 4 /* Invalid */;
15626         }
15627         return flags;
15628     }
15629     ts.getFunctionFlags = getFunctionFlags;
15630     function isAsyncFunction(node) {
15631         switch (node.kind) {
15632             case 244 /* FunctionDeclaration */:
15633             case 201 /* FunctionExpression */:
15634             case 202 /* ArrowFunction */:
15635             case 161 /* MethodDeclaration */:
15636                 return node.body !== undefined
15637                     && node.asteriskToken === undefined
15638                     && hasModifier(node, 256 /* Async */);
15639         }
15640         return false;
15641     }
15642     ts.isAsyncFunction = isAsyncFunction;
15643     function isStringOrNumericLiteralLike(node) {
15644         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
15645     }
15646     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
15647     function isSignedNumericLiteral(node) {
15648         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
15649     }
15650     ts.isSignedNumericLiteral = isSignedNumericLiteral;
15651     /**
15652      * A declaration has a dynamic name if all of the following are true:
15653      *   1. The declaration has a computed property name.
15654      *   2. The computed name is *not* expressed as a StringLiteral.
15655      *   3. The computed name is *not* expressed as a NumericLiteral.
15656      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
15657      *      immediately followed by a NumericLiteral.
15658      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
15659      *      is a property of the Symbol constructor that denotes a built-in
15660      *      Symbol.
15661      */
15662     function hasDynamicName(declaration) {
15663         var name = ts.getNameOfDeclaration(declaration);
15664         return !!name && isDynamicName(name);
15665     }
15666     ts.hasDynamicName = hasDynamicName;
15667     function isDynamicName(name) {
15668         if (!(name.kind === 154 /* ComputedPropertyName */ || name.kind === 195 /* ElementAccessExpression */)) {
15669             return false;
15670         }
15671         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
15672         return !isStringOrNumericLiteralLike(expr) &&
15673             !isSignedNumericLiteral(expr) &&
15674             !isWellKnownSymbolSyntactically(expr);
15675     }
15676     ts.isDynamicName = isDynamicName;
15677     /**
15678      * Checks if the expression is of the form:
15679      *    Symbol.name
15680      * where Symbol is literally the word "Symbol", and name is any identifierName
15681      */
15682     function isWellKnownSymbolSyntactically(node) {
15683         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
15684     }
15685     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
15686     function getPropertyNameForPropertyNameNode(name) {
15687         switch (name.kind) {
15688             case 75 /* Identifier */:
15689             case 76 /* PrivateIdentifier */:
15690                 return name.escapedText;
15691             case 10 /* StringLiteral */:
15692             case 8 /* NumericLiteral */:
15693                 return ts.escapeLeadingUnderscores(name.text);
15694             case 154 /* ComputedPropertyName */:
15695                 var nameExpression = name.expression;
15696                 if (isWellKnownSymbolSyntactically(nameExpression)) {
15697                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
15698                 }
15699                 else if (isStringOrNumericLiteralLike(nameExpression)) {
15700                     return ts.escapeLeadingUnderscores(nameExpression.text);
15701                 }
15702                 return undefined;
15703             default:
15704                 return ts.Debug.assertNever(name);
15705         }
15706     }
15707     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
15708     function isPropertyNameLiteral(node) {
15709         switch (node.kind) {
15710             case 75 /* Identifier */:
15711             case 10 /* StringLiteral */:
15712             case 14 /* NoSubstitutionTemplateLiteral */:
15713             case 8 /* NumericLiteral */:
15714                 return true;
15715             default:
15716                 return false;
15717         }
15718     }
15719     ts.isPropertyNameLiteral = isPropertyNameLiteral;
15720     function getTextOfIdentifierOrLiteral(node) {
15721         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
15722     }
15723     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
15724     function getEscapedTextOfIdentifierOrLiteral(node) {
15725         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
15726     }
15727     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
15728     function getPropertyNameForUniqueESSymbol(symbol) {
15729         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
15730     }
15731     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
15732     function getPropertyNameForKnownSymbolName(symbolName) {
15733         return "__@" + symbolName;
15734     }
15735     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
15736     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
15737         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
15738     }
15739     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
15740     function isKnownSymbol(symbol) {
15741         return ts.startsWith(symbol.escapedName, "__@");
15742     }
15743     ts.isKnownSymbol = isKnownSymbol;
15744     /**
15745      * Includes the word "Symbol" with unicode escapes
15746      */
15747     function isESSymbolIdentifier(node) {
15748         return node.kind === 75 /* Identifier */ && node.escapedText === "Symbol";
15749     }
15750     ts.isESSymbolIdentifier = isESSymbolIdentifier;
15751     function isPushOrUnshiftIdentifier(node) {
15752         return node.escapedText === "push" || node.escapedText === "unshift";
15753     }
15754     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
15755     function isParameterDeclaration(node) {
15756         var root = getRootDeclaration(node);
15757         return root.kind === 156 /* Parameter */;
15758     }
15759     ts.isParameterDeclaration = isParameterDeclaration;
15760     function getRootDeclaration(node) {
15761         while (node.kind === 191 /* BindingElement */) {
15762             node = node.parent.parent;
15763         }
15764         return node;
15765     }
15766     ts.getRootDeclaration = getRootDeclaration;
15767     function nodeStartsNewLexicalEnvironment(node) {
15768         var kind = node.kind;
15769         return kind === 162 /* Constructor */
15770             || kind === 201 /* FunctionExpression */
15771             || kind === 244 /* FunctionDeclaration */
15772             || kind === 202 /* ArrowFunction */
15773             || kind === 161 /* MethodDeclaration */
15774             || kind === 163 /* GetAccessor */
15775             || kind === 164 /* SetAccessor */
15776             || kind === 249 /* ModuleDeclaration */
15777             || kind === 290 /* SourceFile */;
15778     }
15779     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
15780     function nodeIsSynthesized(range) {
15781         return positionIsSynthesized(range.pos)
15782             || positionIsSynthesized(range.end);
15783     }
15784     ts.nodeIsSynthesized = nodeIsSynthesized;
15785     function getOriginalSourceFile(sourceFile) {
15786         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
15787     }
15788     ts.getOriginalSourceFile = getOriginalSourceFile;
15789     var Associativity;
15790     (function (Associativity) {
15791         Associativity[Associativity["Left"] = 0] = "Left";
15792         Associativity[Associativity["Right"] = 1] = "Right";
15793     })(Associativity = ts.Associativity || (ts.Associativity = {}));
15794     function getExpressionAssociativity(expression) {
15795         var operator = getOperator(expression);
15796         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15797         return getOperatorAssociativity(expression.kind, operator, hasArguments);
15798     }
15799     ts.getExpressionAssociativity = getExpressionAssociativity;
15800     function getOperatorAssociativity(kind, operator, hasArguments) {
15801         switch (kind) {
15802             case 197 /* NewExpression */:
15803                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
15804             case 207 /* PrefixUnaryExpression */:
15805             case 204 /* TypeOfExpression */:
15806             case 205 /* VoidExpression */:
15807             case 203 /* DeleteExpression */:
15808             case 206 /* AwaitExpression */:
15809             case 210 /* ConditionalExpression */:
15810             case 212 /* YieldExpression */:
15811                 return 1 /* Right */;
15812             case 209 /* BinaryExpression */:
15813                 switch (operator) {
15814                     case 42 /* AsteriskAsteriskToken */:
15815                     case 62 /* EqualsToken */:
15816                     case 63 /* PlusEqualsToken */:
15817                     case 64 /* MinusEqualsToken */:
15818                     case 66 /* AsteriskAsteriskEqualsToken */:
15819                     case 65 /* AsteriskEqualsToken */:
15820                     case 67 /* SlashEqualsToken */:
15821                     case 68 /* PercentEqualsToken */:
15822                     case 69 /* LessThanLessThanEqualsToken */:
15823                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15824                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15825                     case 72 /* AmpersandEqualsToken */:
15826                     case 74 /* CaretEqualsToken */:
15827                     case 73 /* BarEqualsToken */:
15828                         return 1 /* Right */;
15829                 }
15830         }
15831         return 0 /* Left */;
15832     }
15833     ts.getOperatorAssociativity = getOperatorAssociativity;
15834     function getExpressionPrecedence(expression) {
15835         var operator = getOperator(expression);
15836         var hasArguments = expression.kind === 197 /* NewExpression */ && expression.arguments !== undefined;
15837         return getOperatorPrecedence(expression.kind, operator, hasArguments);
15838     }
15839     ts.getExpressionPrecedence = getExpressionPrecedence;
15840     function getOperator(expression) {
15841         if (expression.kind === 209 /* BinaryExpression */) {
15842             return expression.operatorToken.kind;
15843         }
15844         else if (expression.kind === 207 /* PrefixUnaryExpression */ || expression.kind === 208 /* PostfixUnaryExpression */) {
15845             return expression.operator;
15846         }
15847         else {
15848             return expression.kind;
15849         }
15850     }
15851     ts.getOperator = getOperator;
15852     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
15853         switch (nodeKind) {
15854             case 327 /* CommaListExpression */:
15855                 return 0;
15856             case 213 /* SpreadElement */:
15857                 return 1;
15858             case 212 /* YieldExpression */:
15859                 return 2;
15860             case 210 /* ConditionalExpression */:
15861                 return 4;
15862             case 209 /* BinaryExpression */:
15863                 switch (operatorKind) {
15864                     case 27 /* CommaToken */:
15865                         return 0;
15866                     case 62 /* EqualsToken */:
15867                     case 63 /* PlusEqualsToken */:
15868                     case 64 /* MinusEqualsToken */:
15869                     case 66 /* AsteriskAsteriskEqualsToken */:
15870                     case 65 /* AsteriskEqualsToken */:
15871                     case 67 /* SlashEqualsToken */:
15872                     case 68 /* PercentEqualsToken */:
15873                     case 69 /* LessThanLessThanEqualsToken */:
15874                     case 70 /* GreaterThanGreaterThanEqualsToken */:
15875                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
15876                     case 72 /* AmpersandEqualsToken */:
15877                     case 74 /* CaretEqualsToken */:
15878                     case 73 /* BarEqualsToken */:
15879                         return 3;
15880                     default:
15881                         return getBinaryOperatorPrecedence(operatorKind);
15882                 }
15883             case 207 /* PrefixUnaryExpression */:
15884             case 204 /* TypeOfExpression */:
15885             case 205 /* VoidExpression */:
15886             case 203 /* DeleteExpression */:
15887             case 206 /* AwaitExpression */:
15888                 return 16;
15889             case 208 /* PostfixUnaryExpression */:
15890                 return 17;
15891             case 196 /* CallExpression */:
15892                 return 18;
15893             case 197 /* NewExpression */:
15894                 return hasArguments ? 19 : 18;
15895             case 198 /* TaggedTemplateExpression */:
15896             case 194 /* PropertyAccessExpression */:
15897             case 195 /* ElementAccessExpression */:
15898                 return 19;
15899             case 104 /* ThisKeyword */:
15900             case 102 /* SuperKeyword */:
15901             case 75 /* Identifier */:
15902             case 100 /* NullKeyword */:
15903             case 106 /* TrueKeyword */:
15904             case 91 /* FalseKeyword */:
15905             case 8 /* NumericLiteral */:
15906             case 9 /* BigIntLiteral */:
15907             case 10 /* StringLiteral */:
15908             case 192 /* ArrayLiteralExpression */:
15909             case 193 /* ObjectLiteralExpression */:
15910             case 201 /* FunctionExpression */:
15911             case 202 /* ArrowFunction */:
15912             case 214 /* ClassExpression */:
15913             case 266 /* JsxElement */:
15914             case 267 /* JsxSelfClosingElement */:
15915             case 270 /* JsxFragment */:
15916             case 13 /* RegularExpressionLiteral */:
15917             case 14 /* NoSubstitutionTemplateLiteral */:
15918             case 211 /* TemplateExpression */:
15919             case 200 /* ParenthesizedExpression */:
15920             case 215 /* OmittedExpression */:
15921                 return 20;
15922             default:
15923                 return -1;
15924         }
15925     }
15926     ts.getOperatorPrecedence = getOperatorPrecedence;
15927     function getBinaryOperatorPrecedence(kind) {
15928         switch (kind) {
15929             case 60 /* QuestionQuestionToken */:
15930                 return 4;
15931             case 56 /* BarBarToken */:
15932                 return 5;
15933             case 55 /* AmpersandAmpersandToken */:
15934                 return 6;
15935             case 51 /* BarToken */:
15936                 return 7;
15937             case 52 /* CaretToken */:
15938                 return 8;
15939             case 50 /* AmpersandToken */:
15940                 return 9;
15941             case 34 /* EqualsEqualsToken */:
15942             case 35 /* ExclamationEqualsToken */:
15943             case 36 /* EqualsEqualsEqualsToken */:
15944             case 37 /* ExclamationEqualsEqualsToken */:
15945                 return 10;
15946             case 29 /* LessThanToken */:
15947             case 31 /* GreaterThanToken */:
15948             case 32 /* LessThanEqualsToken */:
15949             case 33 /* GreaterThanEqualsToken */:
15950             case 98 /* InstanceOfKeyword */:
15951             case 97 /* InKeyword */:
15952             case 123 /* AsKeyword */:
15953                 return 11;
15954             case 47 /* LessThanLessThanToken */:
15955             case 48 /* GreaterThanGreaterThanToken */:
15956             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
15957                 return 12;
15958             case 39 /* PlusToken */:
15959             case 40 /* MinusToken */:
15960                 return 13;
15961             case 41 /* AsteriskToken */:
15962             case 43 /* SlashToken */:
15963             case 44 /* PercentToken */:
15964                 return 14;
15965             case 42 /* AsteriskAsteriskToken */:
15966                 return 15;
15967         }
15968         // -1 is lower than all other precedences.  Returning it will cause binary expression
15969         // parsing to stop.
15970         return -1;
15971     }
15972     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
15973     function createDiagnosticCollection() {
15974         var nonFileDiagnostics = []; // See GH#19873
15975         var filesWithDiagnostics = [];
15976         var fileDiagnostics = ts.createMap();
15977         var hasReadNonFileDiagnostics = false;
15978         return {
15979             add: add,
15980             lookup: lookup,
15981             getGlobalDiagnostics: getGlobalDiagnostics,
15982             getDiagnostics: getDiagnostics,
15983             reattachFileDiagnostics: reattachFileDiagnostics
15984         };
15985         function reattachFileDiagnostics(newFile) {
15986             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
15987         }
15988         function lookup(diagnostic) {
15989             var diagnostics;
15990             if (diagnostic.file) {
15991                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
15992             }
15993             else {
15994                 diagnostics = nonFileDiagnostics;
15995             }
15996             if (!diagnostics) {
15997                 return undefined;
15998             }
15999             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16000             if (result >= 0) {
16001                 return diagnostics[result];
16002             }
16003             return undefined;
16004         }
16005         function add(diagnostic) {
16006             var diagnostics;
16007             if (diagnostic.file) {
16008                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16009                 if (!diagnostics) {
16010                     diagnostics = []; // See GH#19873
16011                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16012                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16013                 }
16014             }
16015             else {
16016                 // If we've already read the non-file diagnostics, do not modify the existing array.
16017                 if (hasReadNonFileDiagnostics) {
16018                     hasReadNonFileDiagnostics = false;
16019                     nonFileDiagnostics = nonFileDiagnostics.slice();
16020                 }
16021                 diagnostics = nonFileDiagnostics;
16022             }
16023             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16024         }
16025         function getGlobalDiagnostics() {
16026             hasReadNonFileDiagnostics = true;
16027             return nonFileDiagnostics;
16028         }
16029         function getDiagnostics(fileName) {
16030             if (fileName) {
16031                 return fileDiagnostics.get(fileName) || [];
16032             }
16033             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16034             if (!nonFileDiagnostics.length) {
16035                 return fileDiags;
16036             }
16037             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16038             return fileDiags;
16039         }
16040     }
16041     ts.createDiagnosticCollection = createDiagnosticCollection;
16042     var templateSubstitutionRegExp = /\$\{/g;
16043     function escapeTemplateSubstitution(str) {
16044         return str.replace(templateSubstitutionRegExp, "\\${");
16045     }
16046     /** @internal */
16047     function hasInvalidEscape(template) {
16048         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16049             ? template.templateFlags
16050             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16051     }
16052     ts.hasInvalidEscape = hasInvalidEscape;
16053     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16054     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16055     // the language service. These characters should be escaped when printing, and if any characters are added,
16056     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16057     // There is no reason for this other than that JSON.stringify does not handle it either.
16058     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16059     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16060     // Template strings should be preserved as much as possible
16061     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16062     var escapedCharsMap = ts.createMapFromTemplate({
16063         "\t": "\\t",
16064         "\v": "\\v",
16065         "\f": "\\f",
16066         "\b": "\\b",
16067         "\r": "\\r",
16068         "\n": "\\n",
16069         "\\": "\\\\",
16070         "\"": "\\\"",
16071         "\'": "\\\'",
16072         "\`": "\\\`",
16073         "\u2028": "\\u2028",
16074         "\u2029": "\\u2029",
16075         "\u0085": "\\u0085" // nextLine
16076     });
16077     function encodeUtf16EscapeSequence(charCode) {
16078         var hexCharCode = charCode.toString(16).toUpperCase();
16079         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16080         return "\\u" + paddedHexCode;
16081     }
16082     function getReplacement(c, offset, input) {
16083         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16084             var lookAhead = input.charCodeAt(offset + c.length);
16085             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16086                 // 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)
16087                 return "\\x00";
16088             }
16089             // Otherwise, keep printing a literal \0 for the null character
16090             return "\\0";
16091         }
16092         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16093     }
16094     /**
16095      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16096      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16097      * Note that this doesn't actually wrap the input in double quotes.
16098      */
16099     function escapeString(s, quoteChar) {
16100         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16101             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16102                 doubleQuoteEscapedCharsRegExp;
16103         return s.replace(escapedCharsRegExp, getReplacement);
16104     }
16105     ts.escapeString = escapeString;
16106     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16107     function escapeNonAsciiString(s, quoteChar) {
16108         s = escapeString(s, quoteChar);
16109         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16110         // Otherwise just return the original string.
16111         return nonAsciiCharacters.test(s) ?
16112             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16113             s;
16114     }
16115     ts.escapeNonAsciiString = escapeNonAsciiString;
16116     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16117     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16118     // the language service. These characters should be escaped when printing, and if any characters are added,
16119     // the map below must be updated.
16120     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16121     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16122     var jsxEscapedCharsMap = ts.createMapFromTemplate({
16123         "\"": "&quot;",
16124         "\'": "&apos;"
16125     });
16126     function encodeJsxCharacterEntity(charCode) {
16127         var hexCharCode = charCode.toString(16).toUpperCase();
16128         return "&#x" + hexCharCode + ";";
16129     }
16130     function getJsxAttributeStringReplacement(c) {
16131         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16132             return "&#0;";
16133         }
16134         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16135     }
16136     function escapeJsxAttributeString(s, quoteChar) {
16137         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16138             jsxDoubleQuoteEscapedCharsRegExp;
16139         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16140     }
16141     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16142     /**
16143      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16144      *
16145      * @return non-quoted string
16146      */
16147     function stripQuotes(name) {
16148         var length = name.length;
16149         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16150             return name.substring(1, length - 1);
16151         }
16152         return name;
16153     }
16154     ts.stripQuotes = stripQuotes;
16155     function isQuoteOrBacktick(charCode) {
16156         return charCode === 39 /* singleQuote */ ||
16157             charCode === 34 /* doubleQuote */ ||
16158             charCode === 96 /* backtick */;
16159     }
16160     function isIntrinsicJsxName(name) {
16161         var ch = name.charCodeAt(0);
16162         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16163     }
16164     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16165     var indentStrings = ["", "    "];
16166     function getIndentString(level) {
16167         if (indentStrings[level] === undefined) {
16168             indentStrings[level] = getIndentString(level - 1) + indentStrings[1];
16169         }
16170         return indentStrings[level];
16171     }
16172     ts.getIndentString = getIndentString;
16173     function getIndentSize() {
16174         return indentStrings[1].length;
16175     }
16176     ts.getIndentSize = getIndentSize;
16177     function createTextWriter(newLine) {
16178         var output;
16179         var indent;
16180         var lineStart;
16181         var lineCount;
16182         var linePos;
16183         var hasTrailingComment = false;
16184         function updateLineCountAndPosFor(s) {
16185             var lineStartsOfS = ts.computeLineStarts(s);
16186             if (lineStartsOfS.length > 1) {
16187                 lineCount = lineCount + lineStartsOfS.length - 1;
16188                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16189                 lineStart = (linePos - output.length) === 0;
16190             }
16191             else {
16192                 lineStart = false;
16193             }
16194         }
16195         function writeText(s) {
16196             if (s && s.length) {
16197                 if (lineStart) {
16198                     s = getIndentString(indent) + s;
16199                     lineStart = false;
16200                 }
16201                 output += s;
16202                 updateLineCountAndPosFor(s);
16203             }
16204         }
16205         function write(s) {
16206             if (s)
16207                 hasTrailingComment = false;
16208             writeText(s);
16209         }
16210         function writeComment(s) {
16211             if (s)
16212                 hasTrailingComment = true;
16213             writeText(s);
16214         }
16215         function reset() {
16216             output = "";
16217             indent = 0;
16218             lineStart = true;
16219             lineCount = 0;
16220             linePos = 0;
16221             hasTrailingComment = false;
16222         }
16223         function rawWrite(s) {
16224             if (s !== undefined) {
16225                 output += s;
16226                 updateLineCountAndPosFor(s);
16227                 hasTrailingComment = false;
16228             }
16229         }
16230         function writeLiteral(s) {
16231             if (s && s.length) {
16232                 write(s);
16233             }
16234         }
16235         function writeLine(force) {
16236             if (!lineStart || force) {
16237                 output += newLine;
16238                 lineCount++;
16239                 linePos = output.length;
16240                 lineStart = true;
16241                 hasTrailingComment = false;
16242             }
16243         }
16244         function getTextPosWithWriteLine() {
16245             return lineStart ? output.length : (output.length + newLine.length);
16246         }
16247         reset();
16248         return {
16249             write: write,
16250             rawWrite: rawWrite,
16251             writeLiteral: writeLiteral,
16252             writeLine: writeLine,
16253             increaseIndent: function () { indent++; },
16254             decreaseIndent: function () { indent--; },
16255             getIndent: function () { return indent; },
16256             getTextPos: function () { return output.length; },
16257             getLine: function () { return lineCount; },
16258             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16259             getText: function () { return output; },
16260             isAtStartOfLine: function () { return lineStart; },
16261             hasTrailingComment: function () { return hasTrailingComment; },
16262             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16263             clear: reset,
16264             reportInaccessibleThisError: ts.noop,
16265             reportPrivateInBaseOfClassExpression: ts.noop,
16266             reportInaccessibleUniqueSymbolError: ts.noop,
16267             trackSymbol: ts.noop,
16268             writeKeyword: write,
16269             writeOperator: write,
16270             writeParameter: write,
16271             writeProperty: write,
16272             writePunctuation: write,
16273             writeSpace: write,
16274             writeStringLiteral: write,
16275             writeSymbol: function (s, _) { return write(s); },
16276             writeTrailingSemicolon: write,
16277             writeComment: writeComment,
16278             getTextPosWithWriteLine: getTextPosWithWriteLine
16279         };
16280     }
16281     ts.createTextWriter = createTextWriter;
16282     function getTrailingSemicolonDeferringWriter(writer) {
16283         var pendingTrailingSemicolon = false;
16284         function commitPendingTrailingSemicolon() {
16285             if (pendingTrailingSemicolon) {
16286                 writer.writeTrailingSemicolon(";");
16287                 pendingTrailingSemicolon = false;
16288             }
16289         }
16290         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16291                 pendingTrailingSemicolon = true;
16292             },
16293             writeLiteral: function (s) {
16294                 commitPendingTrailingSemicolon();
16295                 writer.writeLiteral(s);
16296             },
16297             writeStringLiteral: function (s) {
16298                 commitPendingTrailingSemicolon();
16299                 writer.writeStringLiteral(s);
16300             },
16301             writeSymbol: function (s, sym) {
16302                 commitPendingTrailingSemicolon();
16303                 writer.writeSymbol(s, sym);
16304             },
16305             writePunctuation: function (s) {
16306                 commitPendingTrailingSemicolon();
16307                 writer.writePunctuation(s);
16308             },
16309             writeKeyword: function (s) {
16310                 commitPendingTrailingSemicolon();
16311                 writer.writeKeyword(s);
16312             },
16313             writeOperator: function (s) {
16314                 commitPendingTrailingSemicolon();
16315                 writer.writeOperator(s);
16316             },
16317             writeParameter: function (s) {
16318                 commitPendingTrailingSemicolon();
16319                 writer.writeParameter(s);
16320             },
16321             writeSpace: function (s) {
16322                 commitPendingTrailingSemicolon();
16323                 writer.writeSpace(s);
16324             },
16325             writeProperty: function (s) {
16326                 commitPendingTrailingSemicolon();
16327                 writer.writeProperty(s);
16328             },
16329             writeComment: function (s) {
16330                 commitPendingTrailingSemicolon();
16331                 writer.writeComment(s);
16332             },
16333             writeLine: function () {
16334                 commitPendingTrailingSemicolon();
16335                 writer.writeLine();
16336             },
16337             increaseIndent: function () {
16338                 commitPendingTrailingSemicolon();
16339                 writer.increaseIndent();
16340             },
16341             decreaseIndent: function () {
16342                 commitPendingTrailingSemicolon();
16343                 writer.decreaseIndent();
16344             } });
16345     }
16346     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16347     function hostUsesCaseSensitiveFileNames(host) {
16348         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16349     }
16350     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16351     function hostGetCanonicalFileName(host) {
16352         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16353     }
16354     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16355     function getResolvedExternalModuleName(host, file, referenceFile) {
16356         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16357     }
16358     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16359     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16360         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16361         if (!file || file.isDeclarationFile) {
16362             return undefined;
16363         }
16364         return getResolvedExternalModuleName(host, file);
16365     }
16366     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16367     /**
16368      * Resolves a local path to a path which is absolute to the base of the emit
16369      */
16370     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16371         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16372         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16373         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16374         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16375         var extensionless = removeFileExtension(relativePath);
16376         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16377     }
16378     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16379     function getOwnEmitOutputFilePath(fileName, host, extension) {
16380         var compilerOptions = host.getCompilerOptions();
16381         var emitOutputFilePathWithoutExtension;
16382         if (compilerOptions.outDir) {
16383             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16384         }
16385         else {
16386             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16387         }
16388         return emitOutputFilePathWithoutExtension + extension;
16389     }
16390     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16391     function getDeclarationEmitOutputFilePath(fileName, host) {
16392         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16393     }
16394     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16395     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16396         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16397         var path = outputDir
16398             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16399             : fileName;
16400         return removeFileExtension(path) + ".d.ts" /* Dts */;
16401     }
16402     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16403     /**
16404      * Gets the source files that are expected to have an emit output.
16405      *
16406      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
16407      * transformations.
16408      *
16409      * @param host An EmitHost.
16410      * @param targetSourceFile An optional target source file to emit.
16411      */
16412     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
16413         var options = host.getCompilerOptions();
16414         if (options.outFile || options.out) {
16415             var moduleKind = getEmitModuleKind(options);
16416             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
16417             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
16418             return ts.filter(host.getSourceFiles(), function (sourceFile) {
16419                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
16420                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
16421             });
16422         }
16423         else {
16424             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
16425             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
16426         }
16427     }
16428     ts.getSourceFilesToEmit = getSourceFilesToEmit;
16429     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
16430     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
16431         var options = host.getCompilerOptions();
16432         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
16433             !sourceFile.isDeclarationFile &&
16434             !host.isSourceFileFromExternalLibrary(sourceFile) &&
16435             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
16436             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
16437     }
16438     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
16439     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
16440         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16441     }
16442     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
16443     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16444         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
16445         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
16446         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
16447         return ts.combinePaths(newDirPath, sourceFilePath);
16448     }
16449     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
16450     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
16451         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
16452             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
16453         }, sourceFiles);
16454     }
16455     ts.writeFile = writeFile;
16456     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
16457         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
16458             var parentDirectory = ts.getDirectoryPath(directoryPath);
16459             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
16460             createDirectory(directoryPath);
16461         }
16462     }
16463     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
16464         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
16465         // and fall back to creating it if the file write fails.
16466         try {
16467             writeFile(path, data, writeByteOrderMark);
16468         }
16469         catch (_a) {
16470             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
16471             writeFile(path, data, writeByteOrderMark);
16472         }
16473     }
16474     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
16475     function getLineOfLocalPosition(sourceFile, pos) {
16476         var lineStarts = ts.getLineStarts(sourceFile);
16477         return ts.computeLineOfPosition(lineStarts, pos);
16478     }
16479     ts.getLineOfLocalPosition = getLineOfLocalPosition;
16480     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
16481         return ts.computeLineOfPosition(lineMap, pos);
16482     }
16483     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
16484     function getFirstConstructorWithBody(node) {
16485         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
16486     }
16487     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
16488     function getSetAccessorValueParameter(accessor) {
16489         if (accessor && accessor.parameters.length > 0) {
16490             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
16491             return accessor.parameters[hasThis ? 1 : 0];
16492         }
16493     }
16494     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
16495     /** Get the type annotation for the value parameter. */
16496     function getSetAccessorTypeAnnotationNode(accessor) {
16497         var parameter = getSetAccessorValueParameter(accessor);
16498         return parameter && parameter.type;
16499     }
16500     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
16501     function getThisParameter(signature) {
16502         // callback tags do not currently support this parameters
16503         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
16504             var thisParameter = signature.parameters[0];
16505             if (parameterIsThisKeyword(thisParameter)) {
16506                 return thisParameter;
16507             }
16508         }
16509     }
16510     ts.getThisParameter = getThisParameter;
16511     function parameterIsThisKeyword(parameter) {
16512         return isThisIdentifier(parameter.name);
16513     }
16514     ts.parameterIsThisKeyword = parameterIsThisKeyword;
16515     function isThisIdentifier(node) {
16516         return !!node && node.kind === 75 /* Identifier */ && identifierIsThisKeyword(node);
16517     }
16518     ts.isThisIdentifier = isThisIdentifier;
16519     function identifierIsThisKeyword(id) {
16520         return id.originalKeywordKind === 104 /* ThisKeyword */;
16521     }
16522     ts.identifierIsThisKeyword = identifierIsThisKeyword;
16523     function getAllAccessorDeclarations(declarations, accessor) {
16524         // TODO: GH#18217
16525         var firstAccessor;
16526         var secondAccessor;
16527         var getAccessor;
16528         var setAccessor;
16529         if (hasDynamicName(accessor)) {
16530             firstAccessor = accessor;
16531             if (accessor.kind === 163 /* GetAccessor */) {
16532                 getAccessor = accessor;
16533             }
16534             else if (accessor.kind === 164 /* SetAccessor */) {
16535                 setAccessor = accessor;
16536             }
16537             else {
16538                 ts.Debug.fail("Accessor has wrong kind");
16539             }
16540         }
16541         else {
16542             ts.forEach(declarations, function (member) {
16543                 if (ts.isAccessor(member)
16544                     && hasModifier(member, 32 /* Static */) === hasModifier(accessor, 32 /* Static */)) {
16545                     var memberName = getPropertyNameForPropertyNameNode(member.name);
16546                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
16547                     if (memberName === accessorName) {
16548                         if (!firstAccessor) {
16549                             firstAccessor = member;
16550                         }
16551                         else if (!secondAccessor) {
16552                             secondAccessor = member;
16553                         }
16554                         if (member.kind === 163 /* GetAccessor */ && !getAccessor) {
16555                             // eslint-disable-next-line
16556                             getAccessor = member;
16557                         }
16558                         if (member.kind === 164 /* SetAccessor */ && !setAccessor) {
16559                             // eslint-disable-next-line
16560                             setAccessor = member;
16561                         }
16562                     }
16563                 }
16564             });
16565         }
16566         return {
16567             firstAccessor: firstAccessor,
16568             secondAccessor: secondAccessor,
16569             getAccessor: getAccessor,
16570             setAccessor: setAccessor
16571         };
16572     }
16573     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
16574     /**
16575      * Gets the effective type annotation of a variable, parameter, or property. If the node was
16576      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
16577      * functions only the JSDoc case.
16578      */
16579     function getEffectiveTypeAnnotationNode(node) {
16580         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
16581             return undefined;
16582         var type = node.type;
16583         if (type || !isInJSFile(node))
16584             return type;
16585         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
16586     }
16587     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
16588     function getTypeAnnotationNode(node) {
16589         return node.type;
16590     }
16591     ts.getTypeAnnotationNode = getTypeAnnotationNode;
16592     /**
16593      * Gets the effective return type annotation of a signature. If the node was parsed in a
16594      * JavaScript file, gets the return type annotation from JSDoc.
16595      */
16596     function getEffectiveReturnTypeNode(node) {
16597         return ts.isJSDocSignature(node) ?
16598             node.type && node.type.typeExpression && node.type.typeExpression.type :
16599             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
16600     }
16601     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
16602     function getJSDocTypeParameterDeclarations(node) {
16603         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
16604     }
16605     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
16606     /** template tags are only available when a typedef isn't already using them */
16607     function isNonTypeAliasTemplate(tag) {
16608         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 303 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
16609     }
16610     /**
16611      * Gets the effective type annotation of the value parameter of a set accessor. If the node
16612      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
16613      */
16614     function getEffectiveSetAccessorTypeAnnotationNode(node) {
16615         var parameter = getSetAccessorValueParameter(node);
16616         return parameter && getEffectiveTypeAnnotationNode(parameter);
16617     }
16618     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
16619     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
16620         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
16621     }
16622     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
16623     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
16624         // If the leading comments start on different line than the start of node, write new line
16625         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
16626             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
16627             writer.writeLine();
16628         }
16629     }
16630     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
16631     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
16632         // If the leading comments start on different line than the start of node, write new line
16633         if (pos !== commentPos &&
16634             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
16635             writer.writeLine();
16636         }
16637     }
16638     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
16639     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
16640         if (comments && comments.length > 0) {
16641             if (leadingSeparator) {
16642                 writer.writeSpace(" ");
16643             }
16644             var emitInterveningSeparator = false;
16645             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
16646                 var comment = comments_1[_i];
16647                 if (emitInterveningSeparator) {
16648                     writer.writeSpace(" ");
16649                     emitInterveningSeparator = false;
16650                 }
16651                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
16652                 if (comment.hasTrailingNewLine) {
16653                     writer.writeLine();
16654                 }
16655                 else {
16656                     emitInterveningSeparator = true;
16657                 }
16658             }
16659             if (emitInterveningSeparator && trailingSeparator) {
16660                 writer.writeSpace(" ");
16661             }
16662         }
16663     }
16664     ts.emitComments = emitComments;
16665     /**
16666      * Detached comment is a comment at the top of file or function body that is separated from
16667      * the next statement by space.
16668      */
16669     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
16670         var leadingComments;
16671         var currentDetachedCommentInfo;
16672         if (removeComments) {
16673             // removeComments is true, only reserve pinned comment at the top of file
16674             // For example:
16675             //      /*! Pinned Comment */
16676             //
16677             //      var x = 10;
16678             if (node.pos === 0) {
16679                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
16680             }
16681         }
16682         else {
16683             // removeComments is false, just get detached as normal and bypass the process to filter comment
16684             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
16685         }
16686         if (leadingComments) {
16687             var detachedComments = [];
16688             var lastComment = void 0;
16689             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
16690                 var comment = leadingComments_1[_i];
16691                 if (lastComment) {
16692                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
16693                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
16694                     if (commentLine >= lastCommentLine + 2) {
16695                         // There was a blank line between the last comment and this comment.  This
16696                         // comment is not part of the copyright comments.  Return what we have so
16697                         // far.
16698                         break;
16699                     }
16700                 }
16701                 detachedComments.push(comment);
16702                 lastComment = comment;
16703             }
16704             if (detachedComments.length) {
16705                 // All comments look like they could have been part of the copyright header.  Make
16706                 // sure there is at least one blank line between it and the node.  If not, it's not
16707                 // a copyright header.
16708                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
16709                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
16710                 if (nodeLine >= lastCommentLine + 2) {
16711                     // Valid detachedComments
16712                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
16713                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
16714                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
16715                 }
16716             }
16717         }
16718         return currentDetachedCommentInfo;
16719         function isPinnedCommentLocal(comment) {
16720             return isPinnedComment(text, comment.pos);
16721         }
16722     }
16723     ts.emitDetachedComments = emitDetachedComments;
16724     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
16725         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
16726             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
16727             var lineCount = lineMap.length;
16728             var firstCommentLineIndent = void 0;
16729             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
16730                 var nextLineStart = (currentLine + 1) === lineCount
16731                     ? text.length + 1
16732                     : lineMap[currentLine + 1];
16733                 if (pos !== commentPos) {
16734                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
16735                     if (firstCommentLineIndent === undefined) {
16736                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
16737                     }
16738                     // These are number of spaces writer is going to write at current indent
16739                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
16740                     // Number of spaces we want to be writing
16741                     // eg: Assume writer indent
16742                     // module m {
16743                     //         /* starts at character 9 this is line 1
16744                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
16745                     //   More left indented comment */                            --2  = 8 - 8 + 2
16746                     //     class c { }
16747                     // }
16748                     // module m {
16749                     //     /* this is line 1 -- Assume current writer indent 8
16750                     //      * line                                                --3 = 8 - 4 + 5
16751                     //            More right indented comment */                  --4 = 8 - 4 + 11
16752                     //     class c { }
16753                     // }
16754                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
16755                     if (spacesToEmit > 0) {
16756                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
16757                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
16758                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
16759                         writer.rawWrite(indentSizeSpaceString);
16760                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
16761                         while (numberOfSingleSpacesToEmit) {
16762                             writer.rawWrite(" ");
16763                             numberOfSingleSpacesToEmit--;
16764                         }
16765                     }
16766                     else {
16767                         // No spaces to emit write empty string
16768                         writer.rawWrite("");
16769                     }
16770                 }
16771                 // Write the comment line text
16772                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
16773                 pos = nextLineStart;
16774             }
16775         }
16776         else {
16777             // Single line comment of style //....
16778             writer.writeComment(text.substring(commentPos, commentEnd));
16779         }
16780     }
16781     ts.writeCommentRange = writeCommentRange;
16782     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
16783         var end = Math.min(commentEnd, nextLineStart - 1);
16784         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
16785         if (currentLineText) {
16786             // trimmed forward and ending spaces text
16787             writer.writeComment(currentLineText);
16788             if (end !== commentEnd) {
16789                 writer.writeLine();
16790             }
16791         }
16792         else {
16793             // Empty string - make sure we write empty line
16794             writer.rawWrite(newLine);
16795         }
16796     }
16797     function calculateIndent(text, pos, end) {
16798         var currentLineIndent = 0;
16799         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
16800             if (text.charCodeAt(pos) === 9 /* tab */) {
16801                 // Tabs = TabSize = indent size and go to next tabStop
16802                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
16803             }
16804             else {
16805                 // Single space
16806                 currentLineIndent++;
16807             }
16808         }
16809         return currentLineIndent;
16810     }
16811     function hasModifiers(node) {
16812         return getModifierFlags(node) !== 0 /* None */;
16813     }
16814     ts.hasModifiers = hasModifiers;
16815     function hasModifier(node, flags) {
16816         return !!getSelectedModifierFlags(node, flags);
16817     }
16818     ts.hasModifier = hasModifier;
16819     function hasStaticModifier(node) {
16820         return hasModifier(node, 32 /* Static */);
16821     }
16822     ts.hasStaticModifier = hasStaticModifier;
16823     function hasReadonlyModifier(node) {
16824         return hasModifier(node, 64 /* Readonly */);
16825     }
16826     ts.hasReadonlyModifier = hasReadonlyModifier;
16827     function getSelectedModifierFlags(node, flags) {
16828         return getModifierFlags(node) & flags;
16829     }
16830     ts.getSelectedModifierFlags = getSelectedModifierFlags;
16831     function getModifierFlags(node) {
16832         if (node.kind >= 0 /* FirstToken */ && node.kind <= 152 /* LastToken */) {
16833             return 0 /* None */;
16834         }
16835         if (node.modifierFlagsCache & 536870912 /* HasComputedFlags */) {
16836             return node.modifierFlagsCache & ~536870912 /* HasComputedFlags */;
16837         }
16838         var flags = getModifierFlagsNoCache(node);
16839         node.modifierFlagsCache = flags | 536870912 /* HasComputedFlags */;
16840         return flags;
16841     }
16842     ts.getModifierFlags = getModifierFlags;
16843     function getModifierFlagsNoCache(node) {
16844         var flags = 0 /* None */;
16845         if (node.modifiers) {
16846             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
16847                 var modifier = _a[_i];
16848                 flags |= modifierToFlag(modifier.kind);
16849             }
16850         }
16851         if (isInJSFile(node) && !!node.parent) {
16852             // getModifierFlagsNoCache should only be called when parent pointers are set,
16853             // or when !(node.flags & NodeFlags.Synthesized) && node.kind !== SyntaxKind.SourceFile)
16854             var tags = (ts.getJSDocPublicTag(node) ? 4 /* Public */ : 0 /* None */)
16855                 | (ts.getJSDocPrivateTag(node) ? 8 /* Private */ : 0 /* None */)
16856                 | (ts.getJSDocProtectedTag(node) ? 16 /* Protected */ : 0 /* None */)
16857                 | (ts.getJSDocReadonlyTag(node) ? 64 /* Readonly */ : 0 /* None */);
16858             flags |= tags;
16859         }
16860         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 75 /* Identifier */ && node.isInJSDocNamespace)) {
16861             flags |= 1 /* Export */;
16862         }
16863         return flags;
16864     }
16865     ts.getModifierFlagsNoCache = getModifierFlagsNoCache;
16866     function modifierToFlag(token) {
16867         switch (token) {
16868             case 120 /* StaticKeyword */: return 32 /* Static */;
16869             case 119 /* PublicKeyword */: return 4 /* Public */;
16870             case 118 /* ProtectedKeyword */: return 16 /* Protected */;
16871             case 117 /* PrivateKeyword */: return 8 /* Private */;
16872             case 122 /* AbstractKeyword */: return 128 /* Abstract */;
16873             case 89 /* ExportKeyword */: return 1 /* Export */;
16874             case 130 /* DeclareKeyword */: return 2 /* Ambient */;
16875             case 81 /* ConstKeyword */: return 2048 /* Const */;
16876             case 84 /* DefaultKeyword */: return 512 /* Default */;
16877             case 126 /* AsyncKeyword */: return 256 /* Async */;
16878             case 138 /* ReadonlyKeyword */: return 64 /* Readonly */;
16879         }
16880         return 0 /* None */;
16881     }
16882     ts.modifierToFlag = modifierToFlag;
16883     function isLogicalOperator(token) {
16884         return token === 56 /* BarBarToken */
16885             || token === 55 /* AmpersandAmpersandToken */
16886             || token === 53 /* ExclamationToken */;
16887     }
16888     ts.isLogicalOperator = isLogicalOperator;
16889     function isAssignmentOperator(token) {
16890         return token >= 62 /* FirstAssignment */ && token <= 74 /* LastAssignment */;
16891     }
16892     ts.isAssignmentOperator = isAssignmentOperator;
16893     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
16894     function tryGetClassExtendingExpressionWithTypeArguments(node) {
16895         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
16896         return cls && !cls.isImplements ? cls.class : undefined;
16897     }
16898     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
16899     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
16900         return ts.isExpressionWithTypeArguments(node)
16901             && ts.isHeritageClause(node.parent)
16902             && ts.isClassLike(node.parent.parent)
16903             ? { class: node.parent.parent, isImplements: node.parent.token === 113 /* ImplementsKeyword */ }
16904             : undefined;
16905     }
16906     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
16907     function isAssignmentExpression(node, excludeCompoundAssignment) {
16908         return ts.isBinaryExpression(node)
16909             && (excludeCompoundAssignment
16910                 ? node.operatorToken.kind === 62 /* EqualsToken */
16911                 : isAssignmentOperator(node.operatorToken.kind))
16912             && ts.isLeftHandSideExpression(node.left);
16913     }
16914     ts.isAssignmentExpression = isAssignmentExpression;
16915     function isDestructuringAssignment(node) {
16916         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
16917             var kind = node.left.kind;
16918             return kind === 193 /* ObjectLiteralExpression */
16919                 || kind === 192 /* ArrayLiteralExpression */;
16920         }
16921         return false;
16922     }
16923     ts.isDestructuringAssignment = isDestructuringAssignment;
16924     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
16925         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
16926     }
16927     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
16928     function isEntityNameExpression(node) {
16929         return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
16930     }
16931     ts.isEntityNameExpression = isEntityNameExpression;
16932     function getFirstIdentifier(node) {
16933         switch (node.kind) {
16934             case 75 /* Identifier */:
16935                 return node;
16936             case 153 /* QualifiedName */:
16937                 do {
16938                     node = node.left;
16939                 } while (node.kind !== 75 /* Identifier */);
16940                 return node;
16941             case 194 /* PropertyAccessExpression */:
16942                 do {
16943                     node = node.expression;
16944                 } while (node.kind !== 75 /* Identifier */);
16945                 return node;
16946         }
16947     }
16948     ts.getFirstIdentifier = getFirstIdentifier;
16949     function isDottedName(node) {
16950         return node.kind === 75 /* Identifier */ || node.kind === 104 /* ThisKeyword */ || node.kind === 102 /* SuperKeyword */ ||
16951             node.kind === 194 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
16952             node.kind === 200 /* ParenthesizedExpression */ && isDottedName(node.expression);
16953     }
16954     ts.isDottedName = isDottedName;
16955     function isPropertyAccessEntityNameExpression(node) {
16956         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
16957     }
16958     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
16959     function tryGetPropertyAccessOrIdentifierToString(expr) {
16960         if (ts.isPropertyAccessExpression(expr)) {
16961             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
16962             if (baseStr !== undefined) {
16963                 return baseStr + "." + expr.name;
16964             }
16965         }
16966         else if (ts.isIdentifier(expr)) {
16967             return ts.unescapeLeadingUnderscores(expr.escapedText);
16968         }
16969         return undefined;
16970     }
16971     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
16972     function isPrototypeAccess(node) {
16973         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
16974     }
16975     ts.isPrototypeAccess = isPrototypeAccess;
16976     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
16977         return (node.parent.kind === 153 /* QualifiedName */ && node.parent.right === node) ||
16978             (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node);
16979     }
16980     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
16981     function isEmptyObjectLiteral(expression) {
16982         return expression.kind === 193 /* ObjectLiteralExpression */ &&
16983             expression.properties.length === 0;
16984     }
16985     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
16986     function isEmptyArrayLiteral(expression) {
16987         return expression.kind === 192 /* ArrayLiteralExpression */ &&
16988             expression.elements.length === 0;
16989     }
16990     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
16991     function getLocalSymbolForExportDefault(symbol) {
16992         return isExportDefaultSymbol(symbol) ? symbol.declarations[0].localSymbol : undefined;
16993     }
16994     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
16995     function isExportDefaultSymbol(symbol) {
16996         return symbol && ts.length(symbol.declarations) > 0 && hasModifier(symbol.declarations[0], 512 /* Default */);
16997     }
16998     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
16999     function tryExtractTSExtension(fileName) {
17000         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17001     }
17002     ts.tryExtractTSExtension = tryExtractTSExtension;
17003     /**
17004      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17005      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17006      */
17007     function getExpandedCharCodes(input) {
17008         var output = [];
17009         var length = input.length;
17010         for (var i = 0; i < length; i++) {
17011             var charCode = input.charCodeAt(i);
17012             // handle utf8
17013             if (charCode < 0x80) {
17014                 output.push(charCode);
17015             }
17016             else if (charCode < 0x800) {
17017                 output.push((charCode >> 6) | 192);
17018                 output.push((charCode & 63) | 128);
17019             }
17020             else if (charCode < 0x10000) {
17021                 output.push((charCode >> 12) | 224);
17022                 output.push(((charCode >> 6) & 63) | 128);
17023                 output.push((charCode & 63) | 128);
17024             }
17025             else if (charCode < 0x20000) {
17026                 output.push((charCode >> 18) | 240);
17027                 output.push(((charCode >> 12) & 63) | 128);
17028                 output.push(((charCode >> 6) & 63) | 128);
17029                 output.push((charCode & 63) | 128);
17030             }
17031             else {
17032                 ts.Debug.assert(false, "Unexpected code point");
17033             }
17034         }
17035         return output;
17036     }
17037     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17038     /**
17039      * Converts a string to a base-64 encoded ASCII string.
17040      */
17041     function convertToBase64(input) {
17042         var result = "";
17043         var charCodes = getExpandedCharCodes(input);
17044         var i = 0;
17045         var length = charCodes.length;
17046         var byte1, byte2, byte3, byte4;
17047         while (i < length) {
17048             // Convert every 6-bits in the input 3 character points
17049             // into a base64 digit
17050             byte1 = charCodes[i] >> 2;
17051             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17052             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17053             byte4 = charCodes[i + 2] & 63;
17054             // We are out of characters in the input, set the extra
17055             // digits to 64 (padding character).
17056             if (i + 1 >= length) {
17057                 byte3 = byte4 = 64;
17058             }
17059             else if (i + 2 >= length) {
17060                 byte4 = 64;
17061             }
17062             // Write to the output
17063             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17064             i += 3;
17065         }
17066         return result;
17067     }
17068     ts.convertToBase64 = convertToBase64;
17069     function getStringFromExpandedCharCodes(codes) {
17070         var output = "";
17071         var i = 0;
17072         var length = codes.length;
17073         while (i < length) {
17074             var charCode = codes[i];
17075             if (charCode < 0x80) {
17076                 output += String.fromCharCode(charCode);
17077                 i++;
17078             }
17079             else if ((charCode & 192) === 192) {
17080                 var value = charCode & 63;
17081                 i++;
17082                 var nextCode = codes[i];
17083                 while ((nextCode & 192) === 128) {
17084                     value = (value << 6) | (nextCode & 63);
17085                     i++;
17086                     nextCode = codes[i];
17087                 }
17088                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17089                 output += String.fromCharCode(value);
17090             }
17091             else {
17092                 // We don't want to kill the process when decoding fails (due to a following char byte not
17093                 // following a leading char), so we just print the (bad) value
17094                 output += String.fromCharCode(charCode);
17095                 i++;
17096             }
17097         }
17098         return output;
17099     }
17100     function base64encode(host, input) {
17101         if (host && host.base64encode) {
17102             return host.base64encode(input);
17103         }
17104         return convertToBase64(input);
17105     }
17106     ts.base64encode = base64encode;
17107     function base64decode(host, input) {
17108         if (host && host.base64decode) {
17109             return host.base64decode(input);
17110         }
17111         var length = input.length;
17112         var expandedCharCodes = [];
17113         var i = 0;
17114         while (i < length) {
17115             // Stop decoding once padding characters are present
17116             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17117                 break;
17118             }
17119             // convert 4 input digits into three characters, ignoring padding characters at the end
17120             var ch1 = base64Digits.indexOf(input[i]);
17121             var ch2 = base64Digits.indexOf(input[i + 1]);
17122             var ch3 = base64Digits.indexOf(input[i + 2]);
17123             var ch4 = base64Digits.indexOf(input[i + 3]);
17124             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17125             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17126             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17127             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17128                 expandedCharCodes.push(code1);
17129             }
17130             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17131                 expandedCharCodes.push(code1, code2);
17132             }
17133             else {
17134                 expandedCharCodes.push(code1, code2, code3);
17135             }
17136             i += 4;
17137         }
17138         return getStringFromExpandedCharCodes(expandedCharCodes);
17139     }
17140     ts.base64decode = base64decode;
17141     function readJson(path, host) {
17142         try {
17143             var jsonText = host.readFile(path);
17144             if (!jsonText)
17145                 return {};
17146             var result = ts.parseConfigFileTextToJson(path, jsonText);
17147             if (result.error) {
17148                 return {};
17149             }
17150             return result.config;
17151         }
17152         catch (e) {
17153             // gracefully handle if readFile fails or returns not JSON
17154             return {};
17155         }
17156     }
17157     ts.readJson = readJson;
17158     function directoryProbablyExists(directoryName, host) {
17159         // if host does not support 'directoryExists' assume that directory will exist
17160         return !host.directoryExists || host.directoryExists(directoryName);
17161     }
17162     ts.directoryProbablyExists = directoryProbablyExists;
17163     var carriageReturnLineFeed = "\r\n";
17164     var lineFeed = "\n";
17165     function getNewLineCharacter(options, getNewLine) {
17166         switch (options.newLine) {
17167             case 0 /* CarriageReturnLineFeed */:
17168                 return carriageReturnLineFeed;
17169             case 1 /* LineFeed */:
17170                 return lineFeed;
17171         }
17172         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17173     }
17174     ts.getNewLineCharacter = getNewLineCharacter;
17175     /**
17176      * Creates a new TextRange from the provided pos and end.
17177      *
17178      * @param pos The start position.
17179      * @param end The end position.
17180      */
17181     function createRange(pos, end) {
17182         if (end === void 0) { end = pos; }
17183         ts.Debug.assert(end >= pos || end === -1);
17184         return { pos: pos, end: end };
17185     }
17186     ts.createRange = createRange;
17187     /**
17188      * Creates a new TextRange from a provided range with a new end position.
17189      *
17190      * @param range A TextRange.
17191      * @param end The new end position.
17192      */
17193     function moveRangeEnd(range, end) {
17194         return createRange(range.pos, end);
17195     }
17196     ts.moveRangeEnd = moveRangeEnd;
17197     /**
17198      * Creates a new TextRange from a provided range with a new start position.
17199      *
17200      * @param range A TextRange.
17201      * @param pos The new Start position.
17202      */
17203     function moveRangePos(range, pos) {
17204         return createRange(pos, range.end);
17205     }
17206     ts.moveRangePos = moveRangePos;
17207     /**
17208      * Moves the start position of a range past any decorators.
17209      */
17210     function moveRangePastDecorators(node) {
17211         return node.decorators && node.decorators.length > 0
17212             ? moveRangePos(node, node.decorators.end)
17213             : node;
17214     }
17215     ts.moveRangePastDecorators = moveRangePastDecorators;
17216     /**
17217      * Moves the start position of a range past any decorators or modifiers.
17218      */
17219     function moveRangePastModifiers(node) {
17220         return node.modifiers && node.modifiers.length > 0
17221             ? moveRangePos(node, node.modifiers.end)
17222             : moveRangePastDecorators(node);
17223     }
17224     ts.moveRangePastModifiers = moveRangePastModifiers;
17225     /**
17226      * Determines whether a TextRange has the same start and end positions.
17227      *
17228      * @param range A TextRange.
17229      */
17230     function isCollapsedRange(range) {
17231         return range.pos === range.end;
17232     }
17233     ts.isCollapsedRange = isCollapsedRange;
17234     /**
17235      * Creates a new TextRange for a token at the provides start position.
17236      *
17237      * @param pos The start position.
17238      * @param token The token.
17239      */
17240     function createTokenRange(pos, token) {
17241         return createRange(pos, pos + ts.tokenToString(token).length);
17242     }
17243     ts.createTokenRange = createTokenRange;
17244     function rangeIsOnSingleLine(range, sourceFile) {
17245         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17246     }
17247     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17248     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17249         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17250     }
17251     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17252     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17253         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17254     }
17255     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17256     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17257         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17258     }
17259     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17260     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17261         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17262     }
17263     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17264     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17265         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17266         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17267     }
17268     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17269     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17270         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17271     }
17272     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17273     function isNodeArrayMultiLine(list, sourceFile) {
17274         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17275     }
17276     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17277     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17278         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17279     }
17280     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17281     function getStartPositionOfRange(range, sourceFile, includeComments) {
17282         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17283     }
17284     ts.getStartPositionOfRange = getStartPositionOfRange;
17285     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17286         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17287         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17288         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17289     }
17290     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17291     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17292         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17293         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17294     }
17295     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17296     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17297         if (stopPos === void 0) { stopPos = 0; }
17298         while (pos-- > stopPos) {
17299             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17300                 return pos;
17301             }
17302         }
17303     }
17304     /**
17305      * Determines whether a name was originally the declaration name of an enum or namespace
17306      * declaration.
17307      */
17308     function isDeclarationNameOfEnumOrNamespace(node) {
17309         var parseNode = ts.getParseTreeNode(node);
17310         if (parseNode) {
17311             switch (parseNode.parent.kind) {
17312                 case 248 /* EnumDeclaration */:
17313                 case 249 /* ModuleDeclaration */:
17314                     return parseNode === parseNode.parent.name;
17315             }
17316         }
17317         return false;
17318     }
17319     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17320     function getInitializedVariables(node) {
17321         return ts.filter(node.declarations, isInitializedVariable);
17322     }
17323     ts.getInitializedVariables = getInitializedVariables;
17324     function isInitializedVariable(node) {
17325         return node.initializer !== undefined;
17326     }
17327     function isWatchSet(options) {
17328         // Firefox has Object.prototype.watch
17329         return options.watch && options.hasOwnProperty("watch");
17330     }
17331     ts.isWatchSet = isWatchSet;
17332     function closeFileWatcher(watcher) {
17333         watcher.close();
17334     }
17335     ts.closeFileWatcher = closeFileWatcher;
17336     function getCheckFlags(symbol) {
17337         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
17338     }
17339     ts.getCheckFlags = getCheckFlags;
17340     function getDeclarationModifierFlagsFromSymbol(s) {
17341         if (s.valueDeclaration) {
17342             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
17343             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
17344         }
17345         if (getCheckFlags(s) & 6 /* Synthetic */) {
17346             var checkFlags = s.checkFlags;
17347             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
17348                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
17349                     16 /* Protected */;
17350             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
17351             return accessModifier | staticModifier;
17352         }
17353         if (s.flags & 4194304 /* Prototype */) {
17354             return 4 /* Public */ | 32 /* Static */;
17355         }
17356         return 0;
17357     }
17358     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
17359     function skipAlias(symbol, checker) {
17360         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
17361     }
17362     ts.skipAlias = skipAlias;
17363     /** See comment on `declareModuleMember` in `binder.ts`. */
17364     function getCombinedLocalAndExportSymbolFlags(symbol) {
17365         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
17366     }
17367     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
17368     function isWriteOnlyAccess(node) {
17369         return accessKind(node) === 1 /* Write */;
17370     }
17371     ts.isWriteOnlyAccess = isWriteOnlyAccess;
17372     function isWriteAccess(node) {
17373         return accessKind(node) !== 0 /* Read */;
17374     }
17375     ts.isWriteAccess = isWriteAccess;
17376     var AccessKind;
17377     (function (AccessKind) {
17378         /** Only reads from a variable. */
17379         AccessKind[AccessKind["Read"] = 0] = "Read";
17380         /** Only writes to a variable without using the result. E.g.: `x++;`. */
17381         AccessKind[AccessKind["Write"] = 1] = "Write";
17382         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
17383         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
17384     })(AccessKind || (AccessKind = {}));
17385     function accessKind(node) {
17386         var parent = node.parent;
17387         if (!parent)
17388             return 0 /* Read */;
17389         switch (parent.kind) {
17390             case 200 /* ParenthesizedExpression */:
17391                 return accessKind(parent);
17392             case 208 /* PostfixUnaryExpression */:
17393             case 207 /* PrefixUnaryExpression */:
17394                 var operator = parent.operator;
17395                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
17396             case 209 /* BinaryExpression */:
17397                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
17398                 return left === node && isAssignmentOperator(operatorToken.kind) ?
17399                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
17400                     : 0 /* Read */;
17401             case 194 /* PropertyAccessExpression */:
17402                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
17403             case 281 /* PropertyAssignment */: {
17404                 var parentAccess = accessKind(parent.parent);
17405                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
17406                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
17407             }
17408             case 282 /* ShorthandPropertyAssignment */:
17409                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
17410                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
17411             case 192 /* ArrayLiteralExpression */:
17412                 return accessKind(parent);
17413             default:
17414                 return 0 /* Read */;
17415         }
17416         function writeOrReadWrite() {
17417             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
17418             return parent.parent && skipParenthesesUp(parent.parent).kind === 226 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
17419         }
17420     }
17421     function reverseAccessKind(a) {
17422         switch (a) {
17423             case 0 /* Read */:
17424                 return 1 /* Write */;
17425             case 1 /* Write */:
17426                 return 0 /* Read */;
17427             case 2 /* ReadWrite */:
17428                 return 2 /* ReadWrite */;
17429             default:
17430                 return ts.Debug.assertNever(a);
17431         }
17432     }
17433     function compareDataObjects(dst, src) {
17434         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
17435             return false;
17436         }
17437         for (var e in dst) {
17438             if (typeof dst[e] === "object") {
17439                 if (!compareDataObjects(dst[e], src[e])) {
17440                     return false;
17441                 }
17442             }
17443             else if (typeof dst[e] !== "function") {
17444                 if (dst[e] !== src[e]) {
17445                     return false;
17446                 }
17447             }
17448         }
17449         return true;
17450     }
17451     ts.compareDataObjects = compareDataObjects;
17452     /**
17453      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
17454      */
17455     function clearMap(map, onDeleteValue) {
17456         // Remove all
17457         map.forEach(onDeleteValue);
17458         map.clear();
17459     }
17460     ts.clearMap = clearMap;
17461     /**
17462      * Mutates the map with newMap such that keys in map will be same as newMap.
17463      */
17464     function mutateMapSkippingNewValues(map, newMap, options) {
17465         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
17466         // Needs update
17467         map.forEach(function (existingValue, key) {
17468             var valueInNewMap = newMap.get(key);
17469             // Not present any more in new map, remove it
17470             if (valueInNewMap === undefined) {
17471                 map.delete(key);
17472                 onDeleteValue(existingValue, key);
17473             }
17474             // If present notify about existing values
17475             else if (onExistingValue) {
17476                 onExistingValue(existingValue, valueInNewMap, key);
17477             }
17478         });
17479     }
17480     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
17481     /**
17482      * Mutates the map with newMap such that keys in map will be same as newMap.
17483      */
17484     function mutateMap(map, newMap, options) {
17485         // Needs update
17486         mutateMapSkippingNewValues(map, newMap, options);
17487         var createNewValue = options.createNewValue;
17488         // Add new values that are not already present
17489         newMap.forEach(function (valueInNewMap, key) {
17490             if (!map.has(key)) {
17491                 // New values
17492                 map.set(key, createNewValue(key, valueInNewMap));
17493             }
17494         });
17495     }
17496     ts.mutateMap = mutateMap;
17497     // Return true if the given type is the constructor type for an abstract class
17498     function isAbstractConstructorType(type) {
17499         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
17500     }
17501     ts.isAbstractConstructorType = isAbstractConstructorType;
17502     function isAbstractConstructorSymbol(symbol) {
17503         if (symbol.flags & 32 /* Class */) {
17504             var declaration = getClassLikeDeclarationOfSymbol(symbol);
17505             return !!declaration && hasModifier(declaration, 128 /* Abstract */);
17506         }
17507         return false;
17508     }
17509     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
17510     function getClassLikeDeclarationOfSymbol(symbol) {
17511         return ts.find(symbol.declarations, ts.isClassLike);
17512     }
17513     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
17514     function getObjectFlags(type) {
17515         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
17516     }
17517     ts.getObjectFlags = getObjectFlags;
17518     function typeHasCallOrConstructSignatures(type, checker) {
17519         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
17520     }
17521     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
17522     function forSomeAncestorDirectory(directory, callback) {
17523         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
17524     }
17525     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
17526     function isUMDExportSymbol(symbol) {
17527         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
17528     }
17529     ts.isUMDExportSymbol = isUMDExportSymbol;
17530     function showModuleSpecifier(_a) {
17531         var moduleSpecifier = _a.moduleSpecifier;
17532         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
17533     }
17534     ts.showModuleSpecifier = showModuleSpecifier;
17535     function getLastChild(node) {
17536         var lastChild;
17537         ts.forEachChild(node, function (child) {
17538             if (nodeIsPresent(child))
17539                 lastChild = child;
17540         }, function (children) {
17541             // As an optimization, jump straight to the end of the list.
17542             for (var i = children.length - 1; i >= 0; i--) {
17543                 if (nodeIsPresent(children[i])) {
17544                     lastChild = children[i];
17545                     break;
17546                 }
17547             }
17548         });
17549         return lastChild;
17550     }
17551     ts.getLastChild = getLastChild;
17552     function addToSeen(seen, key, value) {
17553         if (value === void 0) { value = true; }
17554         key = String(key);
17555         if (seen.has(key)) {
17556             return false;
17557         }
17558         seen.set(key, value);
17559         return true;
17560     }
17561     ts.addToSeen = addToSeen;
17562     function isObjectTypeDeclaration(node) {
17563         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
17564     }
17565     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
17566     function isTypeNodeKind(kind) {
17567         return (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */)
17568             || kind === 125 /* AnyKeyword */
17569             || kind === 148 /* UnknownKeyword */
17570             || kind === 140 /* NumberKeyword */
17571             || kind === 151 /* BigIntKeyword */
17572             || kind === 141 /* ObjectKeyword */
17573             || kind === 128 /* BooleanKeyword */
17574             || kind === 143 /* StringKeyword */
17575             || kind === 144 /* SymbolKeyword */
17576             || kind === 104 /* ThisKeyword */
17577             || kind === 110 /* VoidKeyword */
17578             || kind === 146 /* UndefinedKeyword */
17579             || kind === 100 /* NullKeyword */
17580             || kind === 137 /* NeverKeyword */
17581             || kind === 216 /* ExpressionWithTypeArguments */
17582             || kind === 295 /* JSDocAllType */
17583             || kind === 296 /* JSDocUnknownType */
17584             || kind === 297 /* JSDocNullableType */
17585             || kind === 298 /* JSDocNonNullableType */
17586             || kind === 299 /* JSDocOptionalType */
17587             || kind === 300 /* JSDocFunctionType */
17588             || kind === 301 /* JSDocVariadicType */;
17589     }
17590     ts.isTypeNodeKind = isTypeNodeKind;
17591     function isAccessExpression(node) {
17592         return node.kind === 194 /* PropertyAccessExpression */ || node.kind === 195 /* ElementAccessExpression */;
17593     }
17594     ts.isAccessExpression = isAccessExpression;
17595     function getNameOfAccessExpression(node) {
17596         if (node.kind === 194 /* PropertyAccessExpression */) {
17597             return node.name;
17598         }
17599         ts.Debug.assert(node.kind === 195 /* ElementAccessExpression */);
17600         return node.argumentExpression;
17601     }
17602     ts.getNameOfAccessExpression = getNameOfAccessExpression;
17603     function isBundleFileTextLike(section) {
17604         switch (section.kind) {
17605             case "text" /* Text */:
17606             case "internal" /* Internal */:
17607                 return true;
17608             default:
17609                 return false;
17610         }
17611     }
17612     ts.isBundleFileTextLike = isBundleFileTextLike;
17613     function isNamedImportsOrExports(node) {
17614         return node.kind === 257 /* NamedImports */ || node.kind === 261 /* NamedExports */;
17615     }
17616     ts.isNamedImportsOrExports = isNamedImportsOrExports;
17617     function Symbol(flags, name) {
17618         this.flags = flags;
17619         this.escapedName = name;
17620         this.declarations = undefined;
17621         this.valueDeclaration = undefined;
17622         this.id = undefined;
17623         this.mergeId = undefined;
17624         this.parent = undefined;
17625     }
17626     function Type(checker, flags) {
17627         this.flags = flags;
17628         if (ts.Debug.isDebugging) {
17629             this.checker = checker;
17630         }
17631     }
17632     function Signature(checker, flags) {
17633         this.flags = flags;
17634         if (ts.Debug.isDebugging) {
17635             this.checker = checker;
17636         }
17637     }
17638     function Node(kind, pos, end) {
17639         this.pos = pos;
17640         this.end = end;
17641         this.kind = kind;
17642         this.id = 0;
17643         this.flags = 0 /* None */;
17644         this.modifierFlagsCache = 0 /* None */;
17645         this.transformFlags = 0 /* None */;
17646         this.parent = undefined;
17647         this.original = undefined;
17648     }
17649     function Token(kind, pos, end) {
17650         this.pos = pos;
17651         this.end = end;
17652         this.kind = kind;
17653         this.id = 0;
17654         this.flags = 0 /* None */;
17655         this.transformFlags = 0 /* None */;
17656         this.parent = undefined;
17657     }
17658     function Identifier(kind, pos, end) {
17659         this.pos = pos;
17660         this.end = end;
17661         this.kind = kind;
17662         this.id = 0;
17663         this.flags = 0 /* None */;
17664         this.transformFlags = 0 /* None */;
17665         this.parent = undefined;
17666         this.original = undefined;
17667         this.flowNode = undefined;
17668     }
17669     function SourceMapSource(fileName, text, skipTrivia) {
17670         this.fileName = fileName;
17671         this.text = text;
17672         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
17673     }
17674     // eslint-disable-next-line prefer-const
17675     ts.objectAllocator = {
17676         getNodeConstructor: function () { return Node; },
17677         getTokenConstructor: function () { return Token; },
17678         getIdentifierConstructor: function () { return Identifier; },
17679         getPrivateIdentifierConstructor: function () { return Node; },
17680         getSourceFileConstructor: function () { return Node; },
17681         getSymbolConstructor: function () { return Symbol; },
17682         getTypeConstructor: function () { return Type; },
17683         getSignatureConstructor: function () { return Signature; },
17684         getSourceMapSourceConstructor: function () { return SourceMapSource; },
17685     };
17686     function setObjectAllocator(alloc) {
17687         ts.objectAllocator = alloc;
17688     }
17689     ts.setObjectAllocator = setObjectAllocator;
17690     function formatStringFromArgs(text, args, baseIndex) {
17691         if (baseIndex === void 0) { baseIndex = 0; }
17692         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
17693     }
17694     ts.formatStringFromArgs = formatStringFromArgs;
17695     /* @internal */
17696     function setLocalizedDiagnosticMessages(messages) {
17697         ts.localizedDiagnosticMessages = messages;
17698     }
17699     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
17700     function getLocaleSpecificMessage(message) {
17701         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
17702     }
17703     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
17704     function createFileDiagnostic(file, start, length, message) {
17705         ts.Debug.assertGreaterThanOrEqual(start, 0);
17706         ts.Debug.assertGreaterThanOrEqual(length, 0);
17707         if (file) {
17708             ts.Debug.assertLessThanOrEqual(start, file.text.length);
17709             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
17710         }
17711         var text = getLocaleSpecificMessage(message);
17712         if (arguments.length > 4) {
17713             text = formatStringFromArgs(text, arguments, 4);
17714         }
17715         return {
17716             file: file,
17717             start: start,
17718             length: length,
17719             messageText: text,
17720             category: message.category,
17721             code: message.code,
17722             reportsUnnecessary: message.reportsUnnecessary,
17723         };
17724     }
17725     ts.createFileDiagnostic = createFileDiagnostic;
17726     function formatMessage(_dummy, message) {
17727         var text = getLocaleSpecificMessage(message);
17728         if (arguments.length > 2) {
17729             text = formatStringFromArgs(text, arguments, 2);
17730         }
17731         return text;
17732     }
17733     ts.formatMessage = formatMessage;
17734     function createCompilerDiagnostic(message) {
17735         var text = getLocaleSpecificMessage(message);
17736         if (arguments.length > 1) {
17737             text = formatStringFromArgs(text, arguments, 1);
17738         }
17739         return {
17740             file: undefined,
17741             start: undefined,
17742             length: undefined,
17743             messageText: text,
17744             category: message.category,
17745             code: message.code,
17746             reportsUnnecessary: message.reportsUnnecessary,
17747         };
17748     }
17749     ts.createCompilerDiagnostic = createCompilerDiagnostic;
17750     function createCompilerDiagnosticFromMessageChain(chain) {
17751         return {
17752             file: undefined,
17753             start: undefined,
17754             length: undefined,
17755             code: chain.code,
17756             category: chain.category,
17757             messageText: chain.next ? chain : chain.messageText,
17758         };
17759     }
17760     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
17761     function chainDiagnosticMessages(details, message) {
17762         var text = getLocaleSpecificMessage(message);
17763         if (arguments.length > 2) {
17764             text = formatStringFromArgs(text, arguments, 2);
17765         }
17766         return {
17767             messageText: text,
17768             category: message.category,
17769             code: message.code,
17770             next: details === undefined || Array.isArray(details) ? details : [details]
17771         };
17772     }
17773     ts.chainDiagnosticMessages = chainDiagnosticMessages;
17774     function concatenateDiagnosticMessageChains(headChain, tailChain) {
17775         var lastChain = headChain;
17776         while (lastChain.next) {
17777             lastChain = lastChain.next[0];
17778         }
17779         lastChain.next = [tailChain];
17780     }
17781     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
17782     function getDiagnosticFilePath(diagnostic) {
17783         return diagnostic.file ? diagnostic.file.path : undefined;
17784     }
17785     function compareDiagnostics(d1, d2) {
17786         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
17787             compareRelatedInformation(d1, d2) ||
17788             0 /* EqualTo */;
17789     }
17790     ts.compareDiagnostics = compareDiagnostics;
17791     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
17792         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
17793             ts.compareValues(d1.start, d2.start) ||
17794             ts.compareValues(d1.length, d2.length) ||
17795             ts.compareValues(d1.code, d2.code) ||
17796             compareMessageText(d1.messageText, d2.messageText) ||
17797             0 /* EqualTo */;
17798     }
17799     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
17800     function compareRelatedInformation(d1, d2) {
17801         if (!d1.relatedInformation && !d2.relatedInformation) {
17802             return 0 /* EqualTo */;
17803         }
17804         if (d1.relatedInformation && d2.relatedInformation) {
17805             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
17806                 var d2i = d2.relatedInformation[index];
17807                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
17808             }) || 0 /* EqualTo */;
17809         }
17810         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
17811     }
17812     function compareMessageText(t1, t2) {
17813         if (typeof t1 === "string" && typeof t2 === "string") {
17814             return ts.compareStringsCaseSensitive(t1, t2);
17815         }
17816         else if (typeof t1 === "string") {
17817             return -1 /* LessThan */;
17818         }
17819         else if (typeof t2 === "string") {
17820             return 1 /* GreaterThan */;
17821         }
17822         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
17823         if (res) {
17824             return res;
17825         }
17826         if (!t1.next && !t2.next) {
17827             return 0 /* EqualTo */;
17828         }
17829         if (!t1.next) {
17830             return -1 /* LessThan */;
17831         }
17832         if (!t2.next) {
17833             return 1 /* GreaterThan */;
17834         }
17835         var len = Math.min(t1.next.length, t2.next.length);
17836         for (var i = 0; i < len; i++) {
17837             res = compareMessageText(t1.next[i], t2.next[i]);
17838             if (res) {
17839                 return res;
17840             }
17841         }
17842         if (t1.next.length < t2.next.length) {
17843             return -1 /* LessThan */;
17844         }
17845         else if (t1.next.length > t2.next.length) {
17846             return 1 /* GreaterThan */;
17847         }
17848         return 0 /* EqualTo */;
17849     }
17850     function getEmitScriptTarget(compilerOptions) {
17851         return compilerOptions.target || 0 /* ES3 */;
17852     }
17853     ts.getEmitScriptTarget = getEmitScriptTarget;
17854     function getEmitModuleKind(compilerOptions) {
17855         return typeof compilerOptions.module === "number" ?
17856             compilerOptions.module :
17857             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
17858     }
17859     ts.getEmitModuleKind = getEmitModuleKind;
17860     function getEmitModuleResolutionKind(compilerOptions) {
17861         var moduleResolution = compilerOptions.moduleResolution;
17862         if (moduleResolution === undefined) {
17863             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
17864         }
17865         return moduleResolution;
17866     }
17867     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
17868     function hasJsonModuleEmitEnabled(options) {
17869         switch (getEmitModuleKind(options)) {
17870             case ts.ModuleKind.CommonJS:
17871             case ts.ModuleKind.AMD:
17872             case ts.ModuleKind.ES2015:
17873             case ts.ModuleKind.ES2020:
17874             case ts.ModuleKind.ESNext:
17875                 return true;
17876             default:
17877                 return false;
17878         }
17879     }
17880     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
17881     function unreachableCodeIsError(options) {
17882         return options.allowUnreachableCode === false;
17883     }
17884     ts.unreachableCodeIsError = unreachableCodeIsError;
17885     function unusedLabelIsError(options) {
17886         return options.allowUnusedLabels === false;
17887     }
17888     ts.unusedLabelIsError = unusedLabelIsError;
17889     function getAreDeclarationMapsEnabled(options) {
17890         return !!(getEmitDeclarations(options) && options.declarationMap);
17891     }
17892     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
17893     function getAllowSyntheticDefaultImports(compilerOptions) {
17894         var moduleKind = getEmitModuleKind(compilerOptions);
17895         return compilerOptions.allowSyntheticDefaultImports !== undefined
17896             ? compilerOptions.allowSyntheticDefaultImports
17897             : compilerOptions.esModuleInterop ||
17898                 moduleKind === ts.ModuleKind.System;
17899     }
17900     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
17901     function getEmitDeclarations(compilerOptions) {
17902         return !!(compilerOptions.declaration || compilerOptions.composite);
17903     }
17904     ts.getEmitDeclarations = getEmitDeclarations;
17905     function isIncrementalCompilation(options) {
17906         return !!(options.incremental || options.composite);
17907     }
17908     ts.isIncrementalCompilation = isIncrementalCompilation;
17909     function getStrictOptionValue(compilerOptions, flag) {
17910         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
17911     }
17912     ts.getStrictOptionValue = getStrictOptionValue;
17913     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
17914         return oldOptions !== newOptions &&
17915             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17916     }
17917     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
17918     function compilerOptionsAffectEmit(newOptions, oldOptions) {
17919         return oldOptions !== newOptions &&
17920             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
17921     }
17922     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
17923     function getCompilerOptionValue(options, option) {
17924         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
17925     }
17926     ts.getCompilerOptionValue = getCompilerOptionValue;
17927     function hasZeroOrOneAsteriskCharacter(str) {
17928         var seenAsterisk = false;
17929         for (var i = 0; i < str.length; i++) {
17930             if (str.charCodeAt(i) === 42 /* asterisk */) {
17931                 if (!seenAsterisk) {
17932                     seenAsterisk = true;
17933                 }
17934                 else {
17935                     // have already seen asterisk
17936                     return false;
17937                 }
17938             }
17939         }
17940         return true;
17941     }
17942     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
17943     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
17944         var result = ts.createMap();
17945         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
17946             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
17947                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
17948             })));
17949         }));
17950         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
17951             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
17952             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName), commonResolved = _b[0], commonOriginal = _b[1];
17953             result.set(commonOriginal, commonResolved);
17954         }
17955         return result;
17956     }
17957     ts.discoverProbableSymlinks = discoverProbableSymlinks;
17958     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
17959         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
17960         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
17961         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
17962             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
17963             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
17964             aParts.pop();
17965             bParts.pop();
17966         }
17967         return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)];
17968     }
17969     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
17970     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
17971     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
17972         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
17973     }
17974     function stripLeadingDirectorySeparator(s) {
17975         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
17976     }
17977     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
17978         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
17979         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
17980     }
17981     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
17982     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
17983     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
17984     // proof.
17985     var reservedCharacterPattern = /[^\w\s\/]/g;
17986     function regExpEscape(text) {
17987         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
17988     }
17989     ts.regExpEscape = regExpEscape;
17990     function escapeRegExpCharacter(match) {
17991         return "\\" + match;
17992     }
17993     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
17994     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
17995     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
17996     var filesMatcher = {
17997         /**
17998          * Matches any single directory segment unless it is the last segment and a .min.js file
17999          * Breakdown:
18000          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18001          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18002          */
18003         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18004         /**
18005          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18006          * files or directories, does not match subdirectories that start with a . character
18007          */
18008         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18009         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18010     };
18011     var directoriesMatcher = {
18012         singleAsteriskRegexFragment: "[^/]*",
18013         /**
18014          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18015          * files or directories, does not match subdirectories that start with a . character
18016          */
18017         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18018         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18019     };
18020     var excludeMatcher = {
18021         singleAsteriskRegexFragment: "[^/]*",
18022         doubleAsteriskRegexFragment: "(/.+?)?",
18023         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18024     };
18025     var wildcardMatchers = {
18026         files: filesMatcher,
18027         directories: directoriesMatcher,
18028         exclude: excludeMatcher
18029     };
18030     function getRegularExpressionForWildcard(specs, basePath, usage) {
18031         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18032         if (!patterns || !patterns.length) {
18033             return undefined;
18034         }
18035         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18036         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18037         var terminator = usage === "exclude" ? "($|/)" : "$";
18038         return "^(" + pattern + ")" + terminator;
18039     }
18040     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18041     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18042         if (specs === undefined || specs.length === 0) {
18043             return undefined;
18044         }
18045         return ts.flatMap(specs, function (spec) {
18046             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18047         });
18048     }
18049     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18050     /**
18051      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18052      * and does not contain any glob characters itself.
18053      */
18054     function isImplicitGlob(lastPathComponent) {
18055         return !/[.*?]/.test(lastPathComponent);
18056     }
18057     ts.isImplicitGlob = isImplicitGlob;
18058     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18059         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18060         var subpattern = "";
18061         var hasWrittenComponent = false;
18062         var components = ts.getNormalizedPathComponents(spec, basePath);
18063         var lastComponent = ts.last(components);
18064         if (usage !== "exclude" && lastComponent === "**") {
18065             return undefined;
18066         }
18067         // getNormalizedPathComponents includes the separator for the root component.
18068         // We need to remove to create our regex correctly.
18069         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18070         if (isImplicitGlob(lastComponent)) {
18071             components.push("**", "*");
18072         }
18073         var optionalCount = 0;
18074         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18075             var component = components_1[_i];
18076             if (component === "**") {
18077                 subpattern += doubleAsteriskRegexFragment;
18078             }
18079             else {
18080                 if (usage === "directories") {
18081                     subpattern += "(";
18082                     optionalCount++;
18083                 }
18084                 if (hasWrittenComponent) {
18085                     subpattern += ts.directorySeparator;
18086                 }
18087                 if (usage !== "exclude") {
18088                     var componentPattern = "";
18089                     // The * and ? wildcards should not match directories or files that start with . if they
18090                     // appear first in a component. Dotted directories and files can be included explicitly
18091                     // like so: **/.*/.*
18092                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18093                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18094                         component = component.substr(1);
18095                     }
18096                     else if (component.charCodeAt(0) === 63 /* question */) {
18097                         componentPattern += "[^./]";
18098                         component = component.substr(1);
18099                     }
18100                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18101                     // Patterns should not include subfolders like node_modules unless they are
18102                     // explicitly included as part of the path.
18103                     //
18104                     // As an optimization, if the component pattern is the same as the component,
18105                     // then there definitely were no wildcard characters and we do not need to
18106                     // add the exclusion pattern.
18107                     if (componentPattern !== component) {
18108                         subpattern += implicitExcludePathRegexPattern;
18109                     }
18110                     subpattern += componentPattern;
18111                 }
18112                 else {
18113                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18114                 }
18115             }
18116             hasWrittenComponent = true;
18117         }
18118         while (optionalCount > 0) {
18119             subpattern += ")?";
18120             optionalCount--;
18121         }
18122         return subpattern;
18123     }
18124     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18125         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18126     }
18127     /** @param path directory of the tsconfig.json */
18128     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18129         path = ts.normalizePath(path);
18130         currentDirectory = ts.normalizePath(currentDirectory);
18131         var absolutePath = ts.combinePaths(currentDirectory, path);
18132         return {
18133             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18134             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18135             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18136             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18137             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18138         };
18139     }
18140     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18141     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18142         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18143     }
18144     ts.getRegexFromPattern = getRegexFromPattern;
18145     /** @param path directory of the tsconfig.json */
18146     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18147         path = ts.normalizePath(path);
18148         currentDirectory = ts.normalizePath(currentDirectory);
18149         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18150         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18151         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18152         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18153         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18154         // If there are no "includes", then just put everything in results[0].
18155         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18156         var visited = ts.createMap();
18157         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18158         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18159             var basePath = _a[_i];
18160             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18161         }
18162         return ts.flatten(results);
18163         function visitDirectory(path, absolutePath, depth) {
18164             var canonicalPath = toCanonical(realpath(absolutePath));
18165             if (visited.has(canonicalPath))
18166                 return;
18167             visited.set(canonicalPath, true);
18168             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18169             var _loop_1 = function (current) {
18170                 var name = ts.combinePaths(path, current);
18171                 var absoluteName = ts.combinePaths(absolutePath, current);
18172                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18173                     return "continue";
18174                 if (excludeRegex && excludeRegex.test(absoluteName))
18175                     return "continue";
18176                 if (!includeFileRegexes) {
18177                     results[0].push(name);
18178                 }
18179                 else {
18180                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
18181                     if (includeIndex !== -1) {
18182                         results[includeIndex].push(name);
18183                     }
18184                 }
18185             };
18186             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
18187                 var current = _b[_i];
18188                 _loop_1(current);
18189             }
18190             if (depth !== undefined) {
18191                 depth--;
18192                 if (depth === 0) {
18193                     return;
18194                 }
18195             }
18196             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
18197                 var current = _d[_c];
18198                 var name = ts.combinePaths(path, current);
18199                 var absoluteName = ts.combinePaths(absolutePath, current);
18200                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
18201                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
18202                     visitDirectory(name, absoluteName, depth);
18203                 }
18204             }
18205         }
18206     }
18207     ts.matchFiles = matchFiles;
18208     /**
18209      * Computes the unique non-wildcard base paths amongst the provided include patterns.
18210      */
18211     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
18212         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
18213         var basePaths = [path];
18214         if (includes) {
18215             // Storage for literal base paths amongst the include patterns.
18216             var includeBasePaths = [];
18217             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
18218                 var include = includes_1[_i];
18219                 // We also need to check the relative paths by converting them to absolute and normalizing
18220                 // in case they escape the base path (e.g "..\somedirectory")
18221                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
18222                 // Append the literal and canonical candidate base paths.
18223                 includeBasePaths.push(getIncludeBasePath(absolute));
18224             }
18225             // Sort the offsets array using either the literal or canonical path representations.
18226             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
18227             var _loop_2 = function (includeBasePath) {
18228                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
18229                     basePaths.push(includeBasePath);
18230                 }
18231             };
18232             // Iterate over each include base path and include unique base paths that are not a
18233             // subpath of an existing base path
18234             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
18235                 var includeBasePath = includeBasePaths_1[_a];
18236                 _loop_2(includeBasePath);
18237             }
18238         }
18239         return basePaths;
18240     }
18241     function getIncludeBasePath(absolute) {
18242         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
18243         if (wildcardOffset < 0) {
18244             // No "*" or "?" in the path
18245             return !ts.hasExtension(absolute)
18246                 ? absolute
18247                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
18248         }
18249         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
18250     }
18251     function ensureScriptKind(fileName, scriptKind) {
18252         // Using scriptKind as a condition handles both:
18253         // - 'scriptKind' is unspecified and thus it is `undefined`
18254         // - 'scriptKind' is set and it is `Unknown` (0)
18255         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
18256         // to get the ScriptKind from the file name. If it cannot be resolved
18257         // from the file name then the default 'TS' script kind is returned.
18258         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
18259     }
18260     ts.ensureScriptKind = ensureScriptKind;
18261     function getScriptKindFromFileName(fileName) {
18262         var ext = fileName.substr(fileName.lastIndexOf("."));
18263         switch (ext.toLowerCase()) {
18264             case ".js" /* Js */:
18265                 return 1 /* JS */;
18266             case ".jsx" /* Jsx */:
18267                 return 2 /* JSX */;
18268             case ".ts" /* Ts */:
18269                 return 3 /* TS */;
18270             case ".tsx" /* Tsx */:
18271                 return 4 /* TSX */;
18272             case ".json" /* Json */:
18273                 return 6 /* JSON */;
18274             default:
18275                 return 0 /* Unknown */;
18276         }
18277     }
18278     ts.getScriptKindFromFileName = getScriptKindFromFileName;
18279     /**
18280      *  List of supported extensions in order of file resolution precedence.
18281      */
18282     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
18283     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
18284     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
18285     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
18286     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
18287     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
18288     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
18289     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
18290     function getSupportedExtensions(options, extraFileExtensions) {
18291         var needJsExtensions = options && options.allowJs;
18292         if (!extraFileExtensions || extraFileExtensions.length === 0) {
18293             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
18294         }
18295         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
18296         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
18297     }
18298     ts.getSupportedExtensions = getSupportedExtensions;
18299     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
18300         if (!options || !options.resolveJsonModule) {
18301             return supportedExtensions;
18302         }
18303         if (supportedExtensions === allSupportedExtensions) {
18304             return allSupportedExtensionsWithJson;
18305         }
18306         if (supportedExtensions === ts.supportedTSExtensions) {
18307             return ts.supportedTSExtensionsWithJson;
18308         }
18309         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
18310     }
18311     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
18312     function isJSLike(scriptKind) {
18313         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
18314     }
18315     function hasJSFileExtension(fileName) {
18316         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18317     }
18318     ts.hasJSFileExtension = hasJSFileExtension;
18319     function hasTSFileExtension(fileName) {
18320         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
18321     }
18322     ts.hasTSFileExtension = hasTSFileExtension;
18323     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
18324         if (!fileName) {
18325             return false;
18326         }
18327         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
18328         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
18329             var extension = _a[_i];
18330             if (ts.fileExtensionIs(fileName, extension)) {
18331                 return true;
18332             }
18333         }
18334         return false;
18335     }
18336     ts.isSupportedSourceFileName = isSupportedSourceFileName;
18337     /**
18338      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
18339      * aligned to the offset of the highest priority extension in the
18340      * allSupportedExtensions array.
18341      */
18342     var ExtensionPriority;
18343     (function (ExtensionPriority) {
18344         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
18345         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
18346         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
18347         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
18348     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
18349     function getExtensionPriority(path, supportedExtensions) {
18350         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
18351             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
18352                 return adjustExtensionPriority(i, supportedExtensions);
18353             }
18354         }
18355         // If its not in the list of supported extensions, this is likely a
18356         // TypeScript file with a non-ts extension
18357         return 0 /* Highest */;
18358     }
18359     ts.getExtensionPriority = getExtensionPriority;
18360     /**
18361      * Adjusts an extension priority to be the highest priority within the same range.
18362      */
18363     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
18364         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18365             return 0 /* TypeScriptFiles */;
18366         }
18367         else if (extensionPriority < supportedExtensions.length) {
18368             return 2 /* DeclarationAndJavaScriptFiles */;
18369         }
18370         else {
18371             return supportedExtensions.length;
18372         }
18373     }
18374     ts.adjustExtensionPriority = adjustExtensionPriority;
18375     /**
18376      * Gets the next lowest extension priority for a given priority.
18377      */
18378     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
18379         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
18380             return 2 /* DeclarationAndJavaScriptFiles */;
18381         }
18382         else {
18383             return supportedExtensions.length;
18384         }
18385     }
18386     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
18387     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
18388     function removeFileExtension(path) {
18389         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
18390             var ext = extensionsToRemove_1[_i];
18391             var extensionless = tryRemoveExtension(path, ext);
18392             if (extensionless !== undefined) {
18393                 return extensionless;
18394             }
18395         }
18396         return path;
18397     }
18398     ts.removeFileExtension = removeFileExtension;
18399     function tryRemoveExtension(path, extension) {
18400         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
18401     }
18402     ts.tryRemoveExtension = tryRemoveExtension;
18403     function removeExtension(path, extension) {
18404         return path.substring(0, path.length - extension.length);
18405     }
18406     ts.removeExtension = removeExtension;
18407     function changeExtension(path, newExtension) {
18408         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
18409     }
18410     ts.changeExtension = changeExtension;
18411     function tryParsePattern(pattern) {
18412         // This should be verified outside of here and a proper error thrown.
18413         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
18414         var indexOfStar = pattern.indexOf("*");
18415         return indexOfStar === -1 ? undefined : {
18416             prefix: pattern.substr(0, indexOfStar),
18417             suffix: pattern.substr(indexOfStar + 1)
18418         };
18419     }
18420     ts.tryParsePattern = tryParsePattern;
18421     function positionIsSynthesized(pos) {
18422         // This is a fast way of testing the following conditions:
18423         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
18424         return !(pos >= 0);
18425     }
18426     ts.positionIsSynthesized = positionIsSynthesized;
18427     /** True if an extension is one of the supported TypeScript extensions. */
18428     function extensionIsTS(ext) {
18429         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
18430     }
18431     ts.extensionIsTS = extensionIsTS;
18432     function resolutionExtensionIsTSOrJson(ext) {
18433         return extensionIsTS(ext) || ext === ".json" /* Json */;
18434     }
18435     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
18436     /**
18437      * Gets the extension from a path.
18438      * Path must have a valid extension.
18439      */
18440     function extensionFromPath(path) {
18441         var ext = tryGetExtensionFromPath(path);
18442         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
18443     }
18444     ts.extensionFromPath = extensionFromPath;
18445     function isAnySupportedFileExtension(path) {
18446         return tryGetExtensionFromPath(path) !== undefined;
18447     }
18448     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
18449     function tryGetExtensionFromPath(path) {
18450         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
18451     }
18452     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
18453     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
18454         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
18455     }
18456     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
18457     ts.emptyFileSystemEntries = {
18458         files: ts.emptyArray,
18459         directories: ts.emptyArray
18460     };
18461     /**
18462      * patternStrings contains both pattern strings (containing "*") and regular strings.
18463      * Return an exact match if possible, or a pattern match, or undefined.
18464      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
18465      */
18466     function matchPatternOrExact(patternStrings, candidate) {
18467         var patterns = [];
18468         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
18469             var patternString = patternStrings_1[_i];
18470             if (!hasZeroOrOneAsteriskCharacter(patternString))
18471                 continue;
18472             var pattern = tryParsePattern(patternString);
18473             if (pattern) {
18474                 patterns.push(pattern);
18475             }
18476             else if (patternString === candidate) {
18477                 // pattern was matched as is - no need to search further
18478                 return patternString;
18479             }
18480         }
18481         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
18482     }
18483     ts.matchPatternOrExact = matchPatternOrExact;
18484     function sliceAfter(arr, value) {
18485         var index = arr.indexOf(value);
18486         ts.Debug.assert(index !== -1);
18487         return arr.slice(index);
18488     }
18489     ts.sliceAfter = sliceAfter;
18490     function addRelatedInfo(diagnostic) {
18491         var _a;
18492         var relatedInformation = [];
18493         for (var _i = 1; _i < arguments.length; _i++) {
18494             relatedInformation[_i - 1] = arguments[_i];
18495         }
18496         if (!relatedInformation.length) {
18497             return diagnostic;
18498         }
18499         if (!diagnostic.relatedInformation) {
18500             diagnostic.relatedInformation = [];
18501         }
18502         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
18503         return diagnostic;
18504     }
18505     ts.addRelatedInfo = addRelatedInfo;
18506     function minAndMax(arr, getValue) {
18507         ts.Debug.assert(arr.length !== 0);
18508         var min = getValue(arr[0]);
18509         var max = min;
18510         for (var i = 1; i < arr.length; i++) {
18511             var value = getValue(arr[i]);
18512             if (value < min) {
18513                 min = value;
18514             }
18515             else if (value > max) {
18516                 max = value;
18517             }
18518         }
18519         return { min: min, max: max };
18520     }
18521     ts.minAndMax = minAndMax;
18522     var NodeSet = /** @class */ (function () {
18523         function NodeSet() {
18524             this.map = ts.createMap();
18525         }
18526         NodeSet.prototype.add = function (node) {
18527             this.map.set(String(ts.getNodeId(node)), node);
18528         };
18529         NodeSet.prototype.tryAdd = function (node) {
18530             if (this.has(node))
18531                 return false;
18532             this.add(node);
18533             return true;
18534         };
18535         NodeSet.prototype.has = function (node) {
18536             return this.map.has(String(ts.getNodeId(node)));
18537         };
18538         NodeSet.prototype.forEach = function (cb) {
18539             this.map.forEach(cb);
18540         };
18541         NodeSet.prototype.some = function (pred) {
18542             return forEachEntry(this.map, pred) || false;
18543         };
18544         return NodeSet;
18545     }());
18546     ts.NodeSet = NodeSet;
18547     var NodeMap = /** @class */ (function () {
18548         function NodeMap() {
18549             this.map = ts.createMap();
18550         }
18551         NodeMap.prototype.get = function (node) {
18552             var res = this.map.get(String(ts.getNodeId(node)));
18553             return res && res.value;
18554         };
18555         NodeMap.prototype.getOrUpdate = function (node, setValue) {
18556             var res = this.get(node);
18557             if (res)
18558                 return res;
18559             var value = setValue();
18560             this.set(node, value);
18561             return value;
18562         };
18563         NodeMap.prototype.set = function (node, value) {
18564             this.map.set(String(ts.getNodeId(node)), { node: node, value: value });
18565         };
18566         NodeMap.prototype.has = function (node) {
18567             return this.map.has(String(ts.getNodeId(node)));
18568         };
18569         NodeMap.prototype.forEach = function (cb) {
18570             this.map.forEach(function (_a) {
18571                 var node = _a.node, value = _a.value;
18572                 return cb(value, node);
18573             });
18574         };
18575         return NodeMap;
18576     }());
18577     ts.NodeMap = NodeMap;
18578     function rangeOfNode(node) {
18579         return { pos: getTokenPosOfNode(node), end: node.end };
18580     }
18581     ts.rangeOfNode = rangeOfNode;
18582     function rangeOfTypeParameters(typeParameters) {
18583         // Include the `<>`
18584         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
18585     }
18586     ts.rangeOfTypeParameters = rangeOfTypeParameters;
18587     function skipTypeChecking(sourceFile, options, host) {
18588         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
18589         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
18590         // '/// <reference no-default-lib="true"/>' directive.
18591         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
18592             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
18593             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
18594     }
18595     ts.skipTypeChecking = skipTypeChecking;
18596     function isJsonEqual(a, b) {
18597         // eslint-disable-next-line no-null/no-null
18598         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
18599     }
18600     ts.isJsonEqual = isJsonEqual;
18601     function getOrUpdate(map, key, getDefault) {
18602         var got = map.get(key);
18603         if (got === undefined) {
18604             var value = getDefault();
18605             map.set(key, value);
18606             return value;
18607         }
18608         else {
18609             return got;
18610         }
18611     }
18612     ts.getOrUpdate = getOrUpdate;
18613     /**
18614      * Converts a bigint literal string, e.g. `0x1234n`,
18615      * to its decimal string representation, e.g. `4660`.
18616      */
18617     function parsePseudoBigInt(stringValue) {
18618         var log2Base;
18619         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
18620             case 98 /* b */:
18621             case 66 /* B */: // 0b or 0B
18622                 log2Base = 1;
18623                 break;
18624             case 111 /* o */:
18625             case 79 /* O */: // 0o or 0O
18626                 log2Base = 3;
18627                 break;
18628             case 120 /* x */:
18629             case 88 /* X */: // 0x or 0X
18630                 log2Base = 4;
18631                 break;
18632             default: // already in decimal; omit trailing "n"
18633                 var nIndex = stringValue.length - 1;
18634                 // Skip leading 0s
18635                 var nonZeroStart = 0;
18636                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
18637                     nonZeroStart++;
18638                 }
18639                 return stringValue.slice(nonZeroStart, nIndex) || "0";
18640         }
18641         // Omit leading "0b", "0o", or "0x", and trailing "n"
18642         var startIndex = 2, endIndex = stringValue.length - 1;
18643         var bitsNeeded = (endIndex - startIndex) * log2Base;
18644         // Stores the value specified by the string as a LE array of 16-bit integers
18645         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
18646         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
18647         // Add the digits, one at a time
18648         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
18649             var segment = bitOffset >>> 4;
18650             var digitChar = stringValue.charCodeAt(i);
18651             // Find character range: 0-9 < A-F < a-f
18652             var digit = digitChar <= 57 /* _9 */
18653                 ? digitChar - 48 /* _0 */
18654                 : 10 + digitChar -
18655                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
18656             var shiftedDigit = digit << (bitOffset & 15);
18657             segments[segment] |= shiftedDigit;
18658             var residual = shiftedDigit >>> 16;
18659             if (residual)
18660                 segments[segment + 1] |= residual; // overflows segment
18661         }
18662         // Repeatedly divide segments by 10 and add remainder to base10Value
18663         var base10Value = "";
18664         var firstNonzeroSegment = segments.length - 1;
18665         var segmentsRemaining = true;
18666         while (segmentsRemaining) {
18667             var mod10 = 0;
18668             segmentsRemaining = false;
18669             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
18670                 var newSegment = mod10 << 16 | segments[segment];
18671                 var segmentValue = (newSegment / 10) | 0;
18672                 segments[segment] = segmentValue;
18673                 mod10 = newSegment - segmentValue * 10;
18674                 if (segmentValue && !segmentsRemaining) {
18675                     firstNonzeroSegment = segment;
18676                     segmentsRemaining = true;
18677                 }
18678             }
18679             base10Value = mod10 + base10Value;
18680         }
18681         return base10Value;
18682     }
18683     ts.parsePseudoBigInt = parsePseudoBigInt;
18684     function pseudoBigIntToString(_a) {
18685         var negative = _a.negative, base10Value = _a.base10Value;
18686         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
18687     }
18688     ts.pseudoBigIntToString = pseudoBigIntToString;
18689     function isValidTypeOnlyAliasUseSite(useSite) {
18690         return !!(useSite.flags & 8388608 /* Ambient */)
18691             || isPartOfTypeQuery(useSite)
18692             || isIdentifierInNonEmittingHeritageClause(useSite)
18693             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
18694             || !isExpressionNode(useSite);
18695     }
18696     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
18697     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
18698         return typeOnlyDeclaration.kind === 263 /* ExportSpecifier */;
18699     }
18700     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
18701     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
18702         while (node.kind === 75 /* Identifier */ || node.kind === 194 /* PropertyAccessExpression */) {
18703             node = node.parent;
18704         }
18705         if (node.kind !== 154 /* ComputedPropertyName */) {
18706             return false;
18707         }
18708         if (hasModifier(node.parent, 128 /* Abstract */)) {
18709             return true;
18710         }
18711         var containerKind = node.parent.parent.kind;
18712         return containerKind === 246 /* InterfaceDeclaration */ || containerKind === 173 /* TypeLiteral */;
18713     }
18714     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
18715     function isIdentifierInNonEmittingHeritageClause(node) {
18716         if (node.kind !== 75 /* Identifier */)
18717             return false;
18718         var heritageClause = findAncestor(node.parent, function (parent) {
18719             switch (parent.kind) {
18720                 case 279 /* HeritageClause */:
18721                     return true;
18722                 case 194 /* PropertyAccessExpression */:
18723                 case 216 /* ExpressionWithTypeArguments */:
18724                     return false;
18725                 default:
18726                     return "quit";
18727             }
18728         });
18729         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 113 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 246 /* InterfaceDeclaration */;
18730     }
18731     function isIdentifierTypeReference(node) {
18732         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
18733     }
18734     ts.isIdentifierTypeReference = isIdentifierTypeReference;
18735     function arrayIsHomogeneous(array, comparer) {
18736         if (comparer === void 0) { comparer = ts.equateValues; }
18737         if (array.length < 2)
18738             return true;
18739         var first = array[0];
18740         for (var i = 1, length_1 = array.length; i < length_1; i++) {
18741             var target = array[i];
18742             if (!comparer(first, target))
18743                 return false;
18744         }
18745         return true;
18746     }
18747     ts.arrayIsHomogeneous = arrayIsHomogeneous;
18748 })(ts || (ts = {}));
18749 var ts;
18750 (function (ts) {
18751     var SignatureFlags;
18752     (function (SignatureFlags) {
18753         SignatureFlags[SignatureFlags["None"] = 0] = "None";
18754         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
18755         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
18756         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
18757         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
18758         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
18759     })(SignatureFlags || (SignatureFlags = {}));
18760     var NodeConstructor;
18761     var TokenConstructor;
18762     var IdentifierConstructor;
18763     var PrivateIdentifierConstructor;
18764     var SourceFileConstructor;
18765     function createNode(kind, pos, end) {
18766         if (kind === 290 /* SourceFile */) {
18767             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, pos, end);
18768         }
18769         else if (kind === 75 /* Identifier */) {
18770             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, pos, end);
18771         }
18772         else if (kind === 76 /* PrivateIdentifier */) {
18773             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, pos, end);
18774         }
18775         else if (!ts.isNodeKind(kind)) {
18776             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, pos, end);
18777         }
18778         else {
18779             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, pos, end);
18780         }
18781     }
18782     ts.createNode = createNode;
18783     function visitNode(cbNode, node) {
18784         return node && cbNode(node);
18785     }
18786     function visitNodes(cbNode, cbNodes, nodes) {
18787         if (nodes) {
18788             if (cbNodes) {
18789                 return cbNodes(nodes);
18790             }
18791             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
18792                 var node = nodes_1[_i];
18793                 var result = cbNode(node);
18794                 if (result) {
18795                     return result;
18796                 }
18797             }
18798         }
18799     }
18800     /*@internal*/
18801     function isJSDocLikeText(text, start) {
18802         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
18803             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
18804             text.charCodeAt(start + 3) !== 47 /* slash */;
18805     }
18806     ts.isJSDocLikeText = isJSDocLikeText;
18807     /**
18808      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
18809      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
18810      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
18811      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
18812      *
18813      * @param node a given node to visit its children
18814      * @param cbNode a callback to be invoked for all child nodes
18815      * @param cbNodes a callback to be invoked for embedded array
18816      *
18817      * @remarks `forEachChild` must visit the children of a node in the order
18818      * that they appear in the source code. The language service depends on this property to locate nodes by position.
18819      */
18820     function forEachChild(node, cbNode, cbNodes) {
18821         if (!node || node.kind <= 152 /* LastToken */) {
18822             return;
18823         }
18824         switch (node.kind) {
18825             case 153 /* QualifiedName */:
18826                 return visitNode(cbNode, node.left) ||
18827                     visitNode(cbNode, node.right);
18828             case 155 /* TypeParameter */:
18829                 return visitNode(cbNode, node.name) ||
18830                     visitNode(cbNode, node.constraint) ||
18831                     visitNode(cbNode, node.default) ||
18832                     visitNode(cbNode, node.expression);
18833             case 282 /* ShorthandPropertyAssignment */:
18834                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18835                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18836                     visitNode(cbNode, node.name) ||
18837                     visitNode(cbNode, node.questionToken) ||
18838                     visitNode(cbNode, node.exclamationToken) ||
18839                     visitNode(cbNode, node.equalsToken) ||
18840                     visitNode(cbNode, node.objectAssignmentInitializer);
18841             case 283 /* SpreadAssignment */:
18842                 return visitNode(cbNode, node.expression);
18843             case 156 /* Parameter */:
18844                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18845                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18846                     visitNode(cbNode, node.dotDotDotToken) ||
18847                     visitNode(cbNode, node.name) ||
18848                     visitNode(cbNode, node.questionToken) ||
18849                     visitNode(cbNode, node.type) ||
18850                     visitNode(cbNode, node.initializer);
18851             case 159 /* PropertyDeclaration */:
18852                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18853                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18854                     visitNode(cbNode, node.name) ||
18855                     visitNode(cbNode, node.questionToken) ||
18856                     visitNode(cbNode, node.exclamationToken) ||
18857                     visitNode(cbNode, node.type) ||
18858                     visitNode(cbNode, node.initializer);
18859             case 158 /* PropertySignature */:
18860                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18861                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18862                     visitNode(cbNode, node.name) ||
18863                     visitNode(cbNode, node.questionToken) ||
18864                     visitNode(cbNode, node.type) ||
18865                     visitNode(cbNode, node.initializer);
18866             case 281 /* PropertyAssignment */:
18867                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18868                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18869                     visitNode(cbNode, node.name) ||
18870                     visitNode(cbNode, node.questionToken) ||
18871                     visitNode(cbNode, node.initializer);
18872             case 242 /* VariableDeclaration */:
18873                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18874                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18875                     visitNode(cbNode, node.name) ||
18876                     visitNode(cbNode, node.exclamationToken) ||
18877                     visitNode(cbNode, node.type) ||
18878                     visitNode(cbNode, node.initializer);
18879             case 191 /* BindingElement */:
18880                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18881                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18882                     visitNode(cbNode, node.dotDotDotToken) ||
18883                     visitNode(cbNode, node.propertyName) ||
18884                     visitNode(cbNode, node.name) ||
18885                     visitNode(cbNode, node.initializer);
18886             case 170 /* FunctionType */:
18887             case 171 /* ConstructorType */:
18888             case 165 /* CallSignature */:
18889             case 166 /* ConstructSignature */:
18890             case 167 /* IndexSignature */:
18891                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18892                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18893                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18894                     visitNodes(cbNode, cbNodes, node.parameters) ||
18895                     visitNode(cbNode, node.type);
18896             case 161 /* MethodDeclaration */:
18897             case 160 /* MethodSignature */:
18898             case 162 /* Constructor */:
18899             case 163 /* GetAccessor */:
18900             case 164 /* SetAccessor */:
18901             case 201 /* FunctionExpression */:
18902             case 244 /* FunctionDeclaration */:
18903             case 202 /* ArrowFunction */:
18904                 return visitNodes(cbNode, cbNodes, node.decorators) ||
18905                     visitNodes(cbNode, cbNodes, node.modifiers) ||
18906                     visitNode(cbNode, node.asteriskToken) ||
18907                     visitNode(cbNode, node.name) ||
18908                     visitNode(cbNode, node.questionToken) ||
18909                     visitNode(cbNode, node.exclamationToken) ||
18910                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
18911                     visitNodes(cbNode, cbNodes, node.parameters) ||
18912                     visitNode(cbNode, node.type) ||
18913                     visitNode(cbNode, node.equalsGreaterThanToken) ||
18914                     visitNode(cbNode, node.body);
18915             case 169 /* TypeReference */:
18916                 return visitNode(cbNode, node.typeName) ||
18917                     visitNodes(cbNode, cbNodes, node.typeArguments);
18918             case 168 /* TypePredicate */:
18919                 return visitNode(cbNode, node.assertsModifier) ||
18920                     visitNode(cbNode, node.parameterName) ||
18921                     visitNode(cbNode, node.type);
18922             case 172 /* TypeQuery */:
18923                 return visitNode(cbNode, node.exprName);
18924             case 173 /* TypeLiteral */:
18925                 return visitNodes(cbNode, cbNodes, node.members);
18926             case 174 /* ArrayType */:
18927                 return visitNode(cbNode, node.elementType);
18928             case 175 /* TupleType */:
18929                 return visitNodes(cbNode, cbNodes, node.elementTypes);
18930             case 178 /* UnionType */:
18931             case 179 /* IntersectionType */:
18932                 return visitNodes(cbNode, cbNodes, node.types);
18933             case 180 /* ConditionalType */:
18934                 return visitNode(cbNode, node.checkType) ||
18935                     visitNode(cbNode, node.extendsType) ||
18936                     visitNode(cbNode, node.trueType) ||
18937                     visitNode(cbNode, node.falseType);
18938             case 181 /* InferType */:
18939                 return visitNode(cbNode, node.typeParameter);
18940             case 188 /* ImportType */:
18941                 return visitNode(cbNode, node.argument) ||
18942                     visitNode(cbNode, node.qualifier) ||
18943                     visitNodes(cbNode, cbNodes, node.typeArguments);
18944             case 182 /* ParenthesizedType */:
18945             case 184 /* TypeOperator */:
18946                 return visitNode(cbNode, node.type);
18947             case 185 /* IndexedAccessType */:
18948                 return visitNode(cbNode, node.objectType) ||
18949                     visitNode(cbNode, node.indexType);
18950             case 186 /* MappedType */:
18951                 return visitNode(cbNode, node.readonlyToken) ||
18952                     visitNode(cbNode, node.typeParameter) ||
18953                     visitNode(cbNode, node.questionToken) ||
18954                     visitNode(cbNode, node.type);
18955             case 187 /* LiteralType */:
18956                 return visitNode(cbNode, node.literal);
18957             case 189 /* ObjectBindingPattern */:
18958             case 190 /* ArrayBindingPattern */:
18959                 return visitNodes(cbNode, cbNodes, node.elements);
18960             case 192 /* ArrayLiteralExpression */:
18961                 return visitNodes(cbNode, cbNodes, node.elements);
18962             case 193 /* ObjectLiteralExpression */:
18963                 return visitNodes(cbNode, cbNodes, node.properties);
18964             case 194 /* PropertyAccessExpression */:
18965                 return visitNode(cbNode, node.expression) ||
18966                     visitNode(cbNode, node.questionDotToken) ||
18967                     visitNode(cbNode, node.name);
18968             case 195 /* ElementAccessExpression */:
18969                 return visitNode(cbNode, node.expression) ||
18970                     visitNode(cbNode, node.questionDotToken) ||
18971                     visitNode(cbNode, node.argumentExpression);
18972             case 196 /* CallExpression */:
18973             case 197 /* NewExpression */:
18974                 return visitNode(cbNode, node.expression) ||
18975                     visitNode(cbNode, node.questionDotToken) ||
18976                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18977                     visitNodes(cbNode, cbNodes, node.arguments);
18978             case 198 /* TaggedTemplateExpression */:
18979                 return visitNode(cbNode, node.tag) ||
18980                     visitNode(cbNode, node.questionDotToken) ||
18981                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
18982                     visitNode(cbNode, node.template);
18983             case 199 /* TypeAssertionExpression */:
18984                 return visitNode(cbNode, node.type) ||
18985                     visitNode(cbNode, node.expression);
18986             case 200 /* ParenthesizedExpression */:
18987                 return visitNode(cbNode, node.expression);
18988             case 203 /* DeleteExpression */:
18989                 return visitNode(cbNode, node.expression);
18990             case 204 /* TypeOfExpression */:
18991                 return visitNode(cbNode, node.expression);
18992             case 205 /* VoidExpression */:
18993                 return visitNode(cbNode, node.expression);
18994             case 207 /* PrefixUnaryExpression */:
18995                 return visitNode(cbNode, node.operand);
18996             case 212 /* YieldExpression */:
18997                 return visitNode(cbNode, node.asteriskToken) ||
18998                     visitNode(cbNode, node.expression);
18999             case 206 /* AwaitExpression */:
19000                 return visitNode(cbNode, node.expression);
19001             case 208 /* PostfixUnaryExpression */:
19002                 return visitNode(cbNode, node.operand);
19003             case 209 /* BinaryExpression */:
19004                 return visitNode(cbNode, node.left) ||
19005                     visitNode(cbNode, node.operatorToken) ||
19006                     visitNode(cbNode, node.right);
19007             case 217 /* AsExpression */:
19008                 return visitNode(cbNode, node.expression) ||
19009                     visitNode(cbNode, node.type);
19010             case 218 /* NonNullExpression */:
19011                 return visitNode(cbNode, node.expression);
19012             case 219 /* MetaProperty */:
19013                 return visitNode(cbNode, node.name);
19014             case 210 /* ConditionalExpression */:
19015                 return visitNode(cbNode, node.condition) ||
19016                     visitNode(cbNode, node.questionToken) ||
19017                     visitNode(cbNode, node.whenTrue) ||
19018                     visitNode(cbNode, node.colonToken) ||
19019                     visitNode(cbNode, node.whenFalse);
19020             case 213 /* SpreadElement */:
19021                 return visitNode(cbNode, node.expression);
19022             case 223 /* Block */:
19023             case 250 /* ModuleBlock */:
19024                 return visitNodes(cbNode, cbNodes, node.statements);
19025             case 290 /* SourceFile */:
19026                 return visitNodes(cbNode, cbNodes, node.statements) ||
19027                     visitNode(cbNode, node.endOfFileToken);
19028             case 225 /* VariableStatement */:
19029                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19030                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19031                     visitNode(cbNode, node.declarationList);
19032             case 243 /* VariableDeclarationList */:
19033                 return visitNodes(cbNode, cbNodes, node.declarations);
19034             case 226 /* ExpressionStatement */:
19035                 return visitNode(cbNode, node.expression);
19036             case 227 /* IfStatement */:
19037                 return visitNode(cbNode, node.expression) ||
19038                     visitNode(cbNode, node.thenStatement) ||
19039                     visitNode(cbNode, node.elseStatement);
19040             case 228 /* DoStatement */:
19041                 return visitNode(cbNode, node.statement) ||
19042                     visitNode(cbNode, node.expression);
19043             case 229 /* WhileStatement */:
19044                 return visitNode(cbNode, node.expression) ||
19045                     visitNode(cbNode, node.statement);
19046             case 230 /* ForStatement */:
19047                 return visitNode(cbNode, node.initializer) ||
19048                     visitNode(cbNode, node.condition) ||
19049                     visitNode(cbNode, node.incrementor) ||
19050                     visitNode(cbNode, node.statement);
19051             case 231 /* ForInStatement */:
19052                 return visitNode(cbNode, node.initializer) ||
19053                     visitNode(cbNode, node.expression) ||
19054                     visitNode(cbNode, node.statement);
19055             case 232 /* ForOfStatement */:
19056                 return visitNode(cbNode, node.awaitModifier) ||
19057                     visitNode(cbNode, node.initializer) ||
19058                     visitNode(cbNode, node.expression) ||
19059                     visitNode(cbNode, node.statement);
19060             case 233 /* ContinueStatement */:
19061             case 234 /* BreakStatement */:
19062                 return visitNode(cbNode, node.label);
19063             case 235 /* ReturnStatement */:
19064                 return visitNode(cbNode, node.expression);
19065             case 236 /* WithStatement */:
19066                 return visitNode(cbNode, node.expression) ||
19067                     visitNode(cbNode, node.statement);
19068             case 237 /* SwitchStatement */:
19069                 return visitNode(cbNode, node.expression) ||
19070                     visitNode(cbNode, node.caseBlock);
19071             case 251 /* CaseBlock */:
19072                 return visitNodes(cbNode, cbNodes, node.clauses);
19073             case 277 /* CaseClause */:
19074                 return visitNode(cbNode, node.expression) ||
19075                     visitNodes(cbNode, cbNodes, node.statements);
19076             case 278 /* DefaultClause */:
19077                 return visitNodes(cbNode, cbNodes, node.statements);
19078             case 238 /* LabeledStatement */:
19079                 return visitNode(cbNode, node.label) ||
19080                     visitNode(cbNode, node.statement);
19081             case 239 /* ThrowStatement */:
19082                 return visitNode(cbNode, node.expression);
19083             case 240 /* TryStatement */:
19084                 return visitNode(cbNode, node.tryBlock) ||
19085                     visitNode(cbNode, node.catchClause) ||
19086                     visitNode(cbNode, node.finallyBlock);
19087             case 280 /* CatchClause */:
19088                 return visitNode(cbNode, node.variableDeclaration) ||
19089                     visitNode(cbNode, node.block);
19090             case 157 /* Decorator */:
19091                 return visitNode(cbNode, node.expression);
19092             case 245 /* ClassDeclaration */:
19093             case 214 /* ClassExpression */:
19094                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19095                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19096                     visitNode(cbNode, node.name) ||
19097                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19098                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19099                     visitNodes(cbNode, cbNodes, node.members);
19100             case 246 /* InterfaceDeclaration */:
19101                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19102                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19103                     visitNode(cbNode, node.name) ||
19104                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19105                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
19106                     visitNodes(cbNode, cbNodes, node.members);
19107             case 247 /* TypeAliasDeclaration */:
19108                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19109                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19110                     visitNode(cbNode, node.name) ||
19111                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
19112                     visitNode(cbNode, node.type);
19113             case 248 /* EnumDeclaration */:
19114                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19115                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19116                     visitNode(cbNode, node.name) ||
19117                     visitNodes(cbNode, cbNodes, node.members);
19118             case 284 /* EnumMember */:
19119                 return visitNode(cbNode, node.name) ||
19120                     visitNode(cbNode, node.initializer);
19121             case 249 /* ModuleDeclaration */:
19122                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19123                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19124                     visitNode(cbNode, node.name) ||
19125                     visitNode(cbNode, node.body);
19126             case 253 /* ImportEqualsDeclaration */:
19127                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19128                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19129                     visitNode(cbNode, node.name) ||
19130                     visitNode(cbNode, node.moduleReference);
19131             case 254 /* ImportDeclaration */:
19132                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19133                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19134                     visitNode(cbNode, node.importClause) ||
19135                     visitNode(cbNode, node.moduleSpecifier);
19136             case 255 /* ImportClause */:
19137                 return visitNode(cbNode, node.name) ||
19138                     visitNode(cbNode, node.namedBindings);
19139             case 252 /* NamespaceExportDeclaration */:
19140                 return visitNode(cbNode, node.name);
19141             case 256 /* NamespaceImport */:
19142                 return visitNode(cbNode, node.name);
19143             case 262 /* NamespaceExport */:
19144                 return visitNode(cbNode, node.name);
19145             case 257 /* NamedImports */:
19146             case 261 /* NamedExports */:
19147                 return visitNodes(cbNode, cbNodes, node.elements);
19148             case 260 /* ExportDeclaration */:
19149                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19150                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19151                     visitNode(cbNode, node.exportClause) ||
19152                     visitNode(cbNode, node.moduleSpecifier);
19153             case 258 /* ImportSpecifier */:
19154             case 263 /* ExportSpecifier */:
19155                 return visitNode(cbNode, node.propertyName) ||
19156                     visitNode(cbNode, node.name);
19157             case 259 /* ExportAssignment */:
19158                 return visitNodes(cbNode, cbNodes, node.decorators) ||
19159                     visitNodes(cbNode, cbNodes, node.modifiers) ||
19160                     visitNode(cbNode, node.expression);
19161             case 211 /* TemplateExpression */:
19162                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
19163             case 221 /* TemplateSpan */:
19164                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
19165             case 154 /* ComputedPropertyName */:
19166                 return visitNode(cbNode, node.expression);
19167             case 279 /* HeritageClause */:
19168                 return visitNodes(cbNode, cbNodes, node.types);
19169             case 216 /* ExpressionWithTypeArguments */:
19170                 return visitNode(cbNode, node.expression) ||
19171                     visitNodes(cbNode, cbNodes, node.typeArguments);
19172             case 265 /* ExternalModuleReference */:
19173                 return visitNode(cbNode, node.expression);
19174             case 264 /* MissingDeclaration */:
19175                 return visitNodes(cbNode, cbNodes, node.decorators);
19176             case 327 /* CommaListExpression */:
19177                 return visitNodes(cbNode, cbNodes, node.elements);
19178             case 266 /* JsxElement */:
19179                 return visitNode(cbNode, node.openingElement) ||
19180                     visitNodes(cbNode, cbNodes, node.children) ||
19181                     visitNode(cbNode, node.closingElement);
19182             case 270 /* JsxFragment */:
19183                 return visitNode(cbNode, node.openingFragment) ||
19184                     visitNodes(cbNode, cbNodes, node.children) ||
19185                     visitNode(cbNode, node.closingFragment);
19186             case 267 /* JsxSelfClosingElement */:
19187             case 268 /* JsxOpeningElement */:
19188                 return visitNode(cbNode, node.tagName) ||
19189                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
19190                     visitNode(cbNode, node.attributes);
19191             case 274 /* JsxAttributes */:
19192                 return visitNodes(cbNode, cbNodes, node.properties);
19193             case 273 /* JsxAttribute */:
19194                 return visitNode(cbNode, node.name) ||
19195                     visitNode(cbNode, node.initializer);
19196             case 275 /* JsxSpreadAttribute */:
19197                 return visitNode(cbNode, node.expression);
19198             case 276 /* JsxExpression */:
19199                 return visitNode(cbNode, node.dotDotDotToken) ||
19200                     visitNode(cbNode, node.expression);
19201             case 269 /* JsxClosingElement */:
19202                 return visitNode(cbNode, node.tagName);
19203             case 176 /* OptionalType */:
19204             case 177 /* RestType */:
19205             case 294 /* JSDocTypeExpression */:
19206             case 298 /* JSDocNonNullableType */:
19207             case 297 /* JSDocNullableType */:
19208             case 299 /* JSDocOptionalType */:
19209             case 301 /* JSDocVariadicType */:
19210                 return visitNode(cbNode, node.type);
19211             case 300 /* JSDocFunctionType */:
19212                 return visitNodes(cbNode, cbNodes, node.parameters) ||
19213                     visitNode(cbNode, node.type);
19214             case 303 /* JSDocComment */:
19215                 return visitNodes(cbNode, cbNodes, node.tags);
19216             case 317 /* JSDocParameterTag */:
19217             case 323 /* JSDocPropertyTag */:
19218                 return visitNode(cbNode, node.tagName) ||
19219                     (node.isNameFirst
19220                         ? visitNode(cbNode, node.name) ||
19221                             visitNode(cbNode, node.typeExpression)
19222                         : visitNode(cbNode, node.typeExpression) ||
19223                             visitNode(cbNode, node.name));
19224             case 309 /* JSDocAuthorTag */:
19225                 return visitNode(cbNode, node.tagName);
19226             case 308 /* JSDocImplementsTag */:
19227                 return visitNode(cbNode, node.tagName) ||
19228                     visitNode(cbNode, node.class);
19229             case 307 /* JSDocAugmentsTag */:
19230                 return visitNode(cbNode, node.tagName) ||
19231                     visitNode(cbNode, node.class);
19232             case 321 /* JSDocTemplateTag */:
19233                 return visitNode(cbNode, node.tagName) ||
19234                     visitNode(cbNode, node.constraint) ||
19235                     visitNodes(cbNode, cbNodes, node.typeParameters);
19236             case 322 /* JSDocTypedefTag */:
19237                 return visitNode(cbNode, node.tagName) ||
19238                     (node.typeExpression &&
19239                         node.typeExpression.kind === 294 /* JSDocTypeExpression */
19240                         ? visitNode(cbNode, node.typeExpression) ||
19241                             visitNode(cbNode, node.fullName)
19242                         : visitNode(cbNode, node.fullName) ||
19243                             visitNode(cbNode, node.typeExpression));
19244             case 315 /* JSDocCallbackTag */:
19245                 return visitNode(cbNode, node.tagName) ||
19246                     visitNode(cbNode, node.fullName) ||
19247                     visitNode(cbNode, node.typeExpression);
19248             case 318 /* JSDocReturnTag */:
19249             case 320 /* JSDocTypeTag */:
19250             case 319 /* JSDocThisTag */:
19251             case 316 /* JSDocEnumTag */:
19252                 return visitNode(cbNode, node.tagName) ||
19253                     visitNode(cbNode, node.typeExpression);
19254             case 305 /* JSDocSignature */:
19255                 return ts.forEach(node.typeParameters, cbNode) ||
19256                     ts.forEach(node.parameters, cbNode) ||
19257                     visitNode(cbNode, node.type);
19258             case 304 /* JSDocTypeLiteral */:
19259                 return ts.forEach(node.jsDocPropertyTags, cbNode);
19260             case 306 /* JSDocTag */:
19261             case 310 /* JSDocClassTag */:
19262             case 311 /* JSDocPublicTag */:
19263             case 312 /* JSDocPrivateTag */:
19264             case 313 /* JSDocProtectedTag */:
19265             case 314 /* JSDocReadonlyTag */:
19266                 return visitNode(cbNode, node.tagName);
19267             case 326 /* PartiallyEmittedExpression */:
19268                 return visitNode(cbNode, node.expression);
19269         }
19270     }
19271     ts.forEachChild = forEachChild;
19272     /** @internal */
19273     /**
19274      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
19275      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
19276      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
19277      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
19278      *
19279      * @param node a given node to visit its children
19280      * @param cbNode a callback to be invoked for all child nodes
19281      * @param cbNodes a callback to be invoked for embedded array
19282      *
19283      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
19284      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
19285      */
19286     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
19287         var stack = [rootNode];
19288         while (stack.length) {
19289             var parent = stack.pop();
19290             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
19291             if (res) {
19292                 return res;
19293             }
19294         }
19295         return;
19296         function gatherPossibleChildren(node) {
19297             var children = [];
19298             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
19299             return children;
19300             function addWorkItem(n) {
19301                 children.unshift(n);
19302             }
19303         }
19304         function visitAllPossibleChildren(parent, children) {
19305             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19306                 var child = children_1[_i];
19307                 if (ts.isArray(child)) {
19308                     if (cbNodes) {
19309                         var res = cbNodes(child, parent);
19310                         if (res) {
19311                             if (res === "skip")
19312                                 continue;
19313                             return res;
19314                         }
19315                     }
19316                     for (var i = child.length - 1; i >= 0; i--) {
19317                         var realChild = child[i];
19318                         var res = cbNode(realChild, parent);
19319                         if (res) {
19320                             if (res === "skip")
19321                                 continue;
19322                             return res;
19323                         }
19324                         stack.push(realChild);
19325                     }
19326                 }
19327                 else {
19328                     stack.push(child);
19329                     var res = cbNode(child, parent);
19330                     if (res) {
19331                         if (res === "skip")
19332                             continue;
19333                         return res;
19334                     }
19335                 }
19336             }
19337         }
19338     }
19339     ts.forEachChildRecursively = forEachChildRecursively;
19340     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
19341         if (setParentNodes === void 0) { setParentNodes = false; }
19342         ts.performance.mark("beforeParse");
19343         var result;
19344         ts.perfLogger.logStartParseSourceFile(fileName);
19345         if (languageVersion === 100 /* JSON */) {
19346             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
19347         }
19348         else {
19349             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
19350         }
19351         ts.perfLogger.logStopParseSourceFile();
19352         ts.performance.mark("afterParse");
19353         ts.performance.measure("Parse", "beforeParse", "afterParse");
19354         return result;
19355     }
19356     ts.createSourceFile = createSourceFile;
19357     function parseIsolatedEntityName(text, languageVersion) {
19358         return Parser.parseIsolatedEntityName(text, languageVersion);
19359     }
19360     ts.parseIsolatedEntityName = parseIsolatedEntityName;
19361     /**
19362      * Parse json text into SyntaxTree and return node and parse errors if any
19363      * @param fileName
19364      * @param sourceText
19365      */
19366     function parseJsonText(fileName, sourceText) {
19367         return Parser.parseJsonText(fileName, sourceText);
19368     }
19369     ts.parseJsonText = parseJsonText;
19370     // See also `isExternalOrCommonJsModule` in utilities.ts
19371     function isExternalModule(file) {
19372         return file.externalModuleIndicator !== undefined;
19373     }
19374     ts.isExternalModule = isExternalModule;
19375     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
19376     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
19377     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
19378     // this file as possible.
19379     //
19380     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
19381     // from this SourceFile that are being held onto may change as a result (including
19382     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
19383     // be used once 'update' is called on it.
19384     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
19385         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
19386         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
19387         // 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.
19388         // We will manually port the flag to the new source file.
19389         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
19390         return newSourceFile;
19391     }
19392     ts.updateSourceFile = updateSourceFile;
19393     /* @internal */
19394     function parseIsolatedJSDocComment(content, start, length) {
19395         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
19396         if (result && result.jsDoc) {
19397             // because the jsDocComment was parsed out of the source file, it might
19398             // not be covered by the fixupParentReferences.
19399             Parser.fixupParentReferences(result.jsDoc);
19400         }
19401         return result;
19402     }
19403     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
19404     /* @internal */
19405     // Exposed only for testing.
19406     function parseJSDocTypeExpressionForTests(content, start, length) {
19407         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
19408     }
19409     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
19410     // Implement the parser as a singleton module.  We do this for perf reasons because creating
19411     // parser instances can actually be expensive enough to impact us on projects with many source
19412     // files.
19413     var Parser;
19414     (function (Parser) {
19415         // Share a single scanner across all calls to parse a source file.  This helps speed things
19416         // up by avoiding the cost of creating/compiling scanners over and over again.
19417         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
19418         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
19419         // capture constructors in 'initializeState' to avoid null checks
19420         var NodeConstructor;
19421         var TokenConstructor;
19422         var IdentifierConstructor;
19423         var PrivateIdentifierConstructor;
19424         var SourceFileConstructor;
19425         var sourceFile;
19426         var parseDiagnostics;
19427         var syntaxCursor;
19428         var currentToken;
19429         var sourceText;
19430         var nodeCount;
19431         var identifiers;
19432         var privateIdentifiers;
19433         var identifierCount;
19434         var parsingContext;
19435         var notParenthesizedArrow;
19436         // Flags that dictate what parsing context we're in.  For example:
19437         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
19438         // that some tokens that would be considered identifiers may be considered keywords.
19439         //
19440         // When adding more parser context flags, consider which is the more common case that the
19441         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
19442         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
19443         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
19444         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
19445         // all nodes would need extra state on them to store this info.
19446         //
19447         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
19448         // grammar specification.
19449         //
19450         // An important thing about these context concepts.  By default they are effectively inherited
19451         // while parsing through every grammar production.  i.e. if you don't change them, then when
19452         // you parse a sub-production, it will have the same context values as the parent production.
19453         // This is great most of the time.  After all, consider all the 'expression' grammar productions
19454         // and how nearly all of them pass along the 'in' and 'yield' context values:
19455         //
19456         // EqualityExpression[In, Yield] :
19457         //      RelationalExpression[?In, ?Yield]
19458         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
19459         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
19460         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
19461         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
19462         //
19463         // Where you have to be careful is then understanding what the points are in the grammar
19464         // where the values are *not* passed along.  For example:
19465         //
19466         // SingleNameBinding[Yield,GeneratorParameter]
19467         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
19468         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
19469         //
19470         // Here this is saying that if the GeneratorParameter context flag is set, that we should
19471         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
19472         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
19473         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
19474         // should leave the 'yield' context flag alone.
19475         //
19476         // Getting this all correct is tricky and requires careful reading of the grammar to
19477         // understand when these values should be changed versus when they should be inherited.
19478         //
19479         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
19480         // parsing.  These context flags are naturally stored and restored through normal recursive
19481         // descent parsing and unwinding.
19482         var contextFlags;
19483         // Whether or not we've had a parse error since creating the last AST node.  If we have
19484         // encountered an error, it will be stored on the next AST node we create.  Parse errors
19485         // can be broken down into three categories:
19486         //
19487         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
19488         //    character that was completely not understood.
19489         //
19490         // 2) A token was expected, but was not present.  This type of error is commonly produced
19491         //    by the 'parseExpected' function.
19492         //
19493         // 3) A token was present that no parsing function was able to consume.  This type of error
19494         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
19495         //    decides to skip the token.
19496         //
19497         // In all of these cases, we want to mark the next node as having had an error before it.
19498         // With this mark, we can know in incremental settings if this node can be reused, or if
19499         // we have to reparse it.  If we don't keep this information around, we may just reuse the
19500         // node.  in that event we would then not produce the same errors as we did before, causing
19501         // significant confusion problems.
19502         //
19503         // Note: it is necessary that this value be saved/restored during speculative/lookahead
19504         // parsing.  During lookahead parsing, we will often create a node.  That node will have
19505         // this value attached, and then this value will be set back to 'false'.  If we decide to
19506         // rewind, we must get back to the same value we had prior to the lookahead.
19507         //
19508         // Note: any errors at the end of the file that do not precede a regular node, should get
19509         // attached to the EOF token.
19510         var parseErrorBeforeNextFinishedNode = false;
19511         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
19512             if (setParentNodes === void 0) { setParentNodes = false; }
19513             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
19514             if (scriptKind === 6 /* JSON */) {
19515                 var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
19516                 ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
19517                 result_2.referencedFiles = ts.emptyArray;
19518                 result_2.typeReferenceDirectives = ts.emptyArray;
19519                 result_2.libReferenceDirectives = ts.emptyArray;
19520                 result_2.amdDependencies = ts.emptyArray;
19521                 result_2.hasNoDefaultLib = false;
19522                 result_2.pragmas = ts.emptyMap;
19523                 return result_2;
19524             }
19525             initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
19526             var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind);
19527             clearState();
19528             return result;
19529         }
19530         Parser.parseSourceFile = parseSourceFile;
19531         function parseIsolatedEntityName(content, languageVersion) {
19532             // Choice of `isDeclarationFile` should be arbitrary
19533             initializeState(content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
19534             // Prime the scanner.
19535             nextToken();
19536             var entityName = parseEntityName(/*allowReservedWords*/ true);
19537             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
19538             clearState();
19539             return isInvalid ? entityName : undefined;
19540         }
19541         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
19542         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
19543             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
19544             initializeState(sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
19545             // Set source file so that errors will be reported with this file name
19546             sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false);
19547             sourceFile.flags = contextFlags;
19548             // Prime the scanner.
19549             nextToken();
19550             var pos = getNodePos();
19551             if (token() === 1 /* EndOfFileToken */) {
19552                 sourceFile.statements = createNodeArray([], pos, pos);
19553                 sourceFile.endOfFileToken = parseTokenNode();
19554             }
19555             else {
19556                 var statement = createNode(226 /* ExpressionStatement */);
19557                 switch (token()) {
19558                     case 22 /* OpenBracketToken */:
19559                         statement.expression = parseArrayLiteralExpression();
19560                         break;
19561                     case 106 /* TrueKeyword */:
19562                     case 91 /* FalseKeyword */:
19563                     case 100 /* NullKeyword */:
19564                         statement.expression = parseTokenNode();
19565                         break;
19566                     case 40 /* MinusToken */:
19567                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
19568                             statement.expression = parsePrefixUnaryExpression();
19569                         }
19570                         else {
19571                             statement.expression = parseObjectLiteralExpression();
19572                         }
19573                         break;
19574                     case 8 /* NumericLiteral */:
19575                     case 10 /* StringLiteral */:
19576                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
19577                             statement.expression = parseLiteralNode();
19578                             break;
19579                         }
19580                     // falls through
19581                     default:
19582                         statement.expression = parseObjectLiteralExpression();
19583                         break;
19584                 }
19585                 finishNode(statement);
19586                 sourceFile.statements = createNodeArray([statement], pos);
19587                 sourceFile.endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
19588             }
19589             if (setParentNodes) {
19590                 fixupParentReferences(sourceFile);
19591             }
19592             sourceFile.nodeCount = nodeCount;
19593             sourceFile.identifierCount = identifierCount;
19594             sourceFile.identifiers = identifiers;
19595             sourceFile.parseDiagnostics = parseDiagnostics;
19596             var result = sourceFile;
19597             clearState();
19598             return result;
19599         }
19600         Parser.parseJsonText = parseJsonText;
19601         function getLanguageVariant(scriptKind) {
19602             // .tsx and .jsx files are treated as jsx language variant.
19603             return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
19604         }
19605         function initializeState(_sourceText, languageVersion, _syntaxCursor, scriptKind) {
19606             NodeConstructor = ts.objectAllocator.getNodeConstructor();
19607             TokenConstructor = ts.objectAllocator.getTokenConstructor();
19608             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
19609             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
19610             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
19611             sourceText = _sourceText;
19612             syntaxCursor = _syntaxCursor;
19613             parseDiagnostics = [];
19614             parsingContext = 0;
19615             identifiers = ts.createMap();
19616             privateIdentifiers = ts.createMap();
19617             identifierCount = 0;
19618             nodeCount = 0;
19619             switch (scriptKind) {
19620                 case 1 /* JS */:
19621                 case 2 /* JSX */:
19622                     contextFlags = 131072 /* JavaScriptFile */;
19623                     break;
19624                 case 6 /* JSON */:
19625                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
19626                     break;
19627                 default:
19628                     contextFlags = 0 /* None */;
19629                     break;
19630             }
19631             parseErrorBeforeNextFinishedNode = false;
19632             // Initialize and prime the scanner before parsing the source elements.
19633             scanner.setText(sourceText);
19634             scanner.setOnError(scanError);
19635             scanner.setScriptTarget(languageVersion);
19636             scanner.setLanguageVariant(getLanguageVariant(scriptKind));
19637         }
19638         function clearState() {
19639             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
19640             scanner.clearCommentDirectives();
19641             scanner.setText("");
19642             scanner.setOnError(undefined);
19643             // Clear any data.  We don't want to accidentally hold onto it for too long.
19644             parseDiagnostics = undefined;
19645             sourceFile = undefined;
19646             identifiers = undefined;
19647             syntaxCursor = undefined;
19648             sourceText = undefined;
19649             notParenthesizedArrow = undefined;
19650         }
19651         function parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind) {
19652             var isDeclarationFile = isDeclarationFileName(fileName);
19653             if (isDeclarationFile) {
19654                 contextFlags |= 8388608 /* Ambient */;
19655             }
19656             sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile);
19657             sourceFile.flags = contextFlags;
19658             // Prime the scanner.
19659             nextToken();
19660             // 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
19661             processCommentPragmas(sourceFile, sourceText);
19662             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
19663             sourceFile.statements = parseList(0 /* SourceElements */, parseStatement);
19664             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
19665             sourceFile.endOfFileToken = addJSDocComment(parseTokenNode());
19666             setExternalModuleIndicator(sourceFile);
19667             sourceFile.commentDirectives = scanner.getCommentDirectives();
19668             sourceFile.nodeCount = nodeCount;
19669             sourceFile.identifierCount = identifierCount;
19670             sourceFile.identifiers = identifiers;
19671             sourceFile.parseDiagnostics = parseDiagnostics;
19672             if (setParentNodes) {
19673                 fixupParentReferences(sourceFile);
19674             }
19675             return sourceFile;
19676             function reportPragmaDiagnostic(pos, end, diagnostic) {
19677                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, pos, end, diagnostic));
19678             }
19679         }
19680         function addJSDocComment(node) {
19681             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
19682             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceFile.text), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
19683             if (jsDoc.length)
19684                 node.jsDoc = jsDoc;
19685             return node;
19686         }
19687         function fixupParentReferences(rootNode) {
19688             // normally parent references are set during binding. However, for clients that only need
19689             // a syntax tree, and no semantic features, then the binding process is an unnecessary
19690             // overhead.  This functions allows us to set all the parents, without all the expense of
19691             // binding.
19692             forEachChildRecursively(rootNode, bindParentToChild);
19693             function bindParentToChild(child, parent) {
19694                 child.parent = parent;
19695                 if (ts.hasJSDocNodes(child)) {
19696                     for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19697                         var doc = _a[_i];
19698                         bindParentToChild(doc, child);
19699                         forEachChildRecursively(doc, bindParentToChild);
19700                     }
19701                 }
19702             }
19703         }
19704         Parser.fixupParentReferences = fixupParentReferences;
19705         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile) {
19706             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
19707             // this is quite rare comparing to other nodes and createNode should be as fast as possible
19708             var sourceFile = new SourceFileConstructor(290 /* SourceFile */, /*pos*/ 0, /* end */ sourceText.length);
19709             nodeCount++;
19710             sourceFile.text = sourceText;
19711             sourceFile.bindDiagnostics = [];
19712             sourceFile.bindSuggestionDiagnostics = undefined;
19713             sourceFile.languageVersion = languageVersion;
19714             sourceFile.fileName = ts.normalizePath(fileName);
19715             sourceFile.languageVariant = getLanguageVariant(scriptKind);
19716             sourceFile.isDeclarationFile = isDeclarationFile;
19717             sourceFile.scriptKind = scriptKind;
19718             return sourceFile;
19719         }
19720         function setContextFlag(val, flag) {
19721             if (val) {
19722                 contextFlags |= flag;
19723             }
19724             else {
19725                 contextFlags &= ~flag;
19726             }
19727         }
19728         function setDisallowInContext(val) {
19729             setContextFlag(val, 4096 /* DisallowInContext */);
19730         }
19731         function setYieldContext(val) {
19732             setContextFlag(val, 8192 /* YieldContext */);
19733         }
19734         function setDecoratorContext(val) {
19735             setContextFlag(val, 16384 /* DecoratorContext */);
19736         }
19737         function setAwaitContext(val) {
19738             setContextFlag(val, 32768 /* AwaitContext */);
19739         }
19740         function doOutsideOfContext(context, func) {
19741             // contextFlagsToClear will contain only the context flags that are
19742             // currently set that we need to temporarily clear
19743             // We don't just blindly reset to the previous flags to ensure
19744             // that we do not mutate cached flags for the incremental
19745             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19746             // HasAggregatedChildData).
19747             var contextFlagsToClear = context & contextFlags;
19748             if (contextFlagsToClear) {
19749                 // clear the requested context flags
19750                 setContextFlag(/*val*/ false, contextFlagsToClear);
19751                 var result = func();
19752                 // restore the context flags we just cleared
19753                 setContextFlag(/*val*/ true, contextFlagsToClear);
19754                 return result;
19755             }
19756             // no need to do anything special as we are not in any of the requested contexts
19757             return func();
19758         }
19759         function doInsideOfContext(context, func) {
19760             // contextFlagsToSet will contain only the context flags that
19761             // are not currently set that we need to temporarily enable.
19762             // We don't just blindly reset to the previous flags to ensure
19763             // that we do not mutate cached flags for the incremental
19764             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
19765             // HasAggregatedChildData).
19766             var contextFlagsToSet = context & ~contextFlags;
19767             if (contextFlagsToSet) {
19768                 // set the requested context flags
19769                 setContextFlag(/*val*/ true, contextFlagsToSet);
19770                 var result = func();
19771                 // reset the context flags we just set
19772                 setContextFlag(/*val*/ false, contextFlagsToSet);
19773                 return result;
19774             }
19775             // no need to do anything special as we are already in all of the requested contexts
19776             return func();
19777         }
19778         function allowInAnd(func) {
19779             return doOutsideOfContext(4096 /* DisallowInContext */, func);
19780         }
19781         function disallowInAnd(func) {
19782             return doInsideOfContext(4096 /* DisallowInContext */, func);
19783         }
19784         function doInYieldContext(func) {
19785             return doInsideOfContext(8192 /* YieldContext */, func);
19786         }
19787         function doInDecoratorContext(func) {
19788             return doInsideOfContext(16384 /* DecoratorContext */, func);
19789         }
19790         function doInAwaitContext(func) {
19791             return doInsideOfContext(32768 /* AwaitContext */, func);
19792         }
19793         function doOutsideOfAwaitContext(func) {
19794             return doOutsideOfContext(32768 /* AwaitContext */, func);
19795         }
19796         function doInYieldAndAwaitContext(func) {
19797             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19798         }
19799         function doOutsideOfYieldAndAwaitContext(func) {
19800             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
19801         }
19802         function inContext(flags) {
19803             return (contextFlags & flags) !== 0;
19804         }
19805         function inYieldContext() {
19806             return inContext(8192 /* YieldContext */);
19807         }
19808         function inDisallowInContext() {
19809             return inContext(4096 /* DisallowInContext */);
19810         }
19811         function inDecoratorContext() {
19812             return inContext(16384 /* DecoratorContext */);
19813         }
19814         function inAwaitContext() {
19815             return inContext(32768 /* AwaitContext */);
19816         }
19817         function parseErrorAtCurrentToken(message, arg0) {
19818             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
19819         }
19820         function parseErrorAtPosition(start, length, message, arg0) {
19821             // Don't report another error if it would just be at the same position as the last error.
19822             var lastError = ts.lastOrUndefined(parseDiagnostics);
19823             if (!lastError || start !== lastError.start) {
19824                 parseDiagnostics.push(ts.createFileDiagnostic(sourceFile, start, length, message, arg0));
19825             }
19826             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
19827             // node we finish so that it can't be reused incrementally.
19828             parseErrorBeforeNextFinishedNode = true;
19829         }
19830         function parseErrorAt(start, end, message, arg0) {
19831             parseErrorAtPosition(start, end - start, message, arg0);
19832         }
19833         function parseErrorAtRange(range, message, arg0) {
19834             parseErrorAt(range.pos, range.end, message, arg0);
19835         }
19836         function scanError(message, length) {
19837             parseErrorAtPosition(scanner.getTextPos(), length, message);
19838         }
19839         function getNodePos() {
19840             return scanner.getStartPos();
19841         }
19842         // Use this function to access the current token instead of reading the currentToken
19843         // variable. Since function results aren't narrowed in control flow analysis, this ensures
19844         // that the type checker doesn't make wrong assumptions about the type of the current
19845         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
19846         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
19847         // there is no performance penalty.
19848         function token() {
19849             return currentToken;
19850         }
19851         function nextTokenWithoutCheck() {
19852             return currentToken = scanner.scan();
19853         }
19854         function nextToken() {
19855             // if the keyword had an escape
19856             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
19857                 // issue a parse error for the escape
19858                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
19859             }
19860             return nextTokenWithoutCheck();
19861         }
19862         function nextTokenJSDoc() {
19863             return currentToken = scanner.scanJsDocToken();
19864         }
19865         function reScanGreaterToken() {
19866             return currentToken = scanner.reScanGreaterToken();
19867         }
19868         function reScanSlashToken() {
19869             return currentToken = scanner.reScanSlashToken();
19870         }
19871         function reScanTemplateToken(isTaggedTemplate) {
19872             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
19873         }
19874         function reScanTemplateHeadOrNoSubstitutionTemplate() {
19875             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
19876         }
19877         function reScanLessThanToken() {
19878             return currentToken = scanner.reScanLessThanToken();
19879         }
19880         function scanJsxIdentifier() {
19881             return currentToken = scanner.scanJsxIdentifier();
19882         }
19883         function scanJsxText() {
19884             return currentToken = scanner.scanJsxToken();
19885         }
19886         function scanJsxAttributeValue() {
19887             return currentToken = scanner.scanJsxAttributeValue();
19888         }
19889         function speculationHelper(callback, isLookAhead) {
19890             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
19891             // caller asked us to always reset our state).
19892             var saveToken = currentToken;
19893             var saveParseDiagnosticsLength = parseDiagnostics.length;
19894             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
19895             // Note: it is not actually necessary to save/restore the context flags here.  That's
19896             // because the saving/restoring of these flags happens naturally through the recursive
19897             // descent nature of our parser.  However, we still store this here just so we can
19898             // assert that invariant holds.
19899             var saveContextFlags = contextFlags;
19900             // If we're only looking ahead, then tell the scanner to only lookahead as well.
19901             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
19902             // same.
19903             var result = isLookAhead
19904                 ? scanner.lookAhead(callback)
19905                 : scanner.tryScan(callback);
19906             ts.Debug.assert(saveContextFlags === contextFlags);
19907             // If our callback returned something 'falsy' or we're just looking ahead,
19908             // then unconditionally restore us to where we were.
19909             if (!result || isLookAhead) {
19910                 currentToken = saveToken;
19911                 parseDiagnostics.length = saveParseDiagnosticsLength;
19912                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
19913             }
19914             return result;
19915         }
19916         /** Invokes the provided callback then unconditionally restores the parser to the state it
19917          * was in immediately prior to invoking the callback.  The result of invoking the callback
19918          * is returned from this function.
19919          */
19920         function lookAhead(callback) {
19921             return speculationHelper(callback, /*isLookAhead*/ true);
19922         }
19923         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
19924          * the parser to the state it was in immediately prior to invoking the callback.  If the
19925          * callback returns something truthy, then the parser state is not rolled back.  The result
19926          * of invoking the callback is returned from this function.
19927          */
19928         function tryParse(callback) {
19929             return speculationHelper(callback, /*isLookAhead*/ false);
19930         }
19931         // Ignore strict mode flag because we will report an error in type checker instead.
19932         function isIdentifier() {
19933             if (token() === 75 /* Identifier */) {
19934                 return true;
19935             }
19936             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
19937             // considered a keyword and is not an identifier.
19938             if (token() === 121 /* YieldKeyword */ && inYieldContext()) {
19939                 return false;
19940             }
19941             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
19942             // considered a keyword and is not an identifier.
19943             if (token() === 127 /* AwaitKeyword */ && inAwaitContext()) {
19944                 return false;
19945             }
19946             return token() > 112 /* LastReservedWord */;
19947         }
19948         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
19949             if (shouldAdvance === void 0) { shouldAdvance = true; }
19950             if (token() === kind) {
19951                 if (shouldAdvance) {
19952                     nextToken();
19953                 }
19954                 return true;
19955             }
19956             // Report specific message if provided with one.  Otherwise, report generic fallback message.
19957             if (diagnosticMessage) {
19958                 parseErrorAtCurrentToken(diagnosticMessage);
19959             }
19960             else {
19961                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19962             }
19963             return false;
19964         }
19965         function parseExpectedJSDoc(kind) {
19966             if (token() === kind) {
19967                 nextTokenJSDoc();
19968                 return true;
19969             }
19970             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
19971             return false;
19972         }
19973         function parseOptional(t) {
19974             if (token() === t) {
19975                 nextToken();
19976                 return true;
19977             }
19978             return false;
19979         }
19980         function parseOptionalToken(t) {
19981             if (token() === t) {
19982                 return parseTokenNode();
19983             }
19984             return undefined;
19985         }
19986         function parseOptionalTokenJSDoc(t) {
19987             if (token() === t) {
19988                 return parseTokenNodeJSDoc();
19989             }
19990             return undefined;
19991         }
19992         function parseExpectedToken(t, diagnosticMessage, arg0) {
19993             return parseOptionalToken(t) ||
19994                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
19995         }
19996         function parseExpectedTokenJSDoc(t) {
19997             return parseOptionalTokenJSDoc(t) ||
19998                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
19999         }
20000         function parseTokenNode() {
20001             var node = createNode(token());
20002             nextToken();
20003             return finishNode(node);
20004         }
20005         function parseTokenNodeJSDoc() {
20006             var node = createNode(token());
20007             nextTokenJSDoc();
20008             return finishNode(node);
20009         }
20010         function canParseSemicolon() {
20011             // If there's a real semicolon, then we can always parse it out.
20012             if (token() === 26 /* SemicolonToken */) {
20013                 return true;
20014             }
20015             // We can parse out an optional semicolon in ASI cases in the following cases.
20016             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
20017         }
20018         function parseSemicolon() {
20019             if (canParseSemicolon()) {
20020                 if (token() === 26 /* SemicolonToken */) {
20021                     // consume the semicolon if it was explicitly provided.
20022                     nextToken();
20023                 }
20024                 return true;
20025             }
20026             else {
20027                 return parseExpected(26 /* SemicolonToken */);
20028             }
20029         }
20030         function createNode(kind, pos) {
20031             nodeCount++;
20032             var p = pos >= 0 ? pos : scanner.getStartPos();
20033             return ts.isNodeKind(kind) || kind === 0 /* Unknown */ ? new NodeConstructor(kind, p, p) :
20034                 kind === 75 /* Identifier */ ? new IdentifierConstructor(kind, p, p) :
20035                     kind === 76 /* PrivateIdentifier */ ? new PrivateIdentifierConstructor(kind, p, p) :
20036                         new TokenConstructor(kind, p, p);
20037         }
20038         function createNodeWithJSDoc(kind, pos) {
20039             var node = createNode(kind, pos);
20040             if (scanner.getTokenFlags() & 2 /* PrecedingJSDocComment */ && (kind !== 226 /* ExpressionStatement */ || token() !== 20 /* OpenParenToken */)) {
20041                 addJSDocComment(node);
20042             }
20043             return node;
20044         }
20045         function createNodeArray(elements, pos, end) {
20046             // Since the element list of a node array is typically created by starting with an empty array and
20047             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20048             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20049             var length = elements.length;
20050             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20051             array.pos = pos;
20052             array.end = end === undefined ? scanner.getStartPos() : end;
20053             return array;
20054         }
20055         function finishNode(node, end) {
20056             node.end = end === undefined ? scanner.getStartPos() : end;
20057             if (contextFlags) {
20058                 node.flags |= contextFlags;
20059             }
20060             // Keep track on the node if we encountered an error while parsing it.  If we did, then
20061             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
20062             // flag so that we don't mark any subsequent nodes.
20063             if (parseErrorBeforeNextFinishedNode) {
20064                 parseErrorBeforeNextFinishedNode = false;
20065                 node.flags |= 65536 /* ThisNodeHasError */;
20066             }
20067             return node;
20068         }
20069         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
20070             if (reportAtCurrentPosition) {
20071                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
20072             }
20073             else if (diagnosticMessage) {
20074                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
20075             }
20076             var result = createNode(kind);
20077             if (kind === 75 /* Identifier */) {
20078                 result.escapedText = "";
20079             }
20080             else if (ts.isLiteralKind(kind) || ts.isTemplateLiteralKind(kind)) {
20081                 result.text = "";
20082             }
20083             return finishNode(result);
20084         }
20085         function internIdentifier(text) {
20086             var identifier = identifiers.get(text);
20087             if (identifier === undefined) {
20088                 identifiers.set(text, identifier = text);
20089             }
20090             return identifier;
20091         }
20092         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
20093         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
20094         // each identifier in order to reduce memory consumption.
20095         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
20096             identifierCount++;
20097             if (isIdentifier) {
20098                 var node = createNode(75 /* Identifier */);
20099                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
20100                 if (token() !== 75 /* Identifier */) {
20101                     node.originalKeywordKind = token();
20102                 }
20103                 node.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
20104                 nextTokenWithoutCheck();
20105                 return finishNode(node);
20106             }
20107             if (token() === 76 /* PrivateIdentifier */) {
20108                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
20109                 return createIdentifier(/*isIdentifier*/ true);
20110             }
20111             // Only for end of file because the error gets reported incorrectly on embedded script tags.
20112             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
20113             var isReservedWord = scanner.isReservedWord();
20114             var msgArg = scanner.getTokenText();
20115             var defaultMessage = isReservedWord ?
20116                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
20117                 ts.Diagnostics.Identifier_expected;
20118             return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
20119         }
20120         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
20121             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
20122         }
20123         function parseIdentifierName(diagnosticMessage) {
20124             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
20125         }
20126         function isLiteralPropertyName() {
20127             return ts.tokenIsIdentifierOrKeyword(token()) ||
20128                 token() === 10 /* StringLiteral */ ||
20129                 token() === 8 /* NumericLiteral */;
20130         }
20131         function parsePropertyNameWorker(allowComputedPropertyNames) {
20132             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
20133                 var node = parseLiteralNode();
20134                 node.text = internIdentifier(node.text);
20135                 return node;
20136             }
20137             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
20138                 return parseComputedPropertyName();
20139             }
20140             if (token() === 76 /* PrivateIdentifier */) {
20141                 return parsePrivateIdentifier();
20142             }
20143             return parseIdentifierName();
20144         }
20145         function parsePropertyName() {
20146             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
20147         }
20148         function parseComputedPropertyName() {
20149             // PropertyName [Yield]:
20150             //      LiteralPropertyName
20151             //      ComputedPropertyName[?Yield]
20152             var node = createNode(154 /* ComputedPropertyName */);
20153             parseExpected(22 /* OpenBracketToken */);
20154             // We parse any expression (including a comma expression). But the grammar
20155             // says that only an assignment expression is allowed, so the grammar checker
20156             // will error if it sees a comma expression.
20157             node.expression = allowInAnd(parseExpression);
20158             parseExpected(23 /* CloseBracketToken */);
20159             return finishNode(node);
20160         }
20161         function internPrivateIdentifier(text) {
20162             var privateIdentifier = privateIdentifiers.get(text);
20163             if (privateIdentifier === undefined) {
20164                 privateIdentifiers.set(text, privateIdentifier = text);
20165             }
20166             return privateIdentifier;
20167         }
20168         function parsePrivateIdentifier() {
20169             var node = createNode(76 /* PrivateIdentifier */);
20170             node.escapedText = ts.escapeLeadingUnderscores(internPrivateIdentifier(scanner.getTokenText()));
20171             nextToken();
20172             return finishNode(node);
20173         }
20174         function parseContextualModifier(t) {
20175             return token() === t && tryParse(nextTokenCanFollowModifier);
20176         }
20177         function nextTokenIsOnSameLineAndCanFollowModifier() {
20178             nextToken();
20179             if (scanner.hasPrecedingLineBreak()) {
20180                 return false;
20181             }
20182             return canFollowModifier();
20183         }
20184         function nextTokenCanFollowModifier() {
20185             switch (token()) {
20186                 case 81 /* ConstKeyword */:
20187                     // 'const' is only a modifier if followed by 'enum'.
20188                     return nextToken() === 88 /* EnumKeyword */;
20189                 case 89 /* ExportKeyword */:
20190                     nextToken();
20191                     if (token() === 84 /* DefaultKeyword */) {
20192                         return lookAhead(nextTokenCanFollowDefaultKeyword);
20193                     }
20194                     if (token() === 145 /* TypeKeyword */) {
20195                         return lookAhead(nextTokenCanFollowExportModifier);
20196                     }
20197                     return canFollowExportModifier();
20198                 case 84 /* DefaultKeyword */:
20199                     return nextTokenCanFollowDefaultKeyword();
20200                 case 120 /* StaticKeyword */:
20201                 case 131 /* GetKeyword */:
20202                 case 142 /* SetKeyword */:
20203                     nextToken();
20204                     return canFollowModifier();
20205                 default:
20206                     return nextTokenIsOnSameLineAndCanFollowModifier();
20207             }
20208         }
20209         function canFollowExportModifier() {
20210             return token() !== 41 /* AsteriskToken */
20211                 && token() !== 123 /* AsKeyword */
20212                 && token() !== 18 /* OpenBraceToken */
20213                 && canFollowModifier();
20214         }
20215         function nextTokenCanFollowExportModifier() {
20216             nextToken();
20217             return canFollowExportModifier();
20218         }
20219         function parseAnyContextualModifier() {
20220             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
20221         }
20222         function canFollowModifier() {
20223             return token() === 22 /* OpenBracketToken */
20224                 || token() === 18 /* OpenBraceToken */
20225                 || token() === 41 /* AsteriskToken */
20226                 || token() === 25 /* DotDotDotToken */
20227                 || isLiteralPropertyName();
20228         }
20229         function nextTokenCanFollowDefaultKeyword() {
20230             nextToken();
20231             return token() === 80 /* ClassKeyword */ || token() === 94 /* FunctionKeyword */ ||
20232                 token() === 114 /* InterfaceKeyword */ ||
20233                 (token() === 122 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
20234                 (token() === 126 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
20235         }
20236         // True if positioned at the start of a list element
20237         function isListElement(parsingContext, inErrorRecovery) {
20238             var node = currentNode(parsingContext);
20239             if (node) {
20240                 return true;
20241             }
20242             switch (parsingContext) {
20243                 case 0 /* SourceElements */:
20244                 case 1 /* BlockStatements */:
20245                 case 3 /* SwitchClauseStatements */:
20246                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
20247                     // The problem is that ';' can show up in far too many contexts, and if we see one
20248                     // and assume it's a statement, then we may bail out inappropriately from whatever
20249                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
20250                     // we really don't want to assume the class is over and we're on a statement in the
20251                     // outer module.  We just want to consume and move on.
20252                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
20253                 case 2 /* SwitchClauses */:
20254                     return token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20255                 case 4 /* TypeMembers */:
20256                     return lookAhead(isTypeMemberStart);
20257                 case 5 /* ClassMembers */:
20258                     // We allow semicolons as class elements (as specified by ES6) as long as we're
20259                     // not in error recovery.  If we're in error recovery, we don't want an errant
20260                     // semicolon to be treated as a class member (since they're almost always used
20261                     // for statements.
20262                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
20263                 case 6 /* EnumMembers */:
20264                     // Include open bracket computed properties. This technically also lets in indexers,
20265                     // which would be a candidate for improved error reporting.
20266                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
20267                 case 12 /* ObjectLiteralMembers */:
20268                     switch (token()) {
20269                         case 22 /* OpenBracketToken */:
20270                         case 41 /* AsteriskToken */:
20271                         case 25 /* DotDotDotToken */:
20272                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
20273                             return true;
20274                         default:
20275                             return isLiteralPropertyName();
20276                     }
20277                 case 18 /* RestProperties */:
20278                     return isLiteralPropertyName();
20279                 case 9 /* ObjectBindingElements */:
20280                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
20281                 case 7 /* HeritageClauseElement */:
20282                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
20283                     // That way we won't consume the body of a class in its heritage clause.
20284                     if (token() === 18 /* OpenBraceToken */) {
20285                         return lookAhead(isValidHeritageClauseObjectLiteral);
20286                     }
20287                     if (!inErrorRecovery) {
20288                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
20289                     }
20290                     else {
20291                         // If we're in error recovery we tighten up what we're willing to match.
20292                         // That way we don't treat something like "this" as a valid heritage clause
20293                         // element during recovery.
20294                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
20295                     }
20296                 case 8 /* VariableDeclarations */:
20297                     return isIdentifierOrPrivateIdentifierOrPattern();
20298                 case 10 /* ArrayBindingElements */:
20299                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isIdentifierOrPrivateIdentifierOrPattern();
20300                 case 19 /* TypeParameters */:
20301                     return isIdentifier();
20302                 case 15 /* ArrayLiteralMembers */:
20303                     switch (token()) {
20304                         case 27 /* CommaToken */:
20305                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
20306                             return true;
20307                     }
20308                 // falls through
20309                 case 11 /* ArgumentExpressions */:
20310                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
20311                 case 16 /* Parameters */:
20312                     return isStartOfParameter(/*isJSDocParameter*/ false);
20313                 case 17 /* JSDocParameters */:
20314                     return isStartOfParameter(/*isJSDocParameter*/ true);
20315                 case 20 /* TypeArguments */:
20316                 case 21 /* TupleElementTypes */:
20317                     return token() === 27 /* CommaToken */ || isStartOfType();
20318                 case 22 /* HeritageClauses */:
20319                     return isHeritageClause();
20320                 case 23 /* ImportOrExportSpecifiers */:
20321                     return ts.tokenIsIdentifierOrKeyword(token());
20322                 case 13 /* JsxAttributes */:
20323                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
20324                 case 14 /* JsxChildren */:
20325                     return true;
20326             }
20327             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
20328         }
20329         function isValidHeritageClauseObjectLiteral() {
20330             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
20331             if (nextToken() === 19 /* CloseBraceToken */) {
20332                 // if we see "extends {}" then only treat the {} as what we're extending (and not
20333                 // the class body) if we have:
20334                 //
20335                 //      extends {} {
20336                 //      extends {},
20337                 //      extends {} extends
20338                 //      extends {} implements
20339                 var next = nextToken();
20340                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 90 /* ExtendsKeyword */ || next === 113 /* ImplementsKeyword */;
20341             }
20342             return true;
20343         }
20344         function nextTokenIsIdentifier() {
20345             nextToken();
20346             return isIdentifier();
20347         }
20348         function nextTokenIsIdentifierOrKeyword() {
20349             nextToken();
20350             return ts.tokenIsIdentifierOrKeyword(token());
20351         }
20352         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
20353             nextToken();
20354             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
20355         }
20356         function isHeritageClauseExtendsOrImplementsKeyword() {
20357             if (token() === 113 /* ImplementsKeyword */ ||
20358                 token() === 90 /* ExtendsKeyword */) {
20359                 return lookAhead(nextTokenIsStartOfExpression);
20360             }
20361             return false;
20362         }
20363         function nextTokenIsStartOfExpression() {
20364             nextToken();
20365             return isStartOfExpression();
20366         }
20367         function nextTokenIsStartOfType() {
20368             nextToken();
20369             return isStartOfType();
20370         }
20371         // True if positioned at a list terminator
20372         function isListTerminator(kind) {
20373             if (token() === 1 /* EndOfFileToken */) {
20374                 // Being at the end of the file ends all lists.
20375                 return true;
20376             }
20377             switch (kind) {
20378                 case 1 /* BlockStatements */:
20379                 case 2 /* SwitchClauses */:
20380                 case 4 /* TypeMembers */:
20381                 case 5 /* ClassMembers */:
20382                 case 6 /* EnumMembers */:
20383                 case 12 /* ObjectLiteralMembers */:
20384                 case 9 /* ObjectBindingElements */:
20385                 case 23 /* ImportOrExportSpecifiers */:
20386                     return token() === 19 /* CloseBraceToken */;
20387                 case 3 /* SwitchClauseStatements */:
20388                     return token() === 19 /* CloseBraceToken */ || token() === 78 /* CaseKeyword */ || token() === 84 /* DefaultKeyword */;
20389                 case 7 /* HeritageClauseElement */:
20390                     return token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20391                 case 8 /* VariableDeclarations */:
20392                     return isVariableDeclaratorListTerminator();
20393                 case 19 /* TypeParameters */:
20394                     // Tokens other than '>' are here for better error recovery
20395                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
20396                 case 11 /* ArgumentExpressions */:
20397                     // Tokens other than ')' are here for better error recovery
20398                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
20399                 case 15 /* ArrayLiteralMembers */:
20400                 case 21 /* TupleElementTypes */:
20401                 case 10 /* ArrayBindingElements */:
20402                     return token() === 23 /* CloseBracketToken */;
20403                 case 17 /* JSDocParameters */:
20404                 case 16 /* Parameters */:
20405                 case 18 /* RestProperties */:
20406                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
20407                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
20408                 case 20 /* TypeArguments */:
20409                     // All other tokens should cause the type-argument to terminate except comma token
20410                     return token() !== 27 /* CommaToken */;
20411                 case 22 /* HeritageClauses */:
20412                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
20413                 case 13 /* JsxAttributes */:
20414                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
20415                 case 14 /* JsxChildren */:
20416                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
20417                 default:
20418                     return false;
20419             }
20420         }
20421         function isVariableDeclaratorListTerminator() {
20422             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
20423             // with parsing the list of variable declarators.
20424             if (canParseSemicolon()) {
20425                 return true;
20426             }
20427             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
20428             // are done if we see an 'in' keyword in front of us. Same with for-of
20429             if (isInOrOfKeyword(token())) {
20430                 return true;
20431             }
20432             // ERROR RECOVERY TWEAK:
20433             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
20434             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
20435             // another variable declaration.
20436             if (token() === 38 /* EqualsGreaterThanToken */) {
20437                 return true;
20438             }
20439             // Keep trying to parse out variable declarators.
20440             return false;
20441         }
20442         // True if positioned at element or terminator of the current list or any enclosing list
20443         function isInSomeParsingContext() {
20444             for (var kind = 0; kind < 24 /* Count */; kind++) {
20445                 if (parsingContext & (1 << kind)) {
20446                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
20447                         return true;
20448                     }
20449                 }
20450             }
20451             return false;
20452         }
20453         // Parses a list of elements
20454         function parseList(kind, parseElement) {
20455             var saveParsingContext = parsingContext;
20456             parsingContext |= 1 << kind;
20457             var list = [];
20458             var listPos = getNodePos();
20459             while (!isListTerminator(kind)) {
20460                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20461                     var element = parseListElement(kind, parseElement);
20462                     list.push(element);
20463                     continue;
20464                 }
20465                 if (abortParsingListOrMoveToNextToken(kind)) {
20466                     break;
20467                 }
20468             }
20469             parsingContext = saveParsingContext;
20470             return createNodeArray(list, listPos);
20471         }
20472         function parseListElement(parsingContext, parseElement) {
20473             var node = currentNode(parsingContext);
20474             if (node) {
20475                 return consumeNode(node);
20476             }
20477             return parseElement();
20478         }
20479         function currentNode(parsingContext) {
20480             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
20481             //
20482             // If there is an outstanding parse error that we've encountered, but not attached to
20483             // some node, then we cannot get a node from the old source tree.  This is because we
20484             // want to mark the next node we encounter as being unusable.
20485             //
20486             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
20487             // on it (or its leftmost child) as having the error.  For now though, being conservative
20488             // is nice and likely won't ever affect perf.
20489             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
20490                 return undefined;
20491             }
20492             var node = syntaxCursor.currentNode(scanner.getStartPos());
20493             // Can't reuse a missing node.
20494             // Can't reuse a node that intersected the change range.
20495             // Can't reuse a node that contains a parse error.  This is necessary so that we
20496             // produce the same set of errors again.
20497             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
20498                 return undefined;
20499             }
20500             // We can only reuse a node if it was parsed under the same strict mode that we're
20501             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
20502             // the user added 'using strict' at the top of the file, then we can't use that node
20503             // again as the presence of strict mode may cause us to parse the tokens in the file
20504             // differently.
20505             //
20506             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
20507             // are unaffected by strict mode.  It's just the parser will decide what to do with it
20508             // differently depending on what mode it is in.
20509             //
20510             // This also applies to all our other context flags as well.
20511             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
20512             if (nodeContextFlags !== contextFlags) {
20513                 return undefined;
20514             }
20515             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
20516             // in the current list parsing context that we're currently at.
20517             if (!canReuseNode(node, parsingContext)) {
20518                 return undefined;
20519             }
20520             if (node.jsDocCache) {
20521                 // jsDocCache may include tags from parent nodes, which might have been modified.
20522                 node.jsDocCache = undefined;
20523             }
20524             return node;
20525         }
20526         function consumeNode(node) {
20527             // Move the scanner so it is after the node we just consumed.
20528             scanner.setTextPos(node.end);
20529             nextToken();
20530             return node;
20531         }
20532         function isReusableParsingContext(parsingContext) {
20533             switch (parsingContext) {
20534                 case 5 /* ClassMembers */:
20535                 case 2 /* SwitchClauses */:
20536                 case 0 /* SourceElements */:
20537                 case 1 /* BlockStatements */:
20538                 case 3 /* SwitchClauseStatements */:
20539                 case 6 /* EnumMembers */:
20540                 case 4 /* TypeMembers */:
20541                 case 8 /* VariableDeclarations */:
20542                 case 17 /* JSDocParameters */:
20543                 case 16 /* Parameters */:
20544                     return true;
20545             }
20546             return false;
20547         }
20548         function canReuseNode(node, parsingContext) {
20549             switch (parsingContext) {
20550                 case 5 /* ClassMembers */:
20551                     return isReusableClassMember(node);
20552                 case 2 /* SwitchClauses */:
20553                     return isReusableSwitchClause(node);
20554                 case 0 /* SourceElements */:
20555                 case 1 /* BlockStatements */:
20556                 case 3 /* SwitchClauseStatements */:
20557                     return isReusableStatement(node);
20558                 case 6 /* EnumMembers */:
20559                     return isReusableEnumMember(node);
20560                 case 4 /* TypeMembers */:
20561                     return isReusableTypeMember(node);
20562                 case 8 /* VariableDeclarations */:
20563                     return isReusableVariableDeclaration(node);
20564                 case 17 /* JSDocParameters */:
20565                 case 16 /* Parameters */:
20566                     return isReusableParameter(node);
20567                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
20568                 // you can do so safely.  Danger areas involve nodes that may involve speculative
20569                 // parsing.  If speculative parsing is involved with the node, then the range the
20570                 // parser reached while looking ahead might be in the edited range (see the example
20571                 // in canReuseVariableDeclaratorNode for a good case of this).
20572                 // case ParsingContext.HeritageClauses:
20573                 // This would probably be safe to reuse.  There is no speculative parsing with
20574                 // heritage clauses.
20575                 // case ParsingContext.TypeParameters:
20576                 // This would probably be safe to reuse.  There is no speculative parsing with
20577                 // type parameters.  Note that that's because type *parameters* only occur in
20578                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
20579                 // *expression* contexts.
20580                 // case ParsingContext.TupleElementTypes:
20581                 // This would probably be safe to reuse.  There is no speculative parsing with
20582                 // tuple types.
20583                 // Technically, type argument list types are probably safe to reuse.  While
20584                 // speculative parsing is involved with them (since type argument lists are only
20585                 // produced from speculative parsing a < as a type argument list), we only have
20586                 // the types because speculative parsing succeeded.  Thus, the lookahead never
20587                 // went past the end of the list and rewound.
20588                 // case ParsingContext.TypeArguments:
20589                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
20590                 // need a large amount of lookahead, and we should not reuse them as they may
20591                 // have actually intersected the edit.
20592                 // case ParsingContext.ArgumentExpressions:
20593                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
20594                 // cases.  i.e. a property assignment may end with an expression, and thus might
20595                 // have lookahead far beyond it's old node.
20596                 // case ParsingContext.ObjectLiteralMembers:
20597                 // This is probably not safe to reuse.  There can be speculative parsing with
20598                 // type names in a heritage clause.  There can be generic names in the type
20599                 // name list, and there can be left hand side expressions (which can have type
20600                 // arguments.)
20601                 // case ParsingContext.HeritageClauseElement:
20602                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
20603                 // on any given element. Same for children.
20604                 // case ParsingContext.JsxAttributes:
20605                 // case ParsingContext.JsxChildren:
20606             }
20607             return false;
20608         }
20609         function isReusableClassMember(node) {
20610             if (node) {
20611                 switch (node.kind) {
20612                     case 162 /* Constructor */:
20613                     case 167 /* IndexSignature */:
20614                     case 163 /* GetAccessor */:
20615                     case 164 /* SetAccessor */:
20616                     case 159 /* PropertyDeclaration */:
20617                     case 222 /* SemicolonClassElement */:
20618                         return true;
20619                     case 161 /* MethodDeclaration */:
20620                         // Method declarations are not necessarily reusable.  An object-literal
20621                         // may have a method calls "constructor(...)" and we must reparse that
20622                         // into an actual .ConstructorDeclaration.
20623                         var methodDeclaration = node;
20624                         var nameIsConstructor = methodDeclaration.name.kind === 75 /* Identifier */ &&
20625                             methodDeclaration.name.originalKeywordKind === 129 /* ConstructorKeyword */;
20626                         return !nameIsConstructor;
20627                 }
20628             }
20629             return false;
20630         }
20631         function isReusableSwitchClause(node) {
20632             if (node) {
20633                 switch (node.kind) {
20634                     case 277 /* CaseClause */:
20635                     case 278 /* DefaultClause */:
20636                         return true;
20637                 }
20638             }
20639             return false;
20640         }
20641         function isReusableStatement(node) {
20642             if (node) {
20643                 switch (node.kind) {
20644                     case 244 /* FunctionDeclaration */:
20645                     case 225 /* VariableStatement */:
20646                     case 223 /* Block */:
20647                     case 227 /* IfStatement */:
20648                     case 226 /* ExpressionStatement */:
20649                     case 239 /* ThrowStatement */:
20650                     case 235 /* ReturnStatement */:
20651                     case 237 /* SwitchStatement */:
20652                     case 234 /* BreakStatement */:
20653                     case 233 /* ContinueStatement */:
20654                     case 231 /* ForInStatement */:
20655                     case 232 /* ForOfStatement */:
20656                     case 230 /* ForStatement */:
20657                     case 229 /* WhileStatement */:
20658                     case 236 /* WithStatement */:
20659                     case 224 /* EmptyStatement */:
20660                     case 240 /* TryStatement */:
20661                     case 238 /* LabeledStatement */:
20662                     case 228 /* DoStatement */:
20663                     case 241 /* DebuggerStatement */:
20664                     case 254 /* ImportDeclaration */:
20665                     case 253 /* ImportEqualsDeclaration */:
20666                     case 260 /* ExportDeclaration */:
20667                     case 259 /* ExportAssignment */:
20668                     case 249 /* ModuleDeclaration */:
20669                     case 245 /* ClassDeclaration */:
20670                     case 246 /* InterfaceDeclaration */:
20671                     case 248 /* EnumDeclaration */:
20672                     case 247 /* TypeAliasDeclaration */:
20673                         return true;
20674                 }
20675             }
20676             return false;
20677         }
20678         function isReusableEnumMember(node) {
20679             return node.kind === 284 /* EnumMember */;
20680         }
20681         function isReusableTypeMember(node) {
20682             if (node) {
20683                 switch (node.kind) {
20684                     case 166 /* ConstructSignature */:
20685                     case 160 /* MethodSignature */:
20686                     case 167 /* IndexSignature */:
20687                     case 158 /* PropertySignature */:
20688                     case 165 /* CallSignature */:
20689                         return true;
20690                 }
20691             }
20692             return false;
20693         }
20694         function isReusableVariableDeclaration(node) {
20695             if (node.kind !== 242 /* VariableDeclaration */) {
20696                 return false;
20697             }
20698             // Very subtle incremental parsing bug.  Consider the following code:
20699             //
20700             //      let v = new List < A, B
20701             //
20702             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
20703             // on one side and "B" on the other. If you then change that to:
20704             //
20705             //      let v = new List < A, B >()
20706             //
20707             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
20708             // start reparsing at "B" and we completely fail to handle this properly.
20709             //
20710             // In order to prevent this, we do not allow a variable declarator to be reused if it
20711             // has an initializer.
20712             var variableDeclarator = node;
20713             return variableDeclarator.initializer === undefined;
20714         }
20715         function isReusableParameter(node) {
20716             if (node.kind !== 156 /* Parameter */) {
20717                 return false;
20718             }
20719             // See the comment in isReusableVariableDeclaration for why we do this.
20720             var parameter = node;
20721             return parameter.initializer === undefined;
20722         }
20723         // Returns true if we should abort parsing.
20724         function abortParsingListOrMoveToNextToken(kind) {
20725             parseErrorAtCurrentToken(parsingContextErrors(kind));
20726             if (isInSomeParsingContext()) {
20727                 return true;
20728             }
20729             nextToken();
20730             return false;
20731         }
20732         function parsingContextErrors(context) {
20733             switch (context) {
20734                 case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected;
20735                 case 1 /* BlockStatements */: return ts.Diagnostics.Declaration_or_statement_expected;
20736                 case 2 /* SwitchClauses */: return ts.Diagnostics.case_or_default_expected;
20737                 case 3 /* SwitchClauseStatements */: return ts.Diagnostics.Statement_expected;
20738                 case 18 /* RestProperties */: // fallthrough
20739                 case 4 /* TypeMembers */: return ts.Diagnostics.Property_or_signature_expected;
20740                 case 5 /* ClassMembers */: return ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected;
20741                 case 6 /* EnumMembers */: return ts.Diagnostics.Enum_member_expected;
20742                 case 7 /* HeritageClauseElement */: return ts.Diagnostics.Expression_expected;
20743                 case 8 /* VariableDeclarations */: return ts.Diagnostics.Variable_declaration_expected;
20744                 case 9 /* ObjectBindingElements */: return ts.Diagnostics.Property_destructuring_pattern_expected;
20745                 case 10 /* ArrayBindingElements */: return ts.Diagnostics.Array_element_destructuring_pattern_expected;
20746                 case 11 /* ArgumentExpressions */: return ts.Diagnostics.Argument_expression_expected;
20747                 case 12 /* ObjectLiteralMembers */: return ts.Diagnostics.Property_assignment_expected;
20748                 case 15 /* ArrayLiteralMembers */: return ts.Diagnostics.Expression_or_comma_expected;
20749                 case 17 /* JSDocParameters */: return ts.Diagnostics.Parameter_declaration_expected;
20750                 case 16 /* Parameters */: return ts.Diagnostics.Parameter_declaration_expected;
20751                 case 19 /* TypeParameters */: return ts.Diagnostics.Type_parameter_declaration_expected;
20752                 case 20 /* TypeArguments */: return ts.Diagnostics.Type_argument_expected;
20753                 case 21 /* TupleElementTypes */: return ts.Diagnostics.Type_expected;
20754                 case 22 /* HeritageClauses */: return ts.Diagnostics.Unexpected_token_expected;
20755                 case 23 /* ImportOrExportSpecifiers */: return ts.Diagnostics.Identifier_expected;
20756                 case 13 /* JsxAttributes */: return ts.Diagnostics.Identifier_expected;
20757                 case 14 /* JsxChildren */: return ts.Diagnostics.Identifier_expected;
20758                 default: return undefined; // TODO: GH#18217 `default: Debug.assertNever(context);`
20759             }
20760         }
20761         // Parses a comma-delimited list of elements
20762         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
20763             var saveParsingContext = parsingContext;
20764             parsingContext |= 1 << kind;
20765             var list = [];
20766             var listPos = getNodePos();
20767             var commaStart = -1; // Meaning the previous token was not a comma
20768             while (true) {
20769                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
20770                     var startPos = scanner.getStartPos();
20771                     list.push(parseListElement(kind, parseElement));
20772                     commaStart = scanner.getTokenPos();
20773                     if (parseOptional(27 /* CommaToken */)) {
20774                         // No need to check for a zero length node since we know we parsed a comma
20775                         continue;
20776                     }
20777                     commaStart = -1; // Back to the state where the last token was not a comma
20778                     if (isListTerminator(kind)) {
20779                         break;
20780                     }
20781                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
20782                     // out a comma so we give a good error message.
20783                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
20784                     // If the token was a semicolon, and the caller allows that, then skip it and
20785                     // continue.  This ensures we get back on track and don't result in tons of
20786                     // parse errors.  For example, this can happen when people do things like use
20787                     // a semicolon to delimit object literal members.   Note: we'll have already
20788                     // reported an error when we called parseExpected above.
20789                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
20790                         nextToken();
20791                     }
20792                     if (startPos === scanner.getStartPos()) {
20793                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
20794                         // Consume a token to advance the parser in some way and avoid an infinite loop
20795                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
20796                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
20797                         nextToken();
20798                     }
20799                     continue;
20800                 }
20801                 if (isListTerminator(kind)) {
20802                     break;
20803                 }
20804                 if (abortParsingListOrMoveToNextToken(kind)) {
20805                     break;
20806                 }
20807             }
20808             parsingContext = saveParsingContext;
20809             var result = createNodeArray(list, listPos);
20810             // Recording the trailing comma is deliberately done after the previous
20811             // loop, and not just if we see a list terminator. This is because the list
20812             // may have ended incorrectly, but it is still important to know if there
20813             // was a trailing comma.
20814             // Check if the last token was a comma.
20815             if (commaStart >= 0) {
20816                 // Always preserve a trailing comma by marking it on the NodeArray
20817                 result.hasTrailingComma = true;
20818             }
20819             return result;
20820         }
20821         function getExpectedCommaDiagnostic(kind) {
20822             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
20823         }
20824         function createMissingList() {
20825             var list = createNodeArray([], getNodePos());
20826             list.isMissingList = true;
20827             return list;
20828         }
20829         function isMissingList(arr) {
20830             return !!arr.isMissingList;
20831         }
20832         function parseBracketedList(kind, parseElement, open, close) {
20833             if (parseExpected(open)) {
20834                 var result = parseDelimitedList(kind, parseElement);
20835                 parseExpected(close);
20836                 return result;
20837             }
20838             return createMissingList();
20839         }
20840         function parseEntityName(allowReservedWords, diagnosticMessage) {
20841             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
20842             var dotPos = scanner.getStartPos();
20843             while (parseOptional(24 /* DotToken */)) {
20844                 if (token() === 29 /* LessThanToken */) {
20845                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
20846                     entity.jsdocDotPos = dotPos;
20847                     break;
20848                 }
20849                 dotPos = scanner.getStartPos();
20850                 entity = createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false));
20851             }
20852             return entity;
20853         }
20854         function createQualifiedName(entity, name) {
20855             var node = createNode(153 /* QualifiedName */, entity.pos);
20856             node.left = entity;
20857             node.right = name;
20858             return finishNode(node);
20859         }
20860         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
20861             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
20862             // However, often we'll encounter this in error situations when the identifier or keyword
20863             // is actually starting another valid construct.
20864             //
20865             // So, we check for the following specific case:
20866             //
20867             //      name.
20868             //      identifierOrKeyword identifierNameOrKeyword
20869             //
20870             // Note: the newlines are important here.  For example, if that above code
20871             // were rewritten into:
20872             //
20873             //      name.identifierOrKeyword
20874             //      identifierNameOrKeyword
20875             //
20876             // Then we would consider it valid.  That's because ASI would take effect and
20877             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
20878             // In the first case though, ASI will not take effect because there is not a
20879             // line terminator after the identifier or keyword.
20880             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
20881                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
20882                 if (matchesPattern) {
20883                     // Report that we need an identifier.  However, report it right after the dot,
20884                     // and not on the next token.  This is because the next token might actually
20885                     // be an identifier and the error would be quite confusing.
20886                     return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20887                 }
20888             }
20889             if (token() === 76 /* PrivateIdentifier */) {
20890                 var node = parsePrivateIdentifier();
20891                 return allowPrivateIdentifiers ? node : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
20892             }
20893             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
20894         }
20895         function parseTemplateExpression(isTaggedTemplate) {
20896             var template = createNode(211 /* TemplateExpression */);
20897             template.head = parseTemplateHead(isTaggedTemplate);
20898             ts.Debug.assert(template.head.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20899             var list = [];
20900             var listPos = getNodePos();
20901             do {
20902                 list.push(parseTemplateSpan(isTaggedTemplate));
20903             } while (ts.last(list).literal.kind === 16 /* TemplateMiddle */);
20904             template.templateSpans = createNodeArray(list, listPos);
20905             return finishNode(template);
20906         }
20907         function parseTemplateSpan(isTaggedTemplate) {
20908             var span = createNode(221 /* TemplateSpan */);
20909             span.expression = allowInAnd(parseExpression);
20910             var literal;
20911             if (token() === 19 /* CloseBraceToken */) {
20912                 reScanTemplateToken(isTaggedTemplate);
20913                 literal = parseTemplateMiddleOrTemplateTail();
20914             }
20915             else {
20916                 literal = parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
20917             }
20918             span.literal = literal;
20919             return finishNode(span);
20920         }
20921         function parseLiteralNode() {
20922             return parseLiteralLikeNode(token());
20923         }
20924         function parseTemplateHead(isTaggedTemplate) {
20925             if (isTaggedTemplate) {
20926                 reScanTemplateHeadOrNoSubstitutionTemplate();
20927             }
20928             var fragment = parseLiteralLikeNode(token());
20929             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
20930             return fragment;
20931         }
20932         function parseTemplateMiddleOrTemplateTail() {
20933             var fragment = parseLiteralLikeNode(token());
20934             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
20935             return fragment;
20936         }
20937         function parseLiteralLikeNode(kind) {
20938             var node = createNode(kind);
20939             node.text = scanner.getTokenValue();
20940             switch (kind) {
20941                 case 14 /* NoSubstitutionTemplateLiteral */:
20942                 case 15 /* TemplateHead */:
20943                 case 16 /* TemplateMiddle */:
20944                 case 17 /* TemplateTail */:
20945                     var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
20946                     var tokenText = scanner.getTokenText();
20947                     node.rawText = tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
20948                     break;
20949             }
20950             if (scanner.hasExtendedUnicodeEscape()) {
20951                 node.hasExtendedUnicodeEscape = true;
20952             }
20953             if (scanner.isUnterminated()) {
20954                 node.isUnterminated = true;
20955             }
20956             // Octal literals are not allowed in strict mode or ES5
20957             // Note that theoretically the following condition would hold true literals like 009,
20958             // which is not octal.But because of how the scanner separates the tokens, we would
20959             // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
20960             // We also do not need to check for negatives because any prefix operator would be part of a
20961             // parent unary expression.
20962             if (node.kind === 8 /* NumericLiteral */) {
20963                 node.numericLiteralFlags = scanner.getTokenFlags() & 1008 /* NumericLiteralFlags */;
20964             }
20965             if (ts.isTemplateLiteralKind(node.kind)) {
20966                 node.templateFlags = scanner.getTokenFlags() & 2048 /* ContainsInvalidEscape */;
20967             }
20968             nextToken();
20969             finishNode(node);
20970             return node;
20971         }
20972         // TYPES
20973         function parseTypeReference() {
20974             var node = createNode(169 /* TypeReference */);
20975             node.typeName = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
20976             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
20977                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
20978             }
20979             return finishNode(node);
20980         }
20981         // If true, we should abort parsing an error function.
20982         function typeHasArrowFunctionBlockingParseError(node) {
20983             switch (node.kind) {
20984                 case 169 /* TypeReference */:
20985                     return ts.nodeIsMissing(node.typeName);
20986                 case 170 /* FunctionType */:
20987                 case 171 /* ConstructorType */: {
20988                     var _a = node, parameters = _a.parameters, type = _a.type;
20989                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
20990                 }
20991                 case 182 /* ParenthesizedType */:
20992                     return typeHasArrowFunctionBlockingParseError(node.type);
20993                 default:
20994                     return false;
20995             }
20996         }
20997         function parseThisTypePredicate(lhs) {
20998             nextToken();
20999             var node = createNode(168 /* TypePredicate */, lhs.pos);
21000             node.parameterName = lhs;
21001             node.type = parseType();
21002             return finishNode(node);
21003         }
21004         function parseThisTypeNode() {
21005             var node = createNode(183 /* ThisType */);
21006             nextToken();
21007             return finishNode(node);
21008         }
21009         function parseJSDocAllType(postFixEquals) {
21010             var result = createNode(295 /* JSDocAllType */);
21011             if (postFixEquals) {
21012                 return createPostfixType(299 /* JSDocOptionalType */, result);
21013             }
21014             else {
21015                 nextToken();
21016             }
21017             return finishNode(result);
21018         }
21019         function parseJSDocNonNullableType() {
21020             var result = createNode(298 /* JSDocNonNullableType */);
21021             nextToken();
21022             result.type = parseNonArrayType();
21023             return finishNode(result);
21024         }
21025         function parseJSDocUnknownOrNullableType() {
21026             var pos = scanner.getStartPos();
21027             // skip the ?
21028             nextToken();
21029             // Need to lookahead to decide if this is a nullable or unknown type.
21030             // Here are cases where we'll pick the unknown type:
21031             //
21032             //      Foo(?,
21033             //      { a: ? }
21034             //      Foo(?)
21035             //      Foo<?>
21036             //      Foo(?=
21037             //      (?|
21038             if (token() === 27 /* CommaToken */ ||
21039                 token() === 19 /* CloseBraceToken */ ||
21040                 token() === 21 /* CloseParenToken */ ||
21041                 token() === 31 /* GreaterThanToken */ ||
21042                 token() === 62 /* EqualsToken */ ||
21043                 token() === 51 /* BarToken */) {
21044                 var result = createNode(296 /* JSDocUnknownType */, pos);
21045                 return finishNode(result);
21046             }
21047             else {
21048                 var result = createNode(297 /* JSDocNullableType */, pos);
21049                 result.type = parseType();
21050                 return finishNode(result);
21051             }
21052         }
21053         function parseJSDocFunctionType() {
21054             if (lookAhead(nextTokenIsOpenParen)) {
21055                 var result = createNodeWithJSDoc(300 /* JSDocFunctionType */);
21056                 nextToken();
21057                 fillSignature(58 /* ColonToken */, 4 /* Type */ | 32 /* JSDoc */, result);
21058                 return finishNode(result);
21059             }
21060             var node = createNode(169 /* TypeReference */);
21061             node.typeName = parseIdentifierName();
21062             return finishNode(node);
21063         }
21064         function parseJSDocParameter() {
21065             var parameter = createNode(156 /* Parameter */);
21066             if (token() === 104 /* ThisKeyword */ || token() === 99 /* NewKeyword */) {
21067                 parameter.name = parseIdentifierName();
21068                 parseExpected(58 /* ColonToken */);
21069             }
21070             parameter.type = parseJSDocType();
21071             return finishNode(parameter);
21072         }
21073         function parseJSDocType() {
21074             scanner.setInJSDocType(true);
21075             var moduleSpecifier = parseOptionalToken(135 /* ModuleKeyword */);
21076             if (moduleSpecifier) {
21077                 var moduleTag = createNode(302 /* JSDocNamepathType */, moduleSpecifier.pos);
21078                 terminate: while (true) {
21079                     switch (token()) {
21080                         case 19 /* CloseBraceToken */:
21081                         case 1 /* EndOfFileToken */:
21082                         case 27 /* CommaToken */:
21083                         case 5 /* WhitespaceTrivia */:
21084                             break terminate;
21085                         default:
21086                             nextTokenJSDoc();
21087                     }
21088                 }
21089                 scanner.setInJSDocType(false);
21090                 return finishNode(moduleTag);
21091             }
21092             var dotdotdot = parseOptionalToken(25 /* DotDotDotToken */);
21093             var type = parseTypeOrTypePredicate();
21094             scanner.setInJSDocType(false);
21095             if (dotdotdot) {
21096                 var variadic = createNode(301 /* JSDocVariadicType */, dotdotdot.pos);
21097                 variadic.type = type;
21098                 type = finishNode(variadic);
21099             }
21100             if (token() === 62 /* EqualsToken */) {
21101                 return createPostfixType(299 /* JSDocOptionalType */, type);
21102             }
21103             return type;
21104         }
21105         function parseTypeQuery() {
21106             var node = createNode(172 /* TypeQuery */);
21107             parseExpected(108 /* TypeOfKeyword */);
21108             node.exprName = parseEntityName(/*allowReservedWords*/ true);
21109             return finishNode(node);
21110         }
21111         function parseTypeParameter() {
21112             var node = createNode(155 /* TypeParameter */);
21113             node.name = parseIdentifier();
21114             if (parseOptional(90 /* ExtendsKeyword */)) {
21115                 // It's not uncommon for people to write improper constraints to a generic.  If the
21116                 // user writes a constraint that is an expression and not an actual type, then parse
21117                 // it out as an expression (so we can recover well), but report that a type is needed
21118                 // instead.
21119                 if (isStartOfType() || !isStartOfExpression()) {
21120                     node.constraint = parseType();
21121                 }
21122                 else {
21123                     // It was not a type, and it looked like an expression.  Parse out an expression
21124                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
21125                     // and not parseExpression here.  If the user has:
21126                     //
21127                     //      <T extends "">
21128                     //
21129                     // We do *not* want to consume the `>` as we're consuming the expression for "".
21130                     node.expression = parseUnaryExpressionOrHigher();
21131                 }
21132             }
21133             if (parseOptional(62 /* EqualsToken */)) {
21134                 node.default = parseType();
21135             }
21136             return finishNode(node);
21137         }
21138         function parseTypeParameters() {
21139             if (token() === 29 /* LessThanToken */) {
21140                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21141             }
21142         }
21143         function parseParameterType() {
21144             if (parseOptional(58 /* ColonToken */)) {
21145                 return parseType();
21146             }
21147             return undefined;
21148         }
21149         function isStartOfParameter(isJSDocParameter) {
21150             return token() === 25 /* DotDotDotToken */ ||
21151                 isIdentifierOrPrivateIdentifierOrPattern() ||
21152                 ts.isModifierKind(token()) ||
21153                 token() === 59 /* AtToken */ ||
21154                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
21155         }
21156         function parseParameter() {
21157             var node = createNodeWithJSDoc(156 /* Parameter */);
21158             if (token() === 104 /* ThisKeyword */) {
21159                 node.name = createIdentifier(/*isIdentifier*/ true);
21160                 node.type = parseParameterType();
21161                 return finishNode(node);
21162             }
21163             node.decorators = parseDecorators();
21164             node.modifiers = parseModifiers();
21165             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
21166             // FormalParameter [Yield,Await]:
21167             //      BindingElement[?Yield,?Await]
21168             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
21169             if (ts.getFullWidth(node.name) === 0 && !node.modifiers && ts.isModifierKind(token())) {
21170                 // in cases like
21171                 // 'use strict'
21172                 // function foo(static)
21173                 // isParameter('static') === true, because of isModifier('static')
21174                 // however 'static' is not a legal identifier in a strict mode.
21175                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
21176                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
21177                 // to avoid this we'll advance cursor to the next token.
21178                 nextToken();
21179             }
21180             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21181             node.type = parseParameterType();
21182             node.initializer = parseInitializer();
21183             return finishNode(node);
21184         }
21185         /**
21186          * Note: If returnToken is EqualsGreaterThanToken, `signature.type` will always be defined.
21187          * @returns If return type parsing succeeds
21188          */
21189         function fillSignature(returnToken, flags, signature) {
21190             if (!(flags & 32 /* JSDoc */)) {
21191                 signature.typeParameters = parseTypeParameters();
21192             }
21193             var parametersParsedSuccessfully = parseParameterList(signature, flags);
21194             if (shouldParseReturnType(returnToken, !!(flags & 4 /* Type */))) {
21195                 signature.type = parseTypeOrTypePredicate();
21196                 if (typeHasArrowFunctionBlockingParseError(signature.type))
21197                     return false;
21198             }
21199             return parametersParsedSuccessfully;
21200         }
21201         function shouldParseReturnType(returnToken, isType) {
21202             if (returnToken === 38 /* EqualsGreaterThanToken */) {
21203                 parseExpected(returnToken);
21204                 return true;
21205             }
21206             else if (parseOptional(58 /* ColonToken */)) {
21207                 return true;
21208             }
21209             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
21210                 // This is easy to get backward, especially in type contexts, so parse the type anyway
21211                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
21212                 nextToken();
21213                 return true;
21214             }
21215             return false;
21216         }
21217         // Returns true on success.
21218         function parseParameterList(signature, flags) {
21219             // FormalParameters [Yield,Await]: (modified)
21220             //      [empty]
21221             //      FormalParameterList[?Yield,Await]
21222             //
21223             // FormalParameter[Yield,Await]: (modified)
21224             //      BindingElement[?Yield,Await]
21225             //
21226             // BindingElement [Yield,Await]: (modified)
21227             //      SingleNameBinding[?Yield,?Await]
21228             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21229             //
21230             // SingleNameBinding [Yield,Await]:
21231             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
21232             if (!parseExpected(20 /* OpenParenToken */)) {
21233                 signature.parameters = createMissingList();
21234                 return false;
21235             }
21236             var savedYieldContext = inYieldContext();
21237             var savedAwaitContext = inAwaitContext();
21238             setYieldContext(!!(flags & 1 /* Yield */));
21239             setAwaitContext(!!(flags & 2 /* Await */));
21240             signature.parameters = flags & 32 /* JSDoc */ ?
21241                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
21242                 parseDelimitedList(16 /* Parameters */, parseParameter);
21243             setYieldContext(savedYieldContext);
21244             setAwaitContext(savedAwaitContext);
21245             return parseExpected(21 /* CloseParenToken */);
21246         }
21247         function parseTypeMemberSemicolon() {
21248             // We allow type members to be separated by commas or (possibly ASI) semicolons.
21249             // First check if it was a comma.  If so, we're done with the member.
21250             if (parseOptional(27 /* CommaToken */)) {
21251                 return;
21252             }
21253             // Didn't have a comma.  We must have a (possible ASI) semicolon.
21254             parseSemicolon();
21255         }
21256         function parseSignatureMember(kind) {
21257             var node = createNodeWithJSDoc(kind);
21258             if (kind === 166 /* ConstructSignature */) {
21259                 parseExpected(99 /* NewKeyword */);
21260             }
21261             fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21262             parseTypeMemberSemicolon();
21263             return finishNode(node);
21264         }
21265         function isIndexSignature() {
21266             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
21267         }
21268         function isUnambiguouslyIndexSignature() {
21269             // The only allowed sequence is:
21270             //
21271             //   [id:
21272             //
21273             // However, for error recovery, we also check the following cases:
21274             //
21275             //   [...
21276             //   [id,
21277             //   [id?,
21278             //   [id?:
21279             //   [id?]
21280             //   [public id
21281             //   [private id
21282             //   [protected id
21283             //   []
21284             //
21285             nextToken();
21286             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
21287                 return true;
21288             }
21289             if (ts.isModifierKind(token())) {
21290                 nextToken();
21291                 if (isIdentifier()) {
21292                     return true;
21293                 }
21294             }
21295             else if (!isIdentifier()) {
21296                 return false;
21297             }
21298             else {
21299                 // Skip the identifier
21300                 nextToken();
21301             }
21302             // A colon signifies a well formed indexer
21303             // A comma should be a badly formed indexer because comma expressions are not allowed
21304             // in computed properties.
21305             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
21306                 return true;
21307             }
21308             // Question mark could be an indexer with an optional property,
21309             // or it could be a conditional expression in a computed property.
21310             if (token() !== 57 /* QuestionToken */) {
21311                 return false;
21312             }
21313             // If any of the following tokens are after the question mark, it cannot
21314             // be a conditional expression, so treat it as an indexer.
21315             nextToken();
21316             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
21317         }
21318         function parseIndexSignatureDeclaration(node) {
21319             node.kind = 167 /* IndexSignature */;
21320             node.parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21321             node.type = parseTypeAnnotation();
21322             parseTypeMemberSemicolon();
21323             return finishNode(node);
21324         }
21325         function parsePropertyOrMethodSignature(node) {
21326             node.name = parsePropertyName();
21327             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
21328             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21329                 node.kind = 160 /* MethodSignature */;
21330                 // Method signatures don't exist in expression contexts.  So they have neither
21331                 // [Yield] nor [Await]
21332                 fillSignature(58 /* ColonToken */, 4 /* Type */, node);
21333             }
21334             else {
21335                 node.kind = 158 /* PropertySignature */;
21336                 node.type = parseTypeAnnotation();
21337                 if (token() === 62 /* EqualsToken */) {
21338                     // Although type literal properties cannot not have initializers, we attempt
21339                     // to parse an initializer so we can report in the checker that an interface
21340                     // property or type literal property cannot have an initializer.
21341                     node.initializer = parseInitializer();
21342                 }
21343             }
21344             parseTypeMemberSemicolon();
21345             return finishNode(node);
21346         }
21347         function isTypeMemberStart() {
21348             // Return true if we have the start of a signature member
21349             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21350                 return true;
21351             }
21352             var idToken = false;
21353             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
21354             while (ts.isModifierKind(token())) {
21355                 idToken = true;
21356                 nextToken();
21357             }
21358             // Index signatures and computed property names are type members
21359             if (token() === 22 /* OpenBracketToken */) {
21360                 return true;
21361             }
21362             // Try to get the first property-like token following all modifiers
21363             if (isLiteralPropertyName()) {
21364                 idToken = true;
21365                 nextToken();
21366             }
21367             // If we were able to get any potential identifier, check that it is
21368             // the start of a member declaration
21369             if (idToken) {
21370                 return token() === 20 /* OpenParenToken */ ||
21371                     token() === 29 /* LessThanToken */ ||
21372                     token() === 57 /* QuestionToken */ ||
21373                     token() === 58 /* ColonToken */ ||
21374                     token() === 27 /* CommaToken */ ||
21375                     canParseSemicolon();
21376             }
21377             return false;
21378         }
21379         function parseTypeMember() {
21380             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
21381                 return parseSignatureMember(165 /* CallSignature */);
21382             }
21383             if (token() === 99 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
21384                 return parseSignatureMember(166 /* ConstructSignature */);
21385             }
21386             var node = createNodeWithJSDoc(0 /* Unknown */);
21387             node.modifiers = parseModifiers();
21388             if (isIndexSignature()) {
21389                 return parseIndexSignatureDeclaration(node);
21390             }
21391             return parsePropertyOrMethodSignature(node);
21392         }
21393         function nextTokenIsOpenParenOrLessThan() {
21394             nextToken();
21395             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
21396         }
21397         function nextTokenIsDot() {
21398             return nextToken() === 24 /* DotToken */;
21399         }
21400         function nextTokenIsOpenParenOrLessThanOrDot() {
21401             switch (nextToken()) {
21402                 case 20 /* OpenParenToken */:
21403                 case 29 /* LessThanToken */:
21404                 case 24 /* DotToken */:
21405                     return true;
21406             }
21407             return false;
21408         }
21409         function parseTypeLiteral() {
21410             var node = createNode(173 /* TypeLiteral */);
21411             node.members = parseObjectTypeMembers();
21412             return finishNode(node);
21413         }
21414         function parseObjectTypeMembers() {
21415             var members;
21416             if (parseExpected(18 /* OpenBraceToken */)) {
21417                 members = parseList(4 /* TypeMembers */, parseTypeMember);
21418                 parseExpected(19 /* CloseBraceToken */);
21419             }
21420             else {
21421                 members = createMissingList();
21422             }
21423             return members;
21424         }
21425         function isStartOfMappedType() {
21426             nextToken();
21427             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21428                 return nextToken() === 138 /* ReadonlyKeyword */;
21429             }
21430             if (token() === 138 /* ReadonlyKeyword */) {
21431                 nextToken();
21432             }
21433             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 97 /* InKeyword */;
21434         }
21435         function parseMappedTypeParameter() {
21436             var node = createNode(155 /* TypeParameter */);
21437             node.name = parseIdentifier();
21438             parseExpected(97 /* InKeyword */);
21439             node.constraint = parseType();
21440             return finishNode(node);
21441         }
21442         function parseMappedType() {
21443             var node = createNode(186 /* MappedType */);
21444             parseExpected(18 /* OpenBraceToken */);
21445             if (token() === 138 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21446                 node.readonlyToken = parseTokenNode();
21447                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
21448                     parseExpectedToken(138 /* ReadonlyKeyword */);
21449                 }
21450             }
21451             parseExpected(22 /* OpenBracketToken */);
21452             node.typeParameter = parseMappedTypeParameter();
21453             parseExpected(23 /* CloseBracketToken */);
21454             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
21455                 node.questionToken = parseTokenNode();
21456                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
21457                     parseExpectedToken(57 /* QuestionToken */);
21458                 }
21459             }
21460             node.type = parseTypeAnnotation();
21461             parseSemicolon();
21462             parseExpected(19 /* CloseBraceToken */);
21463             return finishNode(node);
21464         }
21465         function parseTupleElementType() {
21466             var pos = getNodePos();
21467             if (parseOptional(25 /* DotDotDotToken */)) {
21468                 var node = createNode(177 /* RestType */, pos);
21469                 node.type = parseType();
21470                 return finishNode(node);
21471             }
21472             var type = parseType();
21473             if (!(contextFlags & 4194304 /* JSDoc */) && type.kind === 297 /* JSDocNullableType */ && type.pos === type.type.pos) {
21474                 type.kind = 176 /* OptionalType */;
21475             }
21476             return type;
21477         }
21478         function parseTupleType() {
21479             var node = createNode(175 /* TupleType */);
21480             node.elementTypes = parseBracketedList(21 /* TupleElementTypes */, parseTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
21481             return finishNode(node);
21482         }
21483         function parseParenthesizedType() {
21484             var node = createNode(182 /* ParenthesizedType */);
21485             parseExpected(20 /* OpenParenToken */);
21486             node.type = parseType();
21487             parseExpected(21 /* CloseParenToken */);
21488             return finishNode(node);
21489         }
21490         function parseFunctionOrConstructorType() {
21491             var pos = getNodePos();
21492             var kind = parseOptional(99 /* NewKeyword */) ? 171 /* ConstructorType */ : 170 /* FunctionType */;
21493             var node = createNodeWithJSDoc(kind, pos);
21494             fillSignature(38 /* EqualsGreaterThanToken */, 4 /* Type */, node);
21495             return finishNode(node);
21496         }
21497         function parseKeywordAndNoDot() {
21498             var node = parseTokenNode();
21499             return token() === 24 /* DotToken */ ? undefined : node;
21500         }
21501         function parseLiteralTypeNode(negative) {
21502             var node = createNode(187 /* LiteralType */);
21503             var unaryMinusExpression;
21504             if (negative) {
21505                 unaryMinusExpression = createNode(207 /* PrefixUnaryExpression */);
21506                 unaryMinusExpression.operator = 40 /* MinusToken */;
21507                 nextToken();
21508             }
21509             var expression = token() === 106 /* TrueKeyword */ || token() === 91 /* FalseKeyword */
21510                 ? parseTokenNode()
21511                 : parseLiteralLikeNode(token());
21512             if (negative) {
21513                 unaryMinusExpression.operand = expression;
21514                 finishNode(unaryMinusExpression);
21515                 expression = unaryMinusExpression;
21516             }
21517             node.literal = expression;
21518             return finishNode(node);
21519         }
21520         function isStartOfTypeOfImportType() {
21521             nextToken();
21522             return token() === 96 /* ImportKeyword */;
21523         }
21524         function parseImportType() {
21525             sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
21526             var node = createNode(188 /* ImportType */);
21527             if (parseOptional(108 /* TypeOfKeyword */)) {
21528                 node.isTypeOf = true;
21529             }
21530             parseExpected(96 /* ImportKeyword */);
21531             parseExpected(20 /* OpenParenToken */);
21532             node.argument = parseType();
21533             parseExpected(21 /* CloseParenToken */);
21534             if (parseOptional(24 /* DotToken */)) {
21535                 node.qualifier = parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
21536             }
21537             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
21538                 node.typeArguments = parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
21539             }
21540             return finishNode(node);
21541         }
21542         function nextTokenIsNumericOrBigIntLiteral() {
21543             nextToken();
21544             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
21545         }
21546         function parseNonArrayType() {
21547             switch (token()) {
21548                 case 125 /* AnyKeyword */:
21549                 case 148 /* UnknownKeyword */:
21550                 case 143 /* StringKeyword */:
21551                 case 140 /* NumberKeyword */:
21552                 case 151 /* BigIntKeyword */:
21553                 case 144 /* SymbolKeyword */:
21554                 case 128 /* BooleanKeyword */:
21555                 case 146 /* UndefinedKeyword */:
21556                 case 137 /* NeverKeyword */:
21557                 case 141 /* ObjectKeyword */:
21558                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
21559                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
21560                 case 41 /* AsteriskToken */:
21561                     return parseJSDocAllType(/*postfixEquals*/ false);
21562                 case 65 /* AsteriskEqualsToken */:
21563                     return parseJSDocAllType(/*postfixEquals*/ true);
21564                 case 60 /* QuestionQuestionToken */:
21565                     // If there is '??', consider that is prefix '?' in JSDoc type.
21566                     scanner.reScanQuestionToken();
21567                 // falls through
21568                 case 57 /* QuestionToken */:
21569                     return parseJSDocUnknownOrNullableType();
21570                 case 94 /* FunctionKeyword */:
21571                     return parseJSDocFunctionType();
21572                 case 53 /* ExclamationToken */:
21573                     return parseJSDocNonNullableType();
21574                 case 14 /* NoSubstitutionTemplateLiteral */:
21575                 case 10 /* StringLiteral */:
21576                 case 8 /* NumericLiteral */:
21577                 case 9 /* BigIntLiteral */:
21578                 case 106 /* TrueKeyword */:
21579                 case 91 /* FalseKeyword */:
21580                     return parseLiteralTypeNode();
21581                 case 40 /* MinusToken */:
21582                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
21583                 case 110 /* VoidKeyword */:
21584                 case 100 /* NullKeyword */:
21585                     return parseTokenNode();
21586                 case 104 /* ThisKeyword */: {
21587                     var thisKeyword = parseThisTypeNode();
21588                     if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21589                         return parseThisTypePredicate(thisKeyword);
21590                     }
21591                     else {
21592                         return thisKeyword;
21593                     }
21594                 }
21595                 case 108 /* TypeOfKeyword */:
21596                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
21597                 case 18 /* OpenBraceToken */:
21598                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
21599                 case 22 /* OpenBracketToken */:
21600                     return parseTupleType();
21601                 case 20 /* OpenParenToken */:
21602                     return parseParenthesizedType();
21603                 case 96 /* ImportKeyword */:
21604                     return parseImportType();
21605                 case 124 /* AssertsKeyword */:
21606                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
21607                 default:
21608                     return parseTypeReference();
21609             }
21610         }
21611         function isStartOfType(inStartOfParameter) {
21612             switch (token()) {
21613                 case 125 /* AnyKeyword */:
21614                 case 148 /* UnknownKeyword */:
21615                 case 143 /* StringKeyword */:
21616                 case 140 /* NumberKeyword */:
21617                 case 151 /* BigIntKeyword */:
21618                 case 128 /* BooleanKeyword */:
21619                 case 138 /* ReadonlyKeyword */:
21620                 case 144 /* SymbolKeyword */:
21621                 case 147 /* UniqueKeyword */:
21622                 case 110 /* VoidKeyword */:
21623                 case 146 /* UndefinedKeyword */:
21624                 case 100 /* NullKeyword */:
21625                 case 104 /* ThisKeyword */:
21626                 case 108 /* TypeOfKeyword */:
21627                 case 137 /* NeverKeyword */:
21628                 case 18 /* OpenBraceToken */:
21629                 case 22 /* OpenBracketToken */:
21630                 case 29 /* LessThanToken */:
21631                 case 51 /* BarToken */:
21632                 case 50 /* AmpersandToken */:
21633                 case 99 /* NewKeyword */:
21634                 case 10 /* StringLiteral */:
21635                 case 8 /* NumericLiteral */:
21636                 case 9 /* BigIntLiteral */:
21637                 case 106 /* TrueKeyword */:
21638                 case 91 /* FalseKeyword */:
21639                 case 141 /* ObjectKeyword */:
21640                 case 41 /* AsteriskToken */:
21641                 case 57 /* QuestionToken */:
21642                 case 53 /* ExclamationToken */:
21643                 case 25 /* DotDotDotToken */:
21644                 case 132 /* InferKeyword */:
21645                 case 96 /* ImportKeyword */:
21646                 case 124 /* AssertsKeyword */:
21647                     return true;
21648                 case 94 /* FunctionKeyword */:
21649                     return !inStartOfParameter;
21650                 case 40 /* MinusToken */:
21651                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
21652                 case 20 /* OpenParenToken */:
21653                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
21654                     // or something that starts a type. We don't want to consider things like '(1)' a type.
21655                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
21656                 default:
21657                     return isIdentifier();
21658             }
21659         }
21660         function isStartOfParenthesizedOrFunctionType() {
21661             nextToken();
21662             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
21663         }
21664         function parsePostfixTypeOrHigher() {
21665             var type = parseNonArrayType();
21666             while (!scanner.hasPrecedingLineBreak()) {
21667                 switch (token()) {
21668                     case 53 /* ExclamationToken */:
21669                         type = createPostfixType(298 /* JSDocNonNullableType */, type);
21670                         break;
21671                     case 57 /* QuestionToken */:
21672                         // If not in JSDoc and next token is start of a type we have a conditional type
21673                         if (!(contextFlags & 4194304 /* JSDoc */) && lookAhead(nextTokenIsStartOfType)) {
21674                             return type;
21675                         }
21676                         type = createPostfixType(297 /* JSDocNullableType */, type);
21677                         break;
21678                     case 22 /* OpenBracketToken */:
21679                         parseExpected(22 /* OpenBracketToken */);
21680                         if (isStartOfType()) {
21681                             var node = createNode(185 /* IndexedAccessType */, type.pos);
21682                             node.objectType = type;
21683                             node.indexType = parseType();
21684                             parseExpected(23 /* CloseBracketToken */);
21685                             type = finishNode(node);
21686                         }
21687                         else {
21688                             var node = createNode(174 /* ArrayType */, type.pos);
21689                             node.elementType = type;
21690                             parseExpected(23 /* CloseBracketToken */);
21691                             type = finishNode(node);
21692                         }
21693                         break;
21694                     default:
21695                         return type;
21696                 }
21697             }
21698             return type;
21699         }
21700         function createPostfixType(kind, type) {
21701             nextToken();
21702             var postfix = createNode(kind, type.pos);
21703             postfix.type = type;
21704             return finishNode(postfix);
21705         }
21706         function parseTypeOperator(operator) {
21707             var node = createNode(184 /* TypeOperator */);
21708             parseExpected(operator);
21709             node.operator = operator;
21710             node.type = parseTypeOperatorOrHigher();
21711             return finishNode(node);
21712         }
21713         function parseInferType() {
21714             var node = createNode(181 /* InferType */);
21715             parseExpected(132 /* InferKeyword */);
21716             var typeParameter = createNode(155 /* TypeParameter */);
21717             typeParameter.name = parseIdentifier();
21718             node.typeParameter = finishNode(typeParameter);
21719             return finishNode(node);
21720         }
21721         function parseTypeOperatorOrHigher() {
21722             var operator = token();
21723             switch (operator) {
21724                 case 134 /* KeyOfKeyword */:
21725                 case 147 /* UniqueKeyword */:
21726                 case 138 /* ReadonlyKeyword */:
21727                     return parseTypeOperator(operator);
21728                 case 132 /* InferKeyword */:
21729                     return parseInferType();
21730             }
21731             return parsePostfixTypeOrHigher();
21732         }
21733         function parseUnionOrIntersectionType(kind, parseConstituentType, operator) {
21734             var start = scanner.getStartPos();
21735             var hasLeadingOperator = parseOptional(operator);
21736             var type = parseConstituentType();
21737             if (token() === operator || hasLeadingOperator) {
21738                 var types = [type];
21739                 while (parseOptional(operator)) {
21740                     types.push(parseConstituentType());
21741                 }
21742                 var node = createNode(kind, start);
21743                 node.types = createNodeArray(types, start);
21744                 type = finishNode(node);
21745             }
21746             return type;
21747         }
21748         function parseIntersectionTypeOrHigher() {
21749             return parseUnionOrIntersectionType(179 /* IntersectionType */, parseTypeOperatorOrHigher, 50 /* AmpersandToken */);
21750         }
21751         function parseUnionTypeOrHigher() {
21752             return parseUnionOrIntersectionType(178 /* UnionType */, parseIntersectionTypeOrHigher, 51 /* BarToken */);
21753         }
21754         function isStartOfFunctionType() {
21755             if (token() === 29 /* LessThanToken */) {
21756                 return true;
21757             }
21758             return token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType);
21759         }
21760         function skipParameterStart() {
21761             if (ts.isModifierKind(token())) {
21762                 // Skip modifiers
21763                 parseModifiers();
21764             }
21765             if (isIdentifier() || token() === 104 /* ThisKeyword */) {
21766                 nextToken();
21767                 return true;
21768             }
21769             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
21770                 // Return true if we can parse an array or object binding pattern with no errors
21771                 var previousErrorCount = parseDiagnostics.length;
21772                 parseIdentifierOrPattern();
21773                 return previousErrorCount === parseDiagnostics.length;
21774             }
21775             return false;
21776         }
21777         function isUnambiguouslyStartOfFunctionType() {
21778             nextToken();
21779             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
21780                 // ( )
21781                 // ( ...
21782                 return true;
21783             }
21784             if (skipParameterStart()) {
21785                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
21786                 // now see if we have something that indicates a parameter declaration
21787                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
21788                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
21789                     // ( xxx :
21790                     // ( xxx ,
21791                     // ( xxx ?
21792                     // ( xxx =
21793                     return true;
21794                 }
21795                 if (token() === 21 /* CloseParenToken */) {
21796                     nextToken();
21797                     if (token() === 38 /* EqualsGreaterThanToken */) {
21798                         // ( xxx ) =>
21799                         return true;
21800                     }
21801                 }
21802             }
21803             return false;
21804         }
21805         function parseTypeOrTypePredicate() {
21806             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
21807             var type = parseType();
21808             if (typePredicateVariable) {
21809                 var node = createNode(168 /* TypePredicate */, typePredicateVariable.pos);
21810                 node.assertsModifier = undefined;
21811                 node.parameterName = typePredicateVariable;
21812                 node.type = type;
21813                 return finishNode(node);
21814             }
21815             else {
21816                 return type;
21817             }
21818         }
21819         function parseTypePredicatePrefix() {
21820             var id = parseIdentifier();
21821             if (token() === 133 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
21822                 nextToken();
21823                 return id;
21824             }
21825         }
21826         function parseAssertsTypePredicate() {
21827             var node = createNode(168 /* TypePredicate */);
21828             node.assertsModifier = parseExpectedToken(124 /* AssertsKeyword */);
21829             node.parameterName = token() === 104 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
21830             node.type = parseOptional(133 /* IsKeyword */) ? parseType() : undefined;
21831             return finishNode(node);
21832         }
21833         function parseType() {
21834             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
21835             // apply to 'type' contexts.  So we disable these parameters here before moving on.
21836             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
21837         }
21838         function parseTypeWorker(noConditionalTypes) {
21839             if (isStartOfFunctionType() || token() === 99 /* NewKeyword */) {
21840                 return parseFunctionOrConstructorType();
21841             }
21842             var type = parseUnionTypeOrHigher();
21843             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(90 /* ExtendsKeyword */)) {
21844                 var node = createNode(180 /* ConditionalType */, type.pos);
21845                 node.checkType = type;
21846                 // The type following 'extends' is not permitted to be another conditional type
21847                 node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
21848                 parseExpected(57 /* QuestionToken */);
21849                 node.trueType = parseTypeWorker();
21850                 parseExpected(58 /* ColonToken */);
21851                 node.falseType = parseTypeWorker();
21852                 return finishNode(node);
21853             }
21854             return type;
21855         }
21856         function parseTypeAnnotation() {
21857             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
21858         }
21859         // EXPRESSIONS
21860         function isStartOfLeftHandSideExpression() {
21861             switch (token()) {
21862                 case 104 /* ThisKeyword */:
21863                 case 102 /* SuperKeyword */:
21864                 case 100 /* NullKeyword */:
21865                 case 106 /* TrueKeyword */:
21866                 case 91 /* FalseKeyword */:
21867                 case 8 /* NumericLiteral */:
21868                 case 9 /* BigIntLiteral */:
21869                 case 10 /* StringLiteral */:
21870                 case 14 /* NoSubstitutionTemplateLiteral */:
21871                 case 15 /* TemplateHead */:
21872                 case 20 /* OpenParenToken */:
21873                 case 22 /* OpenBracketToken */:
21874                 case 18 /* OpenBraceToken */:
21875                 case 94 /* FunctionKeyword */:
21876                 case 80 /* ClassKeyword */:
21877                 case 99 /* NewKeyword */:
21878                 case 43 /* SlashToken */:
21879                 case 67 /* SlashEqualsToken */:
21880                 case 75 /* Identifier */:
21881                     return true;
21882                 case 96 /* ImportKeyword */:
21883                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
21884                 default:
21885                     return isIdentifier();
21886             }
21887         }
21888         function isStartOfExpression() {
21889             if (isStartOfLeftHandSideExpression()) {
21890                 return true;
21891             }
21892             switch (token()) {
21893                 case 39 /* PlusToken */:
21894                 case 40 /* MinusToken */:
21895                 case 54 /* TildeToken */:
21896                 case 53 /* ExclamationToken */:
21897                 case 85 /* DeleteKeyword */:
21898                 case 108 /* TypeOfKeyword */:
21899                 case 110 /* VoidKeyword */:
21900                 case 45 /* PlusPlusToken */:
21901                 case 46 /* MinusMinusToken */:
21902                 case 29 /* LessThanToken */:
21903                 case 127 /* AwaitKeyword */:
21904                 case 121 /* YieldKeyword */:
21905                 case 76 /* PrivateIdentifier */:
21906                     // Yield/await always starts an expression.  Either it is an identifier (in which case
21907                     // it is definitely an expression).  Or it's a keyword (either because we're in
21908                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
21909                     return true;
21910                 default:
21911                     // Error tolerance.  If we see the start of some binary operator, we consider
21912                     // that the start of an expression.  That way we'll parse out a missing identifier,
21913                     // give a good message about an identifier being missing, and then consume the
21914                     // rest of the binary expression.
21915                     if (isBinaryOperator()) {
21916                         return true;
21917                     }
21918                     return isIdentifier();
21919             }
21920         }
21921         function isStartOfExpressionStatement() {
21922             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
21923             return token() !== 18 /* OpenBraceToken */ &&
21924                 token() !== 94 /* FunctionKeyword */ &&
21925                 token() !== 80 /* ClassKeyword */ &&
21926                 token() !== 59 /* AtToken */ &&
21927                 isStartOfExpression();
21928         }
21929         function parseExpression() {
21930             // Expression[in]:
21931             //      AssignmentExpression[in]
21932             //      Expression[in] , AssignmentExpression[in]
21933             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
21934             var saveDecoratorContext = inDecoratorContext();
21935             if (saveDecoratorContext) {
21936                 setDecoratorContext(/*val*/ false);
21937             }
21938             var expr = parseAssignmentExpressionOrHigher();
21939             var operatorToken;
21940             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
21941                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher());
21942             }
21943             if (saveDecoratorContext) {
21944                 setDecoratorContext(/*val*/ true);
21945             }
21946             return expr;
21947         }
21948         function parseInitializer() {
21949             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
21950         }
21951         function parseAssignmentExpressionOrHigher() {
21952             //  AssignmentExpression[in,yield]:
21953             //      1) ConditionalExpression[?in,?yield]
21954             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
21955             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
21956             //      4) ArrowFunctionExpression[?in,?yield]
21957             //      5) AsyncArrowFunctionExpression[in,yield,await]
21958             //      6) [+Yield] YieldExpression[?In]
21959             //
21960             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
21961             // (i.e. they're both BinaryExpressions with an assignment operator in it).
21962             // First, do the simple check if we have a YieldExpression (production '6').
21963             if (isYieldExpression()) {
21964                 return parseYieldExpression();
21965             }
21966             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
21967             // parameter list or is an async arrow function.
21968             // AsyncArrowFunctionExpression:
21969             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
21970             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
21971             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
21972             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
21973             //
21974             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
21975             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
21976             // with AssignmentExpression if we see one.
21977             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
21978             if (arrowExpression) {
21979                 return arrowExpression;
21980             }
21981             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
21982             // start with a LogicalOrExpression, while the assignment productions can only start with
21983             // LeftHandSideExpressions.
21984             //
21985             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
21986             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
21987             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
21988             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
21989             // and consumes anything.
21990             var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
21991             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
21992             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
21993             // identifier and the current token is an arrow.
21994             if (expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
21995                 return parseSimpleArrowFunctionExpression(expr);
21996             }
21997             // Now see if we might be in cases '2' or '3'.
21998             // If the expression was a LHS expression, and we have an assignment operator, then
21999             // we're in '2' or '3'. Consume the assignment and return.
22000             //
22001             // Note: we call reScanGreaterToken so that we get an appropriately merged token
22002             // for cases like `> > =` becoming `>>=`
22003             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
22004                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher());
22005             }
22006             // It wasn't an assignment or a lambda.  This is a conditional expression:
22007             return parseConditionalExpressionRest(expr);
22008         }
22009         function isYieldExpression() {
22010             if (token() === 121 /* YieldKeyword */) {
22011                 // If we have a 'yield' keyword, and this is a context where yield expressions are
22012                 // allowed, then definitely parse out a yield expression.
22013                 if (inYieldContext()) {
22014                     return true;
22015                 }
22016                 // We're in a context where 'yield expr' is not allowed.  However, if we can
22017                 // definitely tell that the user was trying to parse a 'yield expr' and not
22018                 // just a normal expr that start with a 'yield' identifier, then parse out
22019                 // a 'yield expr'.  We can then report an error later that they are only
22020                 // allowed in generator expressions.
22021                 //
22022                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
22023                 // invocation expression of something called 'yield'.  However, if we have
22024                 // 'yield foo' then that is not legal as a normal expression, so we can
22025                 // definitely recognize this as a yield expression.
22026                 //
22027                 // for now we just check if the next token is an identifier.  More heuristics
22028                 // can be added here later as necessary.  We just need to make sure that we
22029                 // don't accidentally consume something legal.
22030                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22031             }
22032             return false;
22033         }
22034         function nextTokenIsIdentifierOnSameLine() {
22035             nextToken();
22036             return !scanner.hasPrecedingLineBreak() && isIdentifier();
22037         }
22038         function parseYieldExpression() {
22039             var node = createNode(212 /* YieldExpression */);
22040             // YieldExpression[In] :
22041             //      yield
22042             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22043             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
22044             nextToken();
22045             if (!scanner.hasPrecedingLineBreak() &&
22046                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
22047                 node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
22048                 node.expression = parseAssignmentExpressionOrHigher();
22049                 return finishNode(node);
22050             }
22051             else {
22052                 // if the next token is not on the same line as yield.  or we don't have an '*' or
22053                 // the start of an expression, then this is just a simple "yield" expression.
22054                 return finishNode(node);
22055             }
22056         }
22057         function parseSimpleArrowFunctionExpression(identifier, asyncModifier) {
22058             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
22059             var node;
22060             if (asyncModifier) {
22061                 node = createNode(202 /* ArrowFunction */, asyncModifier.pos);
22062                 node.modifiers = asyncModifier;
22063             }
22064             else {
22065                 node = createNode(202 /* ArrowFunction */, identifier.pos);
22066             }
22067             var parameter = createNode(156 /* Parameter */, identifier.pos);
22068             parameter.name = identifier;
22069             finishNode(parameter);
22070             node.parameters = createNodeArray([parameter], parameter.pos, parameter.end);
22071             node.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22072             node.body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
22073             return addJSDocComment(finishNode(node));
22074         }
22075         function tryParseParenthesizedArrowFunctionExpression() {
22076             var triState = isParenthesizedArrowFunctionExpression();
22077             if (triState === 0 /* False */) {
22078                 // It's definitely not a parenthesized arrow function expression.
22079                 return undefined;
22080             }
22081             // If we definitely have an arrow function, then we can just parse one, not requiring a
22082             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
22083             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
22084             // expression instead.
22085             var arrowFunction = triState === 1 /* True */
22086                 ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true)
22087                 : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead);
22088             if (!arrowFunction) {
22089                 // Didn't appear to actually be a parenthesized arrow function.  Just bail out.
22090                 return undefined;
22091             }
22092             var isAsync = hasModifierOfKind(arrowFunction, 126 /* AsyncKeyword */);
22093             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
22094             // have an opening brace, just in case we're in an error state.
22095             var lastToken = token();
22096             arrowFunction.equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
22097             arrowFunction.body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
22098                 ? parseArrowFunctionExpressionBody(isAsync)
22099                 : parseIdentifier();
22100             return finishNode(arrowFunction);
22101         }
22102         //  True        -> We definitely expect a parenthesized arrow function here.
22103         //  False       -> There *cannot* be a parenthesized arrow function here.
22104         //  Unknown     -> There *might* be a parenthesized arrow function here.
22105         //                 Speculatively look ahead to be sure, and rollback if not.
22106         function isParenthesizedArrowFunctionExpression() {
22107             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 126 /* AsyncKeyword */) {
22108                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
22109             }
22110             if (token() === 38 /* EqualsGreaterThanToken */) {
22111                 // ERROR RECOVERY TWEAK:
22112                 // If we see a standalone => try to parse it as an arrow function expression as that's
22113                 // likely what the user intended to write.
22114                 return 1 /* True */;
22115             }
22116             // Definitely not a parenthesized arrow function.
22117             return 0 /* False */;
22118         }
22119         function isParenthesizedArrowFunctionExpressionWorker() {
22120             if (token() === 126 /* AsyncKeyword */) {
22121                 nextToken();
22122                 if (scanner.hasPrecedingLineBreak()) {
22123                     return 0 /* False */;
22124                 }
22125                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
22126                     return 0 /* False */;
22127                 }
22128             }
22129             var first = token();
22130             var second = nextToken();
22131             if (first === 20 /* OpenParenToken */) {
22132                 if (second === 21 /* CloseParenToken */) {
22133                     // Simple cases: "() =>", "(): ", and "() {".
22134                     // This is an arrow function with no parameters.
22135                     // The last one is not actually an arrow function,
22136                     // but this is probably what the user intended.
22137                     var third = nextToken();
22138                     switch (third) {
22139                         case 38 /* EqualsGreaterThanToken */:
22140                         case 58 /* ColonToken */:
22141                         case 18 /* OpenBraceToken */:
22142                             return 1 /* True */;
22143                         default:
22144                             return 0 /* False */;
22145                     }
22146                 }
22147                 // If encounter "([" or "({", this could be the start of a binding pattern.
22148                 // Examples:
22149                 //      ([ x ]) => { }
22150                 //      ({ x }) => { }
22151                 //      ([ x ])
22152                 //      ({ x })
22153                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
22154                     return 2 /* Unknown */;
22155                 }
22156                 // Simple case: "(..."
22157                 // This is an arrow function with a rest parameter.
22158                 if (second === 25 /* DotDotDotToken */) {
22159                     return 1 /* True */;
22160                 }
22161                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
22162                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
22163                 // a good error message.
22164                 if (ts.isModifierKind(second) && second !== 126 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
22165                     return 1 /* True */;
22166                 }
22167                 // If we had "(" followed by something that's not an identifier,
22168                 // then this definitely doesn't look like a lambda.  "this" is not
22169                 // valid, but we want to parse it and then give a semantic error.
22170                 if (!isIdentifier() && second !== 104 /* ThisKeyword */) {
22171                     return 0 /* False */;
22172                 }
22173                 switch (nextToken()) {
22174                     case 58 /* ColonToken */:
22175                         // If we have something like "(a:", then we must have a
22176                         // type-annotated parameter in an arrow function expression.
22177                         return 1 /* True */;
22178                     case 57 /* QuestionToken */:
22179                         nextToken();
22180                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
22181                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
22182                             return 1 /* True */;
22183                         }
22184                         // Otherwise it is definitely not a lambda.
22185                         return 0 /* False */;
22186                     case 27 /* CommaToken */:
22187                     case 62 /* EqualsToken */:
22188                     case 21 /* CloseParenToken */:
22189                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
22190                         return 2 /* Unknown */;
22191                 }
22192                 // It is definitely not an arrow function
22193                 return 0 /* False */;
22194             }
22195             else {
22196                 ts.Debug.assert(first === 29 /* LessThanToken */);
22197                 // If we have "<" not followed by an identifier,
22198                 // then this definitely is not an arrow function.
22199                 if (!isIdentifier()) {
22200                     return 0 /* False */;
22201                 }
22202                 // JSX overrides
22203                 if (sourceFile.languageVariant === 1 /* JSX */) {
22204                     var isArrowFunctionInJsx = lookAhead(function () {
22205                         var third = nextToken();
22206                         if (third === 90 /* ExtendsKeyword */) {
22207                             var fourth = nextToken();
22208                             switch (fourth) {
22209                                 case 62 /* EqualsToken */:
22210                                 case 31 /* GreaterThanToken */:
22211                                     return false;
22212                                 default:
22213                                     return true;
22214                             }
22215                         }
22216                         else if (third === 27 /* CommaToken */) {
22217                             return true;
22218                         }
22219                         return false;
22220                     });
22221                     if (isArrowFunctionInJsx) {
22222                         return 1 /* True */;
22223                     }
22224                     return 0 /* False */;
22225                 }
22226                 // This *could* be a parenthesized arrow function.
22227                 return 2 /* Unknown */;
22228             }
22229         }
22230         function parsePossibleParenthesizedArrowFunctionExpressionHead() {
22231             var tokenPos = scanner.getTokenPos();
22232             if (notParenthesizedArrow && notParenthesizedArrow.has(tokenPos.toString())) {
22233                 return undefined;
22234             }
22235             var result = parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ false);
22236             if (!result) {
22237                 (notParenthesizedArrow || (notParenthesizedArrow = ts.createMap())).set(tokenPos.toString(), true);
22238             }
22239             return result;
22240         }
22241         function tryParseAsyncSimpleArrowFunctionExpression() {
22242             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
22243             if (token() === 126 /* AsyncKeyword */) {
22244                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
22245                     var asyncModifier = parseModifiersForArrowFunction();
22246                     var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22247                     return parseSimpleArrowFunctionExpression(expr, asyncModifier);
22248                 }
22249             }
22250             return undefined;
22251         }
22252         function isUnParenthesizedAsyncArrowFunctionWorker() {
22253             // AsyncArrowFunctionExpression:
22254             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
22255             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
22256             if (token() === 126 /* AsyncKeyword */) {
22257                 nextToken();
22258                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
22259                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
22260                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
22261                     return 0 /* False */;
22262                 }
22263                 // Check for un-parenthesized AsyncArrowFunction
22264                 var expr = parseBinaryExpressionOrHigher(/*precedence*/ 0);
22265                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 75 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
22266                     return 1 /* True */;
22267                 }
22268             }
22269             return 0 /* False */;
22270         }
22271         function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) {
22272             var node = createNodeWithJSDoc(202 /* ArrowFunction */);
22273             node.modifiers = parseModifiersForArrowFunction();
22274             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
22275             // Arrow functions are never generators.
22276             //
22277             // If we're speculatively parsing a signature for a parenthesized arrow function, then
22278             // we have to have a complete parameter list.  Otherwise we might see something like
22279             // a => (b => c)
22280             // And think that "(b =>" was actually a parenthesized arrow function with a missing
22281             // close paren.
22282             if (!fillSignature(58 /* ColonToken */, isAsync, node) && !allowAmbiguity) {
22283                 return undefined;
22284             }
22285             // Parsing a signature isn't enough.
22286             // Parenthesized arrow signatures often look like other valid expressions.
22287             // For instance:
22288             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
22289             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
22290             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
22291             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
22292             //
22293             // So we need just a bit of lookahead to ensure that it can only be a signature.
22294             var hasJSDocFunctionType = node.type && ts.isJSDocFunctionType(node.type);
22295             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
22296                 // Returning undefined here will cause our caller to rewind to where we started from.
22297                 return undefined;
22298             }
22299             return node;
22300         }
22301         function parseArrowFunctionExpressionBody(isAsync) {
22302             if (token() === 18 /* OpenBraceToken */) {
22303                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
22304             }
22305             if (token() !== 26 /* SemicolonToken */ &&
22306                 token() !== 94 /* FunctionKeyword */ &&
22307                 token() !== 80 /* ClassKeyword */ &&
22308                 isStartOfStatement() &&
22309                 !isStartOfExpressionStatement()) {
22310                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
22311                 //
22312                 // Here we try to recover from a potential error situation in the case where the
22313                 // user meant to supply a block. For example, if the user wrote:
22314                 //
22315                 //  a =>
22316                 //      let v = 0;
22317                 //  }
22318                 //
22319                 // they may be missing an open brace.  Check to see if that's the case so we can
22320                 // try to recover better.  If we don't do this, then the next close curly we see may end
22321                 // up preemptively closing the containing construct.
22322                 //
22323                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
22324                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
22325             }
22326             return isAsync
22327                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
22328                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
22329         }
22330         function parseConditionalExpressionRest(leftOperand) {
22331             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
22332             var questionToken = parseOptionalToken(57 /* QuestionToken */);
22333             if (!questionToken) {
22334                 return leftOperand;
22335             }
22336             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
22337             // we do not that for the 'whenFalse' part.
22338             var node = createNode(210 /* ConditionalExpression */, leftOperand.pos);
22339             node.condition = leftOperand;
22340             node.questionToken = questionToken;
22341             node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher);
22342             node.colonToken = parseExpectedToken(58 /* ColonToken */);
22343             node.whenFalse = ts.nodeIsPresent(node.colonToken)
22344                 ? parseAssignmentExpressionOrHigher()
22345                 : createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
22346             return finishNode(node);
22347         }
22348         function parseBinaryExpressionOrHigher(precedence) {
22349             var leftOperand = parseUnaryExpressionOrHigher();
22350             return parseBinaryExpressionRest(precedence, leftOperand);
22351         }
22352         function isInOrOfKeyword(t) {
22353             return t === 97 /* InKeyword */ || t === 152 /* OfKeyword */;
22354         }
22355         function parseBinaryExpressionRest(precedence, leftOperand) {
22356             while (true) {
22357                 // We either have a binary operator here, or we're finished.  We call
22358                 // reScanGreaterToken so that we merge token sequences like > and = into >=
22359                 reScanGreaterToken();
22360                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
22361                 // Check the precedence to see if we should "take" this operator
22362                 // - For left associative operator (all operator but **), consume the operator,
22363                 //   recursively call the function below, and parse binaryExpression as a rightOperand
22364                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
22365                 //   For example:
22366                 //      a - b - c;
22367                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22368                 //      a * b - c
22369                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
22370                 //      a - b * c;
22371                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
22372                 // - For right associative operator (**), consume the operator, recursively call the function
22373                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
22374                 //   the operator is strictly grater than the current precedence
22375                 //   For example:
22376                 //      a ** b ** c;
22377                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22378                 //      a - b ** c;
22379                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
22380                 //      a ** b - c
22381                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
22382                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
22383                     newPrecedence >= precedence :
22384                     newPrecedence > precedence;
22385                 if (!consumeCurrentOperator) {
22386                     break;
22387                 }
22388                 if (token() === 97 /* InKeyword */ && inDisallowInContext()) {
22389                     break;
22390                 }
22391                 if (token() === 123 /* AsKeyword */) {
22392                     // Make sure we *do* perform ASI for constructs like this:
22393                     //    var x = foo
22394                     //    as (Bar)
22395                     // This should be parsed as an initialized variable, followed
22396                     // by a function call to 'as' with the argument 'Bar'
22397                     if (scanner.hasPrecedingLineBreak()) {
22398                         break;
22399                     }
22400                     else {
22401                         nextToken();
22402                         leftOperand = makeAsExpression(leftOperand, parseType());
22403                     }
22404                 }
22405                 else {
22406                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
22407                 }
22408             }
22409             return leftOperand;
22410         }
22411         function isBinaryOperator() {
22412             if (inDisallowInContext() && token() === 97 /* InKeyword */) {
22413                 return false;
22414             }
22415             return ts.getBinaryOperatorPrecedence(token()) > 0;
22416         }
22417         function makeBinaryExpression(left, operatorToken, right) {
22418             var node = createNode(209 /* BinaryExpression */, left.pos);
22419             node.left = left;
22420             node.operatorToken = operatorToken;
22421             node.right = right;
22422             return finishNode(node);
22423         }
22424         function makeAsExpression(left, right) {
22425             var node = createNode(217 /* AsExpression */, left.pos);
22426             node.expression = left;
22427             node.type = right;
22428             return finishNode(node);
22429         }
22430         function parsePrefixUnaryExpression() {
22431             var node = createNode(207 /* PrefixUnaryExpression */);
22432             node.operator = token();
22433             nextToken();
22434             node.operand = parseSimpleUnaryExpression();
22435             return finishNode(node);
22436         }
22437         function parseDeleteExpression() {
22438             var node = createNode(203 /* DeleteExpression */);
22439             nextToken();
22440             node.expression = parseSimpleUnaryExpression();
22441             return finishNode(node);
22442         }
22443         function parseTypeOfExpression() {
22444             var node = createNode(204 /* TypeOfExpression */);
22445             nextToken();
22446             node.expression = parseSimpleUnaryExpression();
22447             return finishNode(node);
22448         }
22449         function parseVoidExpression() {
22450             var node = createNode(205 /* VoidExpression */);
22451             nextToken();
22452             node.expression = parseSimpleUnaryExpression();
22453             return finishNode(node);
22454         }
22455         function isAwaitExpression() {
22456             if (token() === 127 /* AwaitKeyword */) {
22457                 if (inAwaitContext()) {
22458                     return true;
22459                 }
22460                 // here we are using similar heuristics as 'isYieldExpression'
22461                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
22462             }
22463             return false;
22464         }
22465         function parseAwaitExpression() {
22466             var node = createNode(206 /* AwaitExpression */);
22467             nextToken();
22468             node.expression = parseSimpleUnaryExpression();
22469             return finishNode(node);
22470         }
22471         /**
22472          * Parse ES7 exponential expression and await expression
22473          *
22474          * ES7 ExponentiationExpression:
22475          *      1) UnaryExpression[?Yield]
22476          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
22477          *
22478          */
22479         function parseUnaryExpressionOrHigher() {
22480             /**
22481              * ES7 UpdateExpression:
22482              *      1) LeftHandSideExpression[?Yield]
22483              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
22484              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
22485              *      4) ++UnaryExpression[?Yield]
22486              *      5) --UnaryExpression[?Yield]
22487              */
22488             if (isUpdateExpression()) {
22489                 var updateExpression = parseUpdateExpression();
22490                 return token() === 42 /* AsteriskAsteriskToken */ ?
22491                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) :
22492                     updateExpression;
22493             }
22494             /**
22495              * ES7 UnaryExpression:
22496              *      1) UpdateExpression[?yield]
22497              *      2) delete UpdateExpression[?yield]
22498              *      3) void UpdateExpression[?yield]
22499              *      4) typeof UpdateExpression[?yield]
22500              *      5) + UpdateExpression[?yield]
22501              *      6) - UpdateExpression[?yield]
22502              *      7) ~ UpdateExpression[?yield]
22503              *      8) ! UpdateExpression[?yield]
22504              */
22505             var unaryOperator = token();
22506             var simpleUnaryExpression = parseSimpleUnaryExpression();
22507             if (token() === 42 /* AsteriskAsteriskToken */) {
22508                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
22509                 var end = simpleUnaryExpression.end;
22510                 if (simpleUnaryExpression.kind === 199 /* TypeAssertionExpression */) {
22511                     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);
22512                 }
22513                 else {
22514                     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));
22515                 }
22516             }
22517             return simpleUnaryExpression;
22518         }
22519         /**
22520          * Parse ES7 simple-unary expression or higher:
22521          *
22522          * ES7 UnaryExpression:
22523          *      1) UpdateExpression[?yield]
22524          *      2) delete UnaryExpression[?yield]
22525          *      3) void UnaryExpression[?yield]
22526          *      4) typeof UnaryExpression[?yield]
22527          *      5) + UnaryExpression[?yield]
22528          *      6) - UnaryExpression[?yield]
22529          *      7) ~ UnaryExpression[?yield]
22530          *      8) ! UnaryExpression[?yield]
22531          *      9) [+Await] await UnaryExpression[?yield]
22532          */
22533         function parseSimpleUnaryExpression() {
22534             switch (token()) {
22535                 case 39 /* PlusToken */:
22536                 case 40 /* MinusToken */:
22537                 case 54 /* TildeToken */:
22538                 case 53 /* ExclamationToken */:
22539                     return parsePrefixUnaryExpression();
22540                 case 85 /* DeleteKeyword */:
22541                     return parseDeleteExpression();
22542                 case 108 /* TypeOfKeyword */:
22543                     return parseTypeOfExpression();
22544                 case 110 /* VoidKeyword */:
22545                     return parseVoidExpression();
22546                 case 29 /* LessThanToken */:
22547                     // This is modified UnaryExpression grammar in TypeScript
22548                     //  UnaryExpression (modified):
22549                     //      < type > UnaryExpression
22550                     return parseTypeAssertion();
22551                 case 127 /* AwaitKeyword */:
22552                     if (isAwaitExpression()) {
22553                         return parseAwaitExpression();
22554                     }
22555                 // falls through
22556                 default:
22557                     return parseUpdateExpression();
22558             }
22559         }
22560         /**
22561          * Check if the current token can possibly be an ES7 increment expression.
22562          *
22563          * ES7 UpdateExpression:
22564          *      LeftHandSideExpression[?Yield]
22565          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
22566          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
22567          *      ++LeftHandSideExpression[?Yield]
22568          *      --LeftHandSideExpression[?Yield]
22569          */
22570         function isUpdateExpression() {
22571             // This function is called inside parseUnaryExpression to decide
22572             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
22573             switch (token()) {
22574                 case 39 /* PlusToken */:
22575                 case 40 /* MinusToken */:
22576                 case 54 /* TildeToken */:
22577                 case 53 /* ExclamationToken */:
22578                 case 85 /* DeleteKeyword */:
22579                 case 108 /* TypeOfKeyword */:
22580                 case 110 /* VoidKeyword */:
22581                 case 127 /* AwaitKeyword */:
22582                     return false;
22583                 case 29 /* LessThanToken */:
22584                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
22585                     if (sourceFile.languageVariant !== 1 /* JSX */) {
22586                         return false;
22587                     }
22588                 // We are in JSX context and the token is part of JSXElement.
22589                 // falls through
22590                 default:
22591                     return true;
22592             }
22593         }
22594         /**
22595          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
22596          *
22597          * ES7 UpdateExpression[yield]:
22598          *      1) LeftHandSideExpression[?yield]
22599          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
22600          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
22601          *      4) ++LeftHandSideExpression[?yield]
22602          *      5) --LeftHandSideExpression[?yield]
22603          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
22604          */
22605         function parseUpdateExpression() {
22606             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
22607                 var node = createNode(207 /* PrefixUnaryExpression */);
22608                 node.operator = token();
22609                 nextToken();
22610                 node.operand = parseLeftHandSideExpressionOrHigher();
22611                 return finishNode(node);
22612             }
22613             else if (sourceFile.languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
22614                 // JSXElement is part of primaryExpression
22615                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
22616             }
22617             var expression = parseLeftHandSideExpressionOrHigher();
22618             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
22619             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
22620                 var node = createNode(208 /* PostfixUnaryExpression */, expression.pos);
22621                 node.operand = expression;
22622                 node.operator = token();
22623                 nextToken();
22624                 return finishNode(node);
22625             }
22626             return expression;
22627         }
22628         function parseLeftHandSideExpressionOrHigher() {
22629             // Original Ecma:
22630             // LeftHandSideExpression: See 11.2
22631             //      NewExpression
22632             //      CallExpression
22633             //
22634             // Our simplification:
22635             //
22636             // LeftHandSideExpression: See 11.2
22637             //      MemberExpression
22638             //      CallExpression
22639             //
22640             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
22641             // MemberExpression to make our lives easier.
22642             //
22643             // to best understand the below code, it's important to see how CallExpression expands
22644             // out into its own productions:
22645             //
22646             // CallExpression:
22647             //      MemberExpression Arguments
22648             //      CallExpression Arguments
22649             //      CallExpression[Expression]
22650             //      CallExpression.IdentifierName
22651             //      import (AssignmentExpression)
22652             //      super Arguments
22653             //      super.IdentifierName
22654             //
22655             // Because of the recursion in these calls, we need to bottom out first. There are three
22656             // bottom out states we can run into: 1) We see 'super' which must start either of
22657             // the last two CallExpression productions. 2) We see 'import' which must start import call.
22658             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
22659             // or starts the beginning of the first four CallExpression productions.
22660             var expression;
22661             if (token() === 96 /* ImportKeyword */) {
22662                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
22663                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
22664                     // For example:
22665                     //      var foo3 = require("subfolder
22666                     //      import * as foo1 from "module-from-node
22667                     // We want this import to be a statement rather than import call expression
22668                     sourceFile.flags |= 1048576 /* PossiblyContainsDynamicImport */;
22669                     expression = parseTokenNode();
22670                 }
22671                 else if (lookAhead(nextTokenIsDot)) {
22672                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
22673                     var fullStart = scanner.getStartPos();
22674                     nextToken(); // advance past the 'import'
22675                     nextToken(); // advance past the dot
22676                     var node = createNode(219 /* MetaProperty */, fullStart);
22677                     node.keywordToken = 96 /* ImportKeyword */;
22678                     node.name = parseIdentifierName();
22679                     expression = finishNode(node);
22680                     sourceFile.flags |= 2097152 /* PossiblyContainsImportMeta */;
22681                 }
22682                 else {
22683                     expression = parseMemberExpressionOrHigher();
22684                 }
22685             }
22686             else {
22687                 expression = token() === 102 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
22688             }
22689             // Now, we *may* be complete.  However, we might have consumed the start of a
22690             // CallExpression or OptionalExpression.  As such, we need to consume the rest
22691             // of it here to be complete.
22692             return parseCallExpressionRest(expression);
22693         }
22694         function parseMemberExpressionOrHigher() {
22695             // Note: to make our lives simpler, we decompose the NewExpression productions and
22696             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
22697             // like so:
22698             //
22699             //   PrimaryExpression : See 11.1
22700             //      this
22701             //      Identifier
22702             //      Literal
22703             //      ArrayLiteral
22704             //      ObjectLiteral
22705             //      (Expression)
22706             //      FunctionExpression
22707             //      new MemberExpression Arguments?
22708             //
22709             //   MemberExpression : See 11.2
22710             //      PrimaryExpression
22711             //      MemberExpression[Expression]
22712             //      MemberExpression.IdentifierName
22713             //
22714             //   CallExpression : See 11.2
22715             //      MemberExpression
22716             //      CallExpression Arguments
22717             //      CallExpression[Expression]
22718             //      CallExpression.IdentifierName
22719             //
22720             // Technically this is ambiguous.  i.e. CallExpression defines:
22721             //
22722             //   CallExpression:
22723             //      CallExpression Arguments
22724             //
22725             // If you see: "new Foo()"
22726             //
22727             // Then that could be treated as a single ObjectCreationExpression, or it could be
22728             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
22729             // the original grammar) by making sure that if we see an ObjectCreationExpression
22730             // we always consume arguments if they are there. So we treat "new Foo()" as an
22731             // object creation only, and not at all as an invocation.  Another way to think
22732             // about this is that for every "new" that we see, we will consume an argument list if
22733             // it is there as part of the *associated* object creation node.  Any additional
22734             // argument lists we see, will become invocation expressions.
22735             //
22736             // Because there are no other places in the grammar now that refer to FunctionExpression
22737             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
22738             // production.
22739             //
22740             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
22741             // of the recursion immediately.  So we parse out a primary expression to start with.
22742             var expression = parsePrimaryExpression();
22743             return parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
22744         }
22745         function parseSuperExpression() {
22746             var expression = parseTokenNode();
22747             if (token() === 29 /* LessThanToken */) {
22748                 var startPos = getNodePos();
22749                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
22750                 if (typeArguments !== undefined) {
22751                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
22752                 }
22753             }
22754             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
22755                 return expression;
22756             }
22757             // If we have seen "super" it must be followed by '(' or '.'.
22758             // If it wasn't then just try to parse out a '.' and report an error.
22759             var node = createNode(194 /* PropertyAccessExpression */, expression.pos);
22760             node.expression = expression;
22761             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
22762             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
22763             node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
22764             return finishNode(node);
22765         }
22766         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext) {
22767             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
22768             var result;
22769             if (opening.kind === 268 /* JsxOpeningElement */) {
22770                 var node = createNode(266 /* JsxElement */, opening.pos);
22771                 node.openingElement = opening;
22772                 node.children = parseJsxChildren(node.openingElement);
22773                 node.closingElement = parseJsxClosingElement(inExpressionContext);
22774                 if (!tagNamesAreEquivalent(node.openingElement.tagName, node.closingElement.tagName)) {
22775                     parseErrorAtRange(node.closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, node.openingElement.tagName));
22776                 }
22777                 result = finishNode(node);
22778             }
22779             else if (opening.kind === 271 /* JsxOpeningFragment */) {
22780                 var node = createNode(270 /* JsxFragment */, opening.pos);
22781                 node.openingFragment = opening;
22782                 node.children = parseJsxChildren(node.openingFragment);
22783                 node.closingFragment = parseJsxClosingFragment(inExpressionContext);
22784                 result = finishNode(node);
22785             }
22786             else {
22787                 ts.Debug.assert(opening.kind === 267 /* JsxSelfClosingElement */);
22788                 // Nothing else to do for self-closing elements
22789                 result = opening;
22790             }
22791             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
22792             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
22793             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
22794             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
22795             // does less damage and we can report a better error.
22796             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
22797             // of one sort or another.
22798             if (inExpressionContext && token() === 29 /* LessThanToken */) {
22799                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true); });
22800                 if (invalidElement) {
22801                     parseErrorAtCurrentToken(ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
22802                     var badNode = createNode(209 /* BinaryExpression */, result.pos);
22803                     badNode.end = invalidElement.end;
22804                     badNode.left = result;
22805                     badNode.right = invalidElement;
22806                     badNode.operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
22807                     badNode.operatorToken.pos = badNode.operatorToken.end = badNode.right.pos;
22808                     return badNode;
22809                 }
22810             }
22811             return result;
22812         }
22813         function parseJsxText() {
22814             var node = createNode(11 /* JsxText */);
22815             node.text = scanner.getTokenValue();
22816             node.containsOnlyTriviaWhiteSpaces = currentToken === 12 /* JsxTextAllWhiteSpaces */;
22817             currentToken = scanner.scanJsxToken();
22818             return finishNode(node);
22819         }
22820         function parseJsxChild(openingTag, token) {
22821             switch (token) {
22822                 case 1 /* EndOfFileToken */:
22823                     // If we hit EOF, issue the error at the tag that lacks the closing element
22824                     // rather than at the end of the file (which is useless)
22825                     if (ts.isJsxOpeningFragment(openingTag)) {
22826                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
22827                     }
22828                     else {
22829                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
22830                         // or to cover only 'Foo' in < Foo >
22831                         var tag = openingTag.tagName;
22832                         var start = ts.skipTrivia(sourceText, tag.pos);
22833                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
22834                     }
22835                     return undefined;
22836                 case 30 /* LessThanSlashToken */:
22837                 case 7 /* ConflictMarkerTrivia */:
22838                     return undefined;
22839                 case 11 /* JsxText */:
22840                 case 12 /* JsxTextAllWhiteSpaces */:
22841                     return parseJsxText();
22842                 case 18 /* OpenBraceToken */:
22843                     return parseJsxExpression(/*inExpressionContext*/ false);
22844                 case 29 /* LessThanToken */:
22845                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
22846                 default:
22847                     return ts.Debug.assertNever(token);
22848             }
22849         }
22850         function parseJsxChildren(openingTag) {
22851             var list = [];
22852             var listPos = getNodePos();
22853             var saveParsingContext = parsingContext;
22854             parsingContext |= 1 << 14 /* JsxChildren */;
22855             while (true) {
22856                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
22857                 if (!child)
22858                     break;
22859                 list.push(child);
22860             }
22861             parsingContext = saveParsingContext;
22862             return createNodeArray(list, listPos);
22863         }
22864         function parseJsxAttributes() {
22865             var jsxAttributes = createNode(274 /* JsxAttributes */);
22866             jsxAttributes.properties = parseList(13 /* JsxAttributes */, parseJsxAttribute);
22867             return finishNode(jsxAttributes);
22868         }
22869         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
22870             var fullStart = scanner.getStartPos();
22871             parseExpected(29 /* LessThanToken */);
22872             if (token() === 31 /* GreaterThanToken */) {
22873                 // See below for explanation of scanJsxText
22874                 var node_1 = createNode(271 /* JsxOpeningFragment */, fullStart);
22875                 scanJsxText();
22876                 return finishNode(node_1);
22877             }
22878             var tagName = parseJsxElementName();
22879             var typeArguments = tryParseTypeArguments();
22880             var attributes = parseJsxAttributes();
22881             var node;
22882             if (token() === 31 /* GreaterThanToken */) {
22883                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
22884                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
22885                 // scanning errors
22886                 node = createNode(268 /* JsxOpeningElement */, fullStart);
22887                 scanJsxText();
22888             }
22889             else {
22890                 parseExpected(43 /* SlashToken */);
22891                 if (inExpressionContext) {
22892                     parseExpected(31 /* GreaterThanToken */);
22893                 }
22894                 else {
22895                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22896                     scanJsxText();
22897                 }
22898                 node = createNode(267 /* JsxSelfClosingElement */, fullStart);
22899             }
22900             node.tagName = tagName;
22901             node.typeArguments = typeArguments;
22902             node.attributes = attributes;
22903             return finishNode(node);
22904         }
22905         function parseJsxElementName() {
22906             scanJsxIdentifier();
22907             // JsxElement can have name in the form of
22908             //      propertyAccessExpression
22909             //      primaryExpression in the form of an identifier and "this" keyword
22910             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
22911             // We only want to consider "this" as a primaryExpression
22912             var expression = token() === 104 /* ThisKeyword */ ?
22913                 parseTokenNode() : parseIdentifierName();
22914             while (parseOptional(24 /* DotToken */)) {
22915                 var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
22916                 propertyAccess.expression = expression;
22917                 propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false);
22918                 expression = finishNode(propertyAccess);
22919             }
22920             return expression;
22921         }
22922         function parseJsxExpression(inExpressionContext) {
22923             var node = createNode(276 /* JsxExpression */);
22924             if (!parseExpected(18 /* OpenBraceToken */)) {
22925                 return undefined;
22926             }
22927             if (token() !== 19 /* CloseBraceToken */) {
22928                 node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
22929                 // Only an AssignmentExpression is valid here per the JSX spec,
22930                 // but we can unambiguously parse a comma sequence and provide
22931                 // a better error message in grammar checking.
22932                 node.expression = parseExpression();
22933             }
22934             if (inExpressionContext) {
22935                 parseExpected(19 /* CloseBraceToken */);
22936             }
22937             else {
22938                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
22939                     scanJsxText();
22940                 }
22941             }
22942             return finishNode(node);
22943         }
22944         function parseJsxAttribute() {
22945             if (token() === 18 /* OpenBraceToken */) {
22946                 return parseJsxSpreadAttribute();
22947             }
22948             scanJsxIdentifier();
22949             var node = createNode(273 /* JsxAttribute */);
22950             node.name = parseIdentifierName();
22951             if (token() === 62 /* EqualsToken */) {
22952                 switch (scanJsxAttributeValue()) {
22953                     case 10 /* StringLiteral */:
22954                         node.initializer = parseLiteralNode();
22955                         break;
22956                     default:
22957                         node.initializer = parseJsxExpression(/*inExpressionContext*/ true);
22958                         break;
22959                 }
22960             }
22961             return finishNode(node);
22962         }
22963         function parseJsxSpreadAttribute() {
22964             var node = createNode(275 /* JsxSpreadAttribute */);
22965             parseExpected(18 /* OpenBraceToken */);
22966             parseExpected(25 /* DotDotDotToken */);
22967             node.expression = parseExpression();
22968             parseExpected(19 /* CloseBraceToken */);
22969             return finishNode(node);
22970         }
22971         function parseJsxClosingElement(inExpressionContext) {
22972             var node = createNode(269 /* JsxClosingElement */);
22973             parseExpected(30 /* LessThanSlashToken */);
22974             node.tagName = parseJsxElementName();
22975             if (inExpressionContext) {
22976                 parseExpected(31 /* GreaterThanToken */);
22977             }
22978             else {
22979                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22980                 scanJsxText();
22981             }
22982             return finishNode(node);
22983         }
22984         function parseJsxClosingFragment(inExpressionContext) {
22985             var node = createNode(272 /* JsxClosingFragment */);
22986             parseExpected(30 /* LessThanSlashToken */);
22987             if (ts.tokenIsIdentifierOrKeyword(token())) {
22988                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
22989             }
22990             if (inExpressionContext) {
22991                 parseExpected(31 /* GreaterThanToken */);
22992             }
22993             else {
22994                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
22995                 scanJsxText();
22996             }
22997             return finishNode(node);
22998         }
22999         function parseTypeAssertion() {
23000             var node = createNode(199 /* TypeAssertionExpression */);
23001             parseExpected(29 /* LessThanToken */);
23002             node.type = parseType();
23003             parseExpected(31 /* GreaterThanToken */);
23004             node.expression = parseSimpleUnaryExpression();
23005             return finishNode(node);
23006         }
23007         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
23008             nextToken();
23009             return ts.tokenIsIdentifierOrKeyword(token())
23010                 || token() === 22 /* OpenBracketToken */
23011                 || isTemplateStartOfTaggedTemplate();
23012         }
23013         function isStartOfOptionalPropertyOrElementAccessChain() {
23014             return token() === 28 /* QuestionDotToken */
23015                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
23016         }
23017         function tryReparseOptionalChain(node) {
23018             if (node.flags & 32 /* OptionalChain */) {
23019                 return true;
23020             }
23021             // check for an optional chain in a non-null expression
23022             if (ts.isNonNullExpression(node)) {
23023                 var expr = node.expression;
23024                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
23025                     expr = expr.expression;
23026                 }
23027                 if (expr.flags & 32 /* OptionalChain */) {
23028                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
23029                     while (ts.isNonNullExpression(node)) {
23030                         node.flags |= 32 /* OptionalChain */;
23031                         node = node.expression;
23032                     }
23033                     return true;
23034                 }
23035             }
23036             return false;
23037         }
23038         function parsePropertyAccessExpressionRest(expression, questionDotToken) {
23039             var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23040             propertyAccess.expression = expression;
23041             propertyAccess.questionDotToken = questionDotToken;
23042             propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
23043             if (questionDotToken || tryReparseOptionalChain(expression)) {
23044                 propertyAccess.flags |= 32 /* OptionalChain */;
23045                 if (ts.isPrivateIdentifier(propertyAccess.name)) {
23046                     parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
23047                 }
23048             }
23049             return finishNode(propertyAccess);
23050         }
23051         function parseElementAccessExpressionRest(expression, questionDotToken) {
23052             var indexedAccess = createNode(195 /* ElementAccessExpression */, expression.pos);
23053             indexedAccess.expression = expression;
23054             indexedAccess.questionDotToken = questionDotToken;
23055             if (token() === 23 /* CloseBracketToken */) {
23056                 indexedAccess.argumentExpression = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
23057             }
23058             else {
23059                 var argument = allowInAnd(parseExpression);
23060                 if (ts.isStringOrNumericLiteralLike(argument)) {
23061                     argument.text = internIdentifier(argument.text);
23062                 }
23063                 indexedAccess.argumentExpression = argument;
23064             }
23065             parseExpected(23 /* CloseBracketToken */);
23066             if (questionDotToken || tryReparseOptionalChain(expression)) {
23067                 indexedAccess.flags |= 32 /* OptionalChain */;
23068             }
23069             return finishNode(indexedAccess);
23070         }
23071         function parseMemberExpressionRest(expression, allowOptionalChain) {
23072             while (true) {
23073                 var questionDotToken = void 0;
23074                 var isPropertyAccess = false;
23075                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
23076                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
23077                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
23078                 }
23079                 else {
23080                     isPropertyAccess = parseOptional(24 /* DotToken */);
23081                 }
23082                 if (isPropertyAccess) {
23083                     expression = parsePropertyAccessExpressionRest(expression, questionDotToken);
23084                     continue;
23085                 }
23086                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
23087                     nextToken();
23088                     var nonNullExpression = createNode(218 /* NonNullExpression */, expression.pos);
23089                     nonNullExpression.expression = expression;
23090                     expression = finishNode(nonNullExpression);
23091                     continue;
23092                 }
23093                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
23094                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
23095                     expression = parseElementAccessExpressionRest(expression, questionDotToken);
23096                     continue;
23097                 }
23098                 if (isTemplateStartOfTaggedTemplate()) {
23099                     expression = parseTaggedTemplateRest(expression, questionDotToken, /*typeArguments*/ undefined);
23100                     continue;
23101                 }
23102                 return expression;
23103             }
23104         }
23105         function isTemplateStartOfTaggedTemplate() {
23106             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
23107         }
23108         function parseTaggedTemplateRest(tag, questionDotToken, typeArguments) {
23109             var tagExpression = createNode(198 /* TaggedTemplateExpression */, tag.pos);
23110             tagExpression.tag = tag;
23111             tagExpression.questionDotToken = questionDotToken;
23112             tagExpression.typeArguments = typeArguments;
23113             tagExpression.template = token() === 14 /* NoSubstitutionTemplateLiteral */
23114                 ? (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode())
23115                 : parseTemplateExpression(/*isTaggedTemplate*/ true);
23116             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
23117                 tagExpression.flags |= 32 /* OptionalChain */;
23118             }
23119             return finishNode(tagExpression);
23120         }
23121         function parseCallExpressionRest(expression) {
23122             while (true) {
23123                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ true);
23124                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
23125                 // handle 'foo<<T>()'
23126                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
23127                     // See if this is the start of a generic invocation.  If so, consume it and
23128                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
23129                     // part of an arithmetic expression.  Break out so we consume it higher in the
23130                     // stack.
23131                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
23132                     if (typeArguments) {
23133                         if (isTemplateStartOfTaggedTemplate()) {
23134                             expression = parseTaggedTemplateRest(expression, questionDotToken, typeArguments);
23135                             continue;
23136                         }
23137                         var callExpr = createNode(196 /* CallExpression */, expression.pos);
23138                         callExpr.expression = expression;
23139                         callExpr.questionDotToken = questionDotToken;
23140                         callExpr.typeArguments = typeArguments;
23141                         callExpr.arguments = parseArgumentList();
23142                         if (questionDotToken || tryReparseOptionalChain(expression)) {
23143                             callExpr.flags |= 32 /* OptionalChain */;
23144                         }
23145                         expression = finishNode(callExpr);
23146                         continue;
23147                     }
23148                 }
23149                 else if (token() === 20 /* OpenParenToken */) {
23150                     var callExpr = createNode(196 /* CallExpression */, expression.pos);
23151                     callExpr.expression = expression;
23152                     callExpr.questionDotToken = questionDotToken;
23153                     callExpr.arguments = parseArgumentList();
23154                     if (questionDotToken || tryReparseOptionalChain(expression)) {
23155                         callExpr.flags |= 32 /* OptionalChain */;
23156                     }
23157                     expression = finishNode(callExpr);
23158                     continue;
23159                 }
23160                 if (questionDotToken) {
23161                     // We failed to parse anything, so report a missing identifier here.
23162                     var propertyAccess = createNode(194 /* PropertyAccessExpression */, expression.pos);
23163                     propertyAccess.expression = expression;
23164                     propertyAccess.questionDotToken = questionDotToken;
23165                     propertyAccess.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
23166                     propertyAccess.flags |= 32 /* OptionalChain */;
23167                     expression = finishNode(propertyAccess);
23168                 }
23169                 break;
23170             }
23171             return expression;
23172         }
23173         function parseArgumentList() {
23174             parseExpected(20 /* OpenParenToken */);
23175             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
23176             parseExpected(21 /* CloseParenToken */);
23177             return result;
23178         }
23179         function parseTypeArgumentsInExpression() {
23180             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
23181                 return undefined;
23182             }
23183             nextToken();
23184             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
23185             if (!parseExpected(31 /* GreaterThanToken */)) {
23186                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
23187                 return undefined;
23188             }
23189             // If we have a '<', then only parse this as a argument list if the type arguments
23190             // are complete and we have an open paren.  if we don't, rewind and return nothing.
23191             return typeArguments && canFollowTypeArgumentsInExpression()
23192                 ? typeArguments
23193                 : undefined;
23194         }
23195         function canFollowTypeArgumentsInExpression() {
23196             switch (token()) {
23197                 case 20 /* OpenParenToken */: // foo<x>(
23198                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
23199                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
23200                 // these are the only tokens can legally follow a type argument
23201                 // list. So we definitely want to treat them as type arg lists.
23202                 // falls through
23203                 case 24 /* DotToken */: // foo<x>.
23204                 case 21 /* CloseParenToken */: // foo<x>)
23205                 case 23 /* CloseBracketToken */: // foo<x>]
23206                 case 58 /* ColonToken */: // foo<x>:
23207                 case 26 /* SemicolonToken */: // foo<x>;
23208                 case 57 /* QuestionToken */: // foo<x>?
23209                 case 34 /* EqualsEqualsToken */: // foo<x> ==
23210                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
23211                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
23212                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
23213                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
23214                 case 56 /* BarBarToken */: // foo<x> ||
23215                 case 60 /* QuestionQuestionToken */: // foo<x> ??
23216                 case 52 /* CaretToken */: // foo<x> ^
23217                 case 50 /* AmpersandToken */: // foo<x> &
23218                 case 51 /* BarToken */: // foo<x> |
23219                 case 19 /* CloseBraceToken */: // foo<x> }
23220                 case 1 /* EndOfFileToken */: // foo<x>
23221                     // these cases can't legally follow a type arg list.  However, they're not legal
23222                     // expressions either.  The user is probably in the middle of a generic type. So
23223                     // treat it as such.
23224                     return true;
23225                 case 27 /* CommaToken */: // foo<x>,
23226                 case 18 /* OpenBraceToken */: // foo<x> {
23227                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
23228                 // as an invocation expression.  Instead, we want to parse out the expression
23229                 // in isolation from the type arguments.
23230                 // falls through
23231                 default:
23232                     // Anything else treat as an expression.
23233                     return false;
23234             }
23235         }
23236         function parsePrimaryExpression() {
23237             switch (token()) {
23238                 case 8 /* NumericLiteral */:
23239                 case 9 /* BigIntLiteral */:
23240                 case 10 /* StringLiteral */:
23241                 case 14 /* NoSubstitutionTemplateLiteral */:
23242                     return parseLiteralNode();
23243                 case 104 /* ThisKeyword */:
23244                 case 102 /* SuperKeyword */:
23245                 case 100 /* NullKeyword */:
23246                 case 106 /* TrueKeyword */:
23247                 case 91 /* FalseKeyword */:
23248                     return parseTokenNode();
23249                 case 20 /* OpenParenToken */:
23250                     return parseParenthesizedExpression();
23251                 case 22 /* OpenBracketToken */:
23252                     return parseArrayLiteralExpression();
23253                 case 18 /* OpenBraceToken */:
23254                     return parseObjectLiteralExpression();
23255                 case 126 /* AsyncKeyword */:
23256                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
23257                     // If we encounter `async [no LineTerminator here] function` then this is an async
23258                     // function; otherwise, its an identifier.
23259                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
23260                         break;
23261                     }
23262                     return parseFunctionExpression();
23263                 case 80 /* ClassKeyword */:
23264                     return parseClassExpression();
23265                 case 94 /* FunctionKeyword */:
23266                     return parseFunctionExpression();
23267                 case 99 /* NewKeyword */:
23268                     return parseNewExpressionOrNewDotTarget();
23269                 case 43 /* SlashToken */:
23270                 case 67 /* SlashEqualsToken */:
23271                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
23272                         return parseLiteralNode();
23273                     }
23274                     break;
23275                 case 15 /* TemplateHead */:
23276                     return parseTemplateExpression(/* isTaggedTemplate */ false);
23277             }
23278             return parseIdentifier(ts.Diagnostics.Expression_expected);
23279         }
23280         function parseParenthesizedExpression() {
23281             var node = createNodeWithJSDoc(200 /* ParenthesizedExpression */);
23282             parseExpected(20 /* OpenParenToken */);
23283             node.expression = allowInAnd(parseExpression);
23284             parseExpected(21 /* CloseParenToken */);
23285             return finishNode(node);
23286         }
23287         function parseSpreadElement() {
23288             var node = createNode(213 /* SpreadElement */);
23289             parseExpected(25 /* DotDotDotToken */);
23290             node.expression = parseAssignmentExpressionOrHigher();
23291             return finishNode(node);
23292         }
23293         function parseArgumentOrArrayLiteralElement() {
23294             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
23295                 token() === 27 /* CommaToken */ ? createNode(215 /* OmittedExpression */) :
23296                     parseAssignmentExpressionOrHigher();
23297         }
23298         function parseArgumentExpression() {
23299             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
23300         }
23301         function parseArrayLiteralExpression() {
23302             var node = createNode(192 /* ArrayLiteralExpression */);
23303             parseExpected(22 /* OpenBracketToken */);
23304             if (scanner.hasPrecedingLineBreak()) {
23305                 node.multiLine = true;
23306             }
23307             node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
23308             parseExpected(23 /* CloseBracketToken */);
23309             return finishNode(node);
23310         }
23311         function parseObjectLiteralElement() {
23312             var node = createNodeWithJSDoc(0 /* Unknown */);
23313             if (parseOptionalToken(25 /* DotDotDotToken */)) {
23314                 node.kind = 283 /* SpreadAssignment */;
23315                 node.expression = parseAssignmentExpressionOrHigher();
23316                 return finishNode(node);
23317             }
23318             node.decorators = parseDecorators();
23319             node.modifiers = parseModifiers();
23320             if (parseContextualModifier(131 /* GetKeyword */)) {
23321                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
23322             }
23323             if (parseContextualModifier(142 /* SetKeyword */)) {
23324                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
23325             }
23326             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23327             var tokenIsIdentifier = isIdentifier();
23328             node.name = parsePropertyName();
23329             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
23330             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
23331             node.exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
23332             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
23333                 return parseMethodDeclaration(node, asteriskToken);
23334             }
23335             // check if it is short-hand property assignment or normal property assignment
23336             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
23337             // CoverInitializedName[Yield] :
23338             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
23339             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
23340             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
23341             if (isShorthandPropertyAssignment) {
23342                 node.kind = 282 /* ShorthandPropertyAssignment */;
23343                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
23344                 if (equalsToken) {
23345                     node.equalsToken = equalsToken;
23346                     node.objectAssignmentInitializer = allowInAnd(parseAssignmentExpressionOrHigher);
23347                 }
23348             }
23349             else {
23350                 node.kind = 281 /* PropertyAssignment */;
23351                 parseExpected(58 /* ColonToken */);
23352                 node.initializer = allowInAnd(parseAssignmentExpressionOrHigher);
23353             }
23354             return finishNode(node);
23355         }
23356         function parseObjectLiteralExpression() {
23357             var node = createNode(193 /* ObjectLiteralExpression */);
23358             var openBracePosition = scanner.getTokenPos();
23359             parseExpected(18 /* OpenBraceToken */);
23360             if (scanner.hasPrecedingLineBreak()) {
23361                 node.multiLine = true;
23362             }
23363             node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
23364             if (!parseExpected(19 /* CloseBraceToken */)) {
23365                 var lastError = ts.lastOrUndefined(parseDiagnostics);
23366                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23367                     ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23368                 }
23369             }
23370             return finishNode(node);
23371         }
23372         function parseFunctionExpression() {
23373             // GeneratorExpression:
23374             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
23375             //
23376             // FunctionExpression:
23377             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
23378             var saveDecoratorContext = inDecoratorContext();
23379             if (saveDecoratorContext) {
23380                 setDecoratorContext(/*val*/ false);
23381             }
23382             var node = createNodeWithJSDoc(201 /* FunctionExpression */);
23383             node.modifiers = parseModifiers();
23384             parseExpected(94 /* FunctionKeyword */);
23385             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
23386             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
23387             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
23388             node.name =
23389                 isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) :
23390                     isGenerator ? doInYieldContext(parseOptionalIdentifier) :
23391                         isAsync ? doInAwaitContext(parseOptionalIdentifier) :
23392                             parseOptionalIdentifier();
23393             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
23394             node.body = parseFunctionBlock(isGenerator | isAsync);
23395             if (saveDecoratorContext) {
23396                 setDecoratorContext(/*val*/ true);
23397             }
23398             return finishNode(node);
23399         }
23400         function parseOptionalIdentifier() {
23401             return isIdentifier() ? parseIdentifier() : undefined;
23402         }
23403         function parseNewExpressionOrNewDotTarget() {
23404             var fullStart = scanner.getStartPos();
23405             parseExpected(99 /* NewKeyword */);
23406             if (parseOptional(24 /* DotToken */)) {
23407                 var node_2 = createNode(219 /* MetaProperty */, fullStart);
23408                 node_2.keywordToken = 99 /* NewKeyword */;
23409                 node_2.name = parseIdentifierName();
23410                 return finishNode(node_2);
23411             }
23412             var expression = parsePrimaryExpression();
23413             var typeArguments;
23414             while (true) {
23415                 expression = parseMemberExpressionRest(expression, /*allowOptionalChain*/ false);
23416                 typeArguments = tryParse(parseTypeArgumentsInExpression);
23417                 if (isTemplateStartOfTaggedTemplate()) {
23418                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
23419                     expression = parseTaggedTemplateRest(expression, /*optionalChain*/ undefined, typeArguments);
23420                     typeArguments = undefined;
23421                 }
23422                 break;
23423             }
23424             var node = createNode(197 /* NewExpression */, fullStart);
23425             node.expression = expression;
23426             node.typeArguments = typeArguments;
23427             if (token() === 20 /* OpenParenToken */) {
23428                 node.arguments = parseArgumentList();
23429             }
23430             else if (node.typeArguments) {
23431                 parseErrorAt(fullStart, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
23432             }
23433             return finishNode(node);
23434         }
23435         // STATEMENTS
23436         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
23437             var node = createNode(223 /* Block */);
23438             var openBracePosition = scanner.getTokenPos();
23439             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
23440                 if (scanner.hasPrecedingLineBreak()) {
23441                     node.multiLine = true;
23442                 }
23443                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
23444                 if (!parseExpected(19 /* CloseBraceToken */)) {
23445                     var lastError = ts.lastOrUndefined(parseDiagnostics);
23446                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
23447                         ts.addRelatedInfo(lastError, ts.createFileDiagnostic(sourceFile, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
23448                     }
23449                 }
23450             }
23451             else {
23452                 node.statements = createMissingList();
23453             }
23454             return finishNode(node);
23455         }
23456         function parseFunctionBlock(flags, diagnosticMessage) {
23457             var savedYieldContext = inYieldContext();
23458             setYieldContext(!!(flags & 1 /* Yield */));
23459             var savedAwaitContext = inAwaitContext();
23460             setAwaitContext(!!(flags & 2 /* Await */));
23461             // We may be in a [Decorator] context when parsing a function expression or
23462             // arrow function. The body of the function is not in [Decorator] context.
23463             var saveDecoratorContext = inDecoratorContext();
23464             if (saveDecoratorContext) {
23465                 setDecoratorContext(/*val*/ false);
23466             }
23467             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
23468             if (saveDecoratorContext) {
23469                 setDecoratorContext(/*val*/ true);
23470             }
23471             setYieldContext(savedYieldContext);
23472             setAwaitContext(savedAwaitContext);
23473             return block;
23474         }
23475         function parseEmptyStatement() {
23476             var node = createNode(224 /* EmptyStatement */);
23477             parseExpected(26 /* SemicolonToken */);
23478             return finishNode(node);
23479         }
23480         function parseIfStatement() {
23481             var node = createNode(227 /* IfStatement */);
23482             parseExpected(95 /* IfKeyword */);
23483             parseExpected(20 /* OpenParenToken */);
23484             node.expression = allowInAnd(parseExpression);
23485             parseExpected(21 /* CloseParenToken */);
23486             node.thenStatement = parseStatement();
23487             node.elseStatement = parseOptional(87 /* ElseKeyword */) ? parseStatement() : undefined;
23488             return finishNode(node);
23489         }
23490         function parseDoStatement() {
23491             var node = createNode(228 /* DoStatement */);
23492             parseExpected(86 /* DoKeyword */);
23493             node.statement = parseStatement();
23494             parseExpected(111 /* WhileKeyword */);
23495             parseExpected(20 /* OpenParenToken */);
23496             node.expression = allowInAnd(parseExpression);
23497             parseExpected(21 /* CloseParenToken */);
23498             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
23499             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
23500             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
23501             //  do;while(0)x will have a semicolon inserted before x.
23502             parseOptional(26 /* SemicolonToken */);
23503             return finishNode(node);
23504         }
23505         function parseWhileStatement() {
23506             var node = createNode(229 /* WhileStatement */);
23507             parseExpected(111 /* WhileKeyword */);
23508             parseExpected(20 /* OpenParenToken */);
23509             node.expression = allowInAnd(parseExpression);
23510             parseExpected(21 /* CloseParenToken */);
23511             node.statement = parseStatement();
23512             return finishNode(node);
23513         }
23514         function parseForOrForInOrForOfStatement() {
23515             var pos = getNodePos();
23516             parseExpected(93 /* ForKeyword */);
23517             var awaitToken = parseOptionalToken(127 /* AwaitKeyword */);
23518             parseExpected(20 /* OpenParenToken */);
23519             var initializer;
23520             if (token() !== 26 /* SemicolonToken */) {
23521                 if (token() === 109 /* VarKeyword */ || token() === 115 /* LetKeyword */ || token() === 81 /* ConstKeyword */) {
23522                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
23523                 }
23524                 else {
23525                     initializer = disallowInAnd(parseExpression);
23526                 }
23527             }
23528             var forOrForInOrForOfStatement;
23529             if (awaitToken ? parseExpected(152 /* OfKeyword */) : parseOptional(152 /* OfKeyword */)) {
23530                 var forOfStatement = createNode(232 /* ForOfStatement */, pos);
23531                 forOfStatement.awaitModifier = awaitToken;
23532                 forOfStatement.initializer = initializer;
23533                 forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher);
23534                 parseExpected(21 /* CloseParenToken */);
23535                 forOrForInOrForOfStatement = forOfStatement;
23536             }
23537             else if (parseOptional(97 /* InKeyword */)) {
23538                 var forInStatement = createNode(231 /* ForInStatement */, pos);
23539                 forInStatement.initializer = initializer;
23540                 forInStatement.expression = allowInAnd(parseExpression);
23541                 parseExpected(21 /* CloseParenToken */);
23542                 forOrForInOrForOfStatement = forInStatement;
23543             }
23544             else {
23545                 var forStatement = createNode(230 /* ForStatement */, pos);
23546                 forStatement.initializer = initializer;
23547                 parseExpected(26 /* SemicolonToken */);
23548                 if (token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */) {
23549                     forStatement.condition = allowInAnd(parseExpression);
23550                 }
23551                 parseExpected(26 /* SemicolonToken */);
23552                 if (token() !== 21 /* CloseParenToken */) {
23553                     forStatement.incrementor = allowInAnd(parseExpression);
23554                 }
23555                 parseExpected(21 /* CloseParenToken */);
23556                 forOrForInOrForOfStatement = forStatement;
23557             }
23558             forOrForInOrForOfStatement.statement = parseStatement();
23559             return finishNode(forOrForInOrForOfStatement);
23560         }
23561         function parseBreakOrContinueStatement(kind) {
23562             var node = createNode(kind);
23563             parseExpected(kind === 234 /* BreakStatement */ ? 77 /* BreakKeyword */ : 82 /* ContinueKeyword */);
23564             if (!canParseSemicolon()) {
23565                 node.label = parseIdentifier();
23566             }
23567             parseSemicolon();
23568             return finishNode(node);
23569         }
23570         function parseReturnStatement() {
23571             var node = createNode(235 /* ReturnStatement */);
23572             parseExpected(101 /* ReturnKeyword */);
23573             if (!canParseSemicolon()) {
23574                 node.expression = allowInAnd(parseExpression);
23575             }
23576             parseSemicolon();
23577             return finishNode(node);
23578         }
23579         function parseWithStatement() {
23580             var node = createNode(236 /* WithStatement */);
23581             parseExpected(112 /* WithKeyword */);
23582             parseExpected(20 /* OpenParenToken */);
23583             node.expression = allowInAnd(parseExpression);
23584             parseExpected(21 /* CloseParenToken */);
23585             node.statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
23586             return finishNode(node);
23587         }
23588         function parseCaseClause() {
23589             var node = createNode(277 /* CaseClause */);
23590             parseExpected(78 /* CaseKeyword */);
23591             node.expression = allowInAnd(parseExpression);
23592             parseExpected(58 /* ColonToken */);
23593             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23594             return finishNode(node);
23595         }
23596         function parseDefaultClause() {
23597             var node = createNode(278 /* DefaultClause */);
23598             parseExpected(84 /* DefaultKeyword */);
23599             parseExpected(58 /* ColonToken */);
23600             node.statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
23601             return finishNode(node);
23602         }
23603         function parseCaseOrDefaultClause() {
23604             return token() === 78 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
23605         }
23606         function parseSwitchStatement() {
23607             var node = createNode(237 /* SwitchStatement */);
23608             parseExpected(103 /* SwitchKeyword */);
23609             parseExpected(20 /* OpenParenToken */);
23610             node.expression = allowInAnd(parseExpression);
23611             parseExpected(21 /* CloseParenToken */);
23612             var caseBlock = createNode(251 /* CaseBlock */);
23613             parseExpected(18 /* OpenBraceToken */);
23614             caseBlock.clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
23615             parseExpected(19 /* CloseBraceToken */);
23616             node.caseBlock = finishNode(caseBlock);
23617             return finishNode(node);
23618         }
23619         function parseThrowStatement() {
23620             // ThrowStatement[Yield] :
23621             //      throw [no LineTerminator here]Expression[In, ?Yield];
23622             // Because of automatic semicolon insertion, we need to report error if this
23623             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
23624             // directly as that might consume an expression on the following line.
23625             // We just return 'undefined' in that case.  The actual error will be reported in the
23626             // grammar walker.
23627             var node = createNode(239 /* ThrowStatement */);
23628             parseExpected(105 /* ThrowKeyword */);
23629             node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
23630             parseSemicolon();
23631             return finishNode(node);
23632         }
23633         // TODO: Review for error recovery
23634         function parseTryStatement() {
23635             var node = createNode(240 /* TryStatement */);
23636             parseExpected(107 /* TryKeyword */);
23637             node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23638             node.catchClause = token() === 79 /* CatchKeyword */ ? parseCatchClause() : undefined;
23639             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
23640             // one out no matter what.
23641             if (!node.catchClause || token() === 92 /* FinallyKeyword */) {
23642                 parseExpected(92 /* FinallyKeyword */);
23643                 node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
23644             }
23645             return finishNode(node);
23646         }
23647         function parseCatchClause() {
23648             var result = createNode(280 /* CatchClause */);
23649             parseExpected(79 /* CatchKeyword */);
23650             if (parseOptional(20 /* OpenParenToken */)) {
23651                 result.variableDeclaration = parseVariableDeclaration();
23652                 parseExpected(21 /* CloseParenToken */);
23653             }
23654             else {
23655                 // Keep shape of node to avoid degrading performance.
23656                 result.variableDeclaration = undefined;
23657             }
23658             result.block = parseBlock(/*ignoreMissingOpenBrace*/ false);
23659             return finishNode(result);
23660         }
23661         function parseDebuggerStatement() {
23662             var node = createNode(241 /* DebuggerStatement */);
23663             parseExpected(83 /* DebuggerKeyword */);
23664             parseSemicolon();
23665             return finishNode(node);
23666         }
23667         function parseExpressionOrLabeledStatement() {
23668             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
23669             // out an expression, seeing if it is identifier and then seeing if it is followed by
23670             // a colon.
23671             var node = createNodeWithJSDoc(token() === 75 /* Identifier */ ? 0 /* Unknown */ : 226 /* ExpressionStatement */);
23672             var expression = allowInAnd(parseExpression);
23673             if (expression.kind === 75 /* Identifier */ && parseOptional(58 /* ColonToken */)) {
23674                 node.kind = 238 /* LabeledStatement */;
23675                 node.label = expression;
23676                 node.statement = parseStatement();
23677             }
23678             else {
23679                 node.kind = 226 /* ExpressionStatement */;
23680                 node.expression = expression;
23681                 parseSemicolon();
23682             }
23683             return finishNode(node);
23684         }
23685         function nextTokenIsIdentifierOrKeywordOnSameLine() {
23686             nextToken();
23687             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
23688         }
23689         function nextTokenIsClassKeywordOnSameLine() {
23690             nextToken();
23691             return token() === 80 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
23692         }
23693         function nextTokenIsFunctionKeywordOnSameLine() {
23694             nextToken();
23695             return token() === 94 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
23696         }
23697         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
23698             nextToken();
23699             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
23700         }
23701         function isDeclaration() {
23702             while (true) {
23703                 switch (token()) {
23704                     case 109 /* VarKeyword */:
23705                     case 115 /* LetKeyword */:
23706                     case 81 /* ConstKeyword */:
23707                     case 94 /* FunctionKeyword */:
23708                     case 80 /* ClassKeyword */:
23709                     case 88 /* EnumKeyword */:
23710                         return true;
23711                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
23712                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
23713                     // count on to parse out the respective declarations. For instance, we exploit this to say that
23714                     //
23715                     //    namespace n
23716                     //
23717                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
23718                     //
23719                     //    namespace
23720                     //    n
23721                     //
23722                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
23723                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
23724                     //
23725                     // *Note*: 'interface' is actually a strict mode reserved word. So while
23726                     //
23727                     //   "use strict"
23728                     //   interface
23729                     //   I {}
23730                     //
23731                     // could be legal, it would add complexity for very little gain.
23732                     case 114 /* InterfaceKeyword */:
23733                     case 145 /* TypeKeyword */:
23734                         return nextTokenIsIdentifierOnSameLine();
23735                     case 135 /* ModuleKeyword */:
23736                     case 136 /* NamespaceKeyword */:
23737                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
23738                     case 122 /* AbstractKeyword */:
23739                     case 126 /* AsyncKeyword */:
23740                     case 130 /* DeclareKeyword */:
23741                     case 117 /* PrivateKeyword */:
23742                     case 118 /* ProtectedKeyword */:
23743                     case 119 /* PublicKeyword */:
23744                     case 138 /* ReadonlyKeyword */:
23745                         nextToken();
23746                         // ASI takes effect for this modifier.
23747                         if (scanner.hasPrecedingLineBreak()) {
23748                             return false;
23749                         }
23750                         continue;
23751                     case 150 /* GlobalKeyword */:
23752                         nextToken();
23753                         return token() === 18 /* OpenBraceToken */ || token() === 75 /* Identifier */ || token() === 89 /* ExportKeyword */;
23754                     case 96 /* ImportKeyword */:
23755                         nextToken();
23756                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
23757                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
23758                     case 89 /* ExportKeyword */:
23759                         var currentToken_1 = nextToken();
23760                         if (currentToken_1 === 145 /* TypeKeyword */) {
23761                             currentToken_1 = lookAhead(nextToken);
23762                         }
23763                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
23764                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 84 /* DefaultKeyword */ ||
23765                             currentToken_1 === 123 /* AsKeyword */) {
23766                             return true;
23767                         }
23768                         continue;
23769                     case 120 /* StaticKeyword */:
23770                         nextToken();
23771                         continue;
23772                     default:
23773                         return false;
23774                 }
23775             }
23776         }
23777         function isStartOfDeclaration() {
23778             return lookAhead(isDeclaration);
23779         }
23780         function isStartOfStatement() {
23781             switch (token()) {
23782                 case 59 /* AtToken */:
23783                 case 26 /* SemicolonToken */:
23784                 case 18 /* OpenBraceToken */:
23785                 case 109 /* VarKeyword */:
23786                 case 115 /* LetKeyword */:
23787                 case 94 /* FunctionKeyword */:
23788                 case 80 /* ClassKeyword */:
23789                 case 88 /* EnumKeyword */:
23790                 case 95 /* IfKeyword */:
23791                 case 86 /* DoKeyword */:
23792                 case 111 /* WhileKeyword */:
23793                 case 93 /* ForKeyword */:
23794                 case 82 /* ContinueKeyword */:
23795                 case 77 /* BreakKeyword */:
23796                 case 101 /* ReturnKeyword */:
23797                 case 112 /* WithKeyword */:
23798                 case 103 /* SwitchKeyword */:
23799                 case 105 /* ThrowKeyword */:
23800                 case 107 /* TryKeyword */:
23801                 case 83 /* DebuggerKeyword */:
23802                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
23803                 // however, we say they are here so that we may gracefully parse them and error later.
23804                 // falls through
23805                 case 79 /* CatchKeyword */:
23806                 case 92 /* FinallyKeyword */:
23807                     return true;
23808                 case 96 /* ImportKeyword */:
23809                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
23810                 case 81 /* ConstKeyword */:
23811                 case 89 /* ExportKeyword */:
23812                     return isStartOfDeclaration();
23813                 case 126 /* AsyncKeyword */:
23814                 case 130 /* DeclareKeyword */:
23815                 case 114 /* InterfaceKeyword */:
23816                 case 135 /* ModuleKeyword */:
23817                 case 136 /* NamespaceKeyword */:
23818                 case 145 /* TypeKeyword */:
23819                 case 150 /* GlobalKeyword */:
23820                     // When these don't start a declaration, they're an identifier in an expression statement
23821                     return true;
23822                 case 119 /* PublicKeyword */:
23823                 case 117 /* PrivateKeyword */:
23824                 case 118 /* ProtectedKeyword */:
23825                 case 120 /* StaticKeyword */:
23826                 case 138 /* ReadonlyKeyword */:
23827                     // When these don't start a declaration, they may be the start of a class member if an identifier
23828                     // immediately follows. Otherwise they're an identifier in an expression statement.
23829                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
23830                 default:
23831                     return isStartOfExpression();
23832             }
23833         }
23834         function nextTokenIsIdentifierOrStartOfDestructuring() {
23835             nextToken();
23836             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
23837         }
23838         function isLetDeclaration() {
23839             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
23840             // or [.
23841             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
23842         }
23843         function parseStatement() {
23844             switch (token()) {
23845                 case 26 /* SemicolonToken */:
23846                     return parseEmptyStatement();
23847                 case 18 /* OpenBraceToken */:
23848                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
23849                 case 109 /* VarKeyword */:
23850                     return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23851                 case 115 /* LetKeyword */:
23852                     if (isLetDeclaration()) {
23853                         return parseVariableStatement(createNodeWithJSDoc(242 /* VariableDeclaration */));
23854                     }
23855                     break;
23856                 case 94 /* FunctionKeyword */:
23857                     return parseFunctionDeclaration(createNodeWithJSDoc(244 /* FunctionDeclaration */));
23858                 case 80 /* ClassKeyword */:
23859                     return parseClassDeclaration(createNodeWithJSDoc(245 /* ClassDeclaration */));
23860                 case 95 /* IfKeyword */:
23861                     return parseIfStatement();
23862                 case 86 /* DoKeyword */:
23863                     return parseDoStatement();
23864                 case 111 /* WhileKeyword */:
23865                     return parseWhileStatement();
23866                 case 93 /* ForKeyword */:
23867                     return parseForOrForInOrForOfStatement();
23868                 case 82 /* ContinueKeyword */:
23869                     return parseBreakOrContinueStatement(233 /* ContinueStatement */);
23870                 case 77 /* BreakKeyword */:
23871                     return parseBreakOrContinueStatement(234 /* BreakStatement */);
23872                 case 101 /* ReturnKeyword */:
23873                     return parseReturnStatement();
23874                 case 112 /* WithKeyword */:
23875                     return parseWithStatement();
23876                 case 103 /* SwitchKeyword */:
23877                     return parseSwitchStatement();
23878                 case 105 /* ThrowKeyword */:
23879                     return parseThrowStatement();
23880                 case 107 /* TryKeyword */:
23881                 // Include 'catch' and 'finally' for error recovery.
23882                 // falls through
23883                 case 79 /* CatchKeyword */:
23884                 case 92 /* FinallyKeyword */:
23885                     return parseTryStatement();
23886                 case 83 /* DebuggerKeyword */:
23887                     return parseDebuggerStatement();
23888                 case 59 /* AtToken */:
23889                     return parseDeclaration();
23890                 case 126 /* AsyncKeyword */:
23891                 case 114 /* InterfaceKeyword */:
23892                 case 145 /* TypeKeyword */:
23893                 case 135 /* ModuleKeyword */:
23894                 case 136 /* NamespaceKeyword */:
23895                 case 130 /* DeclareKeyword */:
23896                 case 81 /* ConstKeyword */:
23897                 case 88 /* EnumKeyword */:
23898                 case 89 /* ExportKeyword */:
23899                 case 96 /* ImportKeyword */:
23900                 case 117 /* PrivateKeyword */:
23901                 case 118 /* ProtectedKeyword */:
23902                 case 119 /* PublicKeyword */:
23903                 case 122 /* AbstractKeyword */:
23904                 case 120 /* StaticKeyword */:
23905                 case 138 /* ReadonlyKeyword */:
23906                 case 150 /* GlobalKeyword */:
23907                     if (isStartOfDeclaration()) {
23908                         return parseDeclaration();
23909                     }
23910                     break;
23911             }
23912             return parseExpressionOrLabeledStatement();
23913         }
23914         function isDeclareModifier(modifier) {
23915             return modifier.kind === 130 /* DeclareKeyword */;
23916         }
23917         function parseDeclaration() {
23918             var modifiers = lookAhead(function () { return (parseDecorators(), parseModifiers()); });
23919             // `parseListElement` attempted to get the reused node at this position,
23920             // but the ambient context flag was not yet set, so the node appeared
23921             // not reusable in that context.
23922             var isAmbient = ts.some(modifiers, isDeclareModifier);
23923             if (isAmbient) {
23924                 var node_3 = tryReuseAmbientDeclaration();
23925                 if (node_3) {
23926                     return node_3;
23927                 }
23928             }
23929             var node = createNodeWithJSDoc(0 /* Unknown */);
23930             node.decorators = parseDecorators();
23931             node.modifiers = parseModifiers();
23932             if (isAmbient) {
23933                 for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
23934                     var m = _a[_i];
23935                     m.flags |= 8388608 /* Ambient */;
23936                 }
23937                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(node); });
23938             }
23939             else {
23940                 return parseDeclarationWorker(node);
23941             }
23942         }
23943         function tryReuseAmbientDeclaration() {
23944             return doInsideOfContext(8388608 /* Ambient */, function () {
23945                 var node = currentNode(parsingContext);
23946                 if (node) {
23947                     return consumeNode(node);
23948                 }
23949             });
23950         }
23951         function parseDeclarationWorker(node) {
23952             switch (token()) {
23953                 case 109 /* VarKeyword */:
23954                 case 115 /* LetKeyword */:
23955                 case 81 /* ConstKeyword */:
23956                     return parseVariableStatement(node);
23957                 case 94 /* FunctionKeyword */:
23958                     return parseFunctionDeclaration(node);
23959                 case 80 /* ClassKeyword */:
23960                     return parseClassDeclaration(node);
23961                 case 114 /* InterfaceKeyword */:
23962                     return parseInterfaceDeclaration(node);
23963                 case 145 /* TypeKeyword */:
23964                     return parseTypeAliasDeclaration(node);
23965                 case 88 /* EnumKeyword */:
23966                     return parseEnumDeclaration(node);
23967                 case 150 /* GlobalKeyword */:
23968                 case 135 /* ModuleKeyword */:
23969                 case 136 /* NamespaceKeyword */:
23970                     return parseModuleDeclaration(node);
23971                 case 96 /* ImportKeyword */:
23972                     return parseImportDeclarationOrImportEqualsDeclaration(node);
23973                 case 89 /* ExportKeyword */:
23974                     nextToken();
23975                     switch (token()) {
23976                         case 84 /* DefaultKeyword */:
23977                         case 62 /* EqualsToken */:
23978                             return parseExportAssignment(node);
23979                         case 123 /* AsKeyword */:
23980                             return parseNamespaceExportDeclaration(node);
23981                         default:
23982                             return parseExportDeclaration(node);
23983                     }
23984                 default:
23985                     if (node.decorators || node.modifiers) {
23986                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
23987                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
23988                         var missing = createMissingNode(264 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
23989                         missing.pos = node.pos;
23990                         missing.decorators = node.decorators;
23991                         missing.modifiers = node.modifiers;
23992                         return finishNode(missing);
23993                     }
23994                     return undefined; // TODO: GH#18217
23995             }
23996         }
23997         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
23998             nextToken();
23999             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
24000         }
24001         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
24002             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
24003                 parseSemicolon();
24004                 return;
24005             }
24006             return parseFunctionBlock(flags, diagnosticMessage);
24007         }
24008         // DECLARATIONS
24009         function parseArrayBindingElement() {
24010             if (token() === 27 /* CommaToken */) {
24011                 return createNode(215 /* OmittedExpression */);
24012             }
24013             var node = createNode(191 /* BindingElement */);
24014             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24015             node.name = parseIdentifierOrPattern();
24016             node.initializer = parseInitializer();
24017             return finishNode(node);
24018         }
24019         function parseObjectBindingElement() {
24020             var node = createNode(191 /* BindingElement */);
24021             node.dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
24022             var tokenIsIdentifier = isIdentifier();
24023             var propertyName = parsePropertyName();
24024             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
24025                 node.name = propertyName;
24026             }
24027             else {
24028                 parseExpected(58 /* ColonToken */);
24029                 node.propertyName = propertyName;
24030                 node.name = parseIdentifierOrPattern();
24031             }
24032             node.initializer = parseInitializer();
24033             return finishNode(node);
24034         }
24035         function parseObjectBindingPattern() {
24036             var node = createNode(189 /* ObjectBindingPattern */);
24037             parseExpected(18 /* OpenBraceToken */);
24038             node.elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
24039             parseExpected(19 /* CloseBraceToken */);
24040             return finishNode(node);
24041         }
24042         function parseArrayBindingPattern() {
24043             var node = createNode(190 /* ArrayBindingPattern */);
24044             parseExpected(22 /* OpenBracketToken */);
24045             node.elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
24046             parseExpected(23 /* CloseBracketToken */);
24047             return finishNode(node);
24048         }
24049         function isIdentifierOrPrivateIdentifierOrPattern() {
24050             return token() === 18 /* OpenBraceToken */
24051                 || token() === 22 /* OpenBracketToken */
24052                 || token() === 76 /* PrivateIdentifier */
24053                 || isIdentifier();
24054         }
24055         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
24056             if (token() === 22 /* OpenBracketToken */) {
24057                 return parseArrayBindingPattern();
24058             }
24059             if (token() === 18 /* OpenBraceToken */) {
24060                 return parseObjectBindingPattern();
24061             }
24062             return parseIdentifier(/*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
24063         }
24064         function parseVariableDeclarationAllowExclamation() {
24065             return parseVariableDeclaration(/*allowExclamation*/ true);
24066         }
24067         function parseVariableDeclaration(allowExclamation) {
24068             var node = createNode(242 /* VariableDeclaration */);
24069             node.name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
24070             if (allowExclamation && node.name.kind === 75 /* Identifier */ &&
24071                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24072                 node.exclamationToken = parseTokenNode();
24073             }
24074             node.type = parseTypeAnnotation();
24075             if (!isInOrOfKeyword(token())) {
24076                 node.initializer = parseInitializer();
24077             }
24078             return finishNode(node);
24079         }
24080         function parseVariableDeclarationList(inForStatementInitializer) {
24081             var node = createNode(243 /* VariableDeclarationList */);
24082             switch (token()) {
24083                 case 109 /* VarKeyword */:
24084                     break;
24085                 case 115 /* LetKeyword */:
24086                     node.flags |= 1 /* Let */;
24087                     break;
24088                 case 81 /* ConstKeyword */:
24089                     node.flags |= 2 /* Const */;
24090                     break;
24091                 default:
24092                     ts.Debug.fail();
24093             }
24094             nextToken();
24095             // The user may have written the following:
24096             //
24097             //    for (let of X) { }
24098             //
24099             // In this case, we want to parse an empty declaration list, and then parse 'of'
24100             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
24101             // So we need to look ahead to determine if 'of' should be treated as a keyword in
24102             // this context.
24103             // The checker will then give an error that there is an empty declaration list.
24104             if (token() === 152 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
24105                 node.declarations = createMissingList();
24106             }
24107             else {
24108                 var savedDisallowIn = inDisallowInContext();
24109                 setDisallowInContext(inForStatementInitializer);
24110                 node.declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
24111                 setDisallowInContext(savedDisallowIn);
24112             }
24113             return finishNode(node);
24114         }
24115         function canFollowContextualOfKeyword() {
24116             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
24117         }
24118         function parseVariableStatement(node) {
24119             node.kind = 225 /* VariableStatement */;
24120             node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
24121             parseSemicolon();
24122             return finishNode(node);
24123         }
24124         function parseFunctionDeclaration(node) {
24125             node.kind = 244 /* FunctionDeclaration */;
24126             parseExpected(94 /* FunctionKeyword */);
24127             node.asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24128             node.name = hasModifierOfKind(node, 84 /* DefaultKeyword */) ? parseOptionalIdentifier() : parseIdentifier();
24129             var isGenerator = node.asteriskToken ? 1 /* Yield */ : 0 /* None */;
24130             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24131             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24132             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
24133             return finishNode(node);
24134         }
24135         function parseConstructorName() {
24136             if (token() === 129 /* ConstructorKeyword */) {
24137                 return parseExpected(129 /* ConstructorKeyword */);
24138             }
24139             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
24140                 return tryParse(function () {
24141                     var literalNode = parseLiteralNode();
24142                     return literalNode.text === "constructor" ? literalNode : undefined;
24143                 });
24144             }
24145         }
24146         function tryParseConstructorDeclaration(node) {
24147             return tryParse(function () {
24148                 if (parseConstructorName()) {
24149                     node.kind = 162 /* Constructor */;
24150                     fillSignature(58 /* ColonToken */, 0 /* None */, node);
24151                     node.body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
24152                     return finishNode(node);
24153                 }
24154             });
24155         }
24156         function parseMethodDeclaration(node, asteriskToken, diagnosticMessage) {
24157             node.kind = 161 /* MethodDeclaration */;
24158             node.asteriskToken = asteriskToken;
24159             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
24160             var isAsync = hasModifierOfKind(node, 126 /* AsyncKeyword */) ? 2 /* Await */ : 0 /* None */;
24161             fillSignature(58 /* ColonToken */, isGenerator | isAsync, node);
24162             node.body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
24163             return finishNode(node);
24164         }
24165         function parsePropertyDeclaration(node) {
24166             node.kind = 159 /* PropertyDeclaration */;
24167             if (!node.questionToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
24168                 node.exclamationToken = parseTokenNode();
24169             }
24170             node.type = parseTypeAnnotation();
24171             node.initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
24172             parseSemicolon();
24173             return finishNode(node);
24174         }
24175         function parsePropertyOrMethodDeclaration(node) {
24176             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
24177             node.name = parsePropertyName();
24178             // Note: this is not legal as per the grammar.  But we allow it in the parser and
24179             // report an error in the grammar checker.
24180             node.questionToken = parseOptionalToken(57 /* QuestionToken */);
24181             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
24182                 return parseMethodDeclaration(node, asteriskToken, ts.Diagnostics.or_expected);
24183             }
24184             return parsePropertyDeclaration(node);
24185         }
24186         function parseAccessorDeclaration(node, kind) {
24187             node.kind = kind;
24188             node.name = parsePropertyName();
24189             fillSignature(58 /* ColonToken */, 0 /* None */, node);
24190             node.body = parseFunctionBlockOrSemicolon(0 /* None */);
24191             return finishNode(node);
24192         }
24193         function isClassMemberStart() {
24194             var idToken;
24195             if (token() === 59 /* AtToken */) {
24196                 return true;
24197             }
24198             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
24199             while (ts.isModifierKind(token())) {
24200                 idToken = token();
24201                 // If the idToken is a class modifier (protected, private, public, and static), it is
24202                 // certain that we are starting to parse class member. This allows better error recovery
24203                 // Example:
24204                 //      public foo() ...     // true
24205                 //      public @dec blah ... // true; we will then report an error later
24206                 //      export public ...    // true; we will then report an error later
24207                 if (ts.isClassMemberModifier(idToken)) {
24208                     return true;
24209                 }
24210                 nextToken();
24211             }
24212             if (token() === 41 /* AsteriskToken */) {
24213                 return true;
24214             }
24215             // Try to get the first property-like token following all modifiers.
24216             // This can either be an identifier or the 'get' or 'set' keywords.
24217             if (isLiteralPropertyName()) {
24218                 idToken = token();
24219                 nextToken();
24220             }
24221             // Index signatures and computed properties are class members; we can parse.
24222             if (token() === 22 /* OpenBracketToken */) {
24223                 return true;
24224             }
24225             // If we were able to get any potential identifier...
24226             if (idToken !== undefined) {
24227                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
24228                 if (!ts.isKeyword(idToken) || idToken === 142 /* SetKeyword */ || idToken === 131 /* GetKeyword */) {
24229                     return true;
24230                 }
24231                 // If it *is* a keyword, but not an accessor, check a little farther along
24232                 // to see if it should actually be parsed as a class member.
24233                 switch (token()) {
24234                     case 20 /* OpenParenToken */: // Method declaration
24235                     case 29 /* LessThanToken */: // Generic Method declaration
24236                     case 53 /* ExclamationToken */: // Non-null assertion on property name
24237                     case 58 /* ColonToken */: // Type Annotation for declaration
24238                     case 62 /* EqualsToken */: // Initializer for declaration
24239                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
24240                         return true;
24241                     default:
24242                         // Covers
24243                         //  - Semicolons     (declaration termination)
24244                         //  - Closing braces (end-of-class, must be declaration)
24245                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
24246                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
24247                         return canParseSemicolon();
24248                 }
24249             }
24250             return false;
24251         }
24252         function parseDecorators() {
24253             var list;
24254             var listPos = getNodePos();
24255             while (true) {
24256                 var decoratorStart = getNodePos();
24257                 if (!parseOptional(59 /* AtToken */)) {
24258                     break;
24259                 }
24260                 var decorator = createNode(157 /* Decorator */, decoratorStart);
24261                 decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher);
24262                 finishNode(decorator);
24263                 (list || (list = [])).push(decorator);
24264             }
24265             return list && createNodeArray(list, listPos);
24266         }
24267         /*
24268          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
24269          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
24270          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
24271          *
24272          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
24273          */
24274         function parseModifiers(permitInvalidConstAsModifier) {
24275             var list;
24276             var listPos = getNodePos();
24277             while (true) {
24278                 var modifierStart = scanner.getStartPos();
24279                 var modifierKind = token();
24280                 if (token() === 81 /* ConstKeyword */ && permitInvalidConstAsModifier) {
24281                     // We need to ensure that any subsequent modifiers appear on the same line
24282                     // so that when 'const' is a standalone declaration, we don't issue an error.
24283                     if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
24284                         break;
24285                     }
24286                 }
24287                 else {
24288                     if (!parseAnyContextualModifier()) {
24289                         break;
24290                     }
24291                 }
24292                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24293                 (list || (list = [])).push(modifier);
24294             }
24295             return list && createNodeArray(list, listPos);
24296         }
24297         function parseModifiersForArrowFunction() {
24298             var modifiers;
24299             if (token() === 126 /* AsyncKeyword */) {
24300                 var modifierStart = scanner.getStartPos();
24301                 var modifierKind = token();
24302                 nextToken();
24303                 var modifier = finishNode(createNode(modifierKind, modifierStart));
24304                 modifiers = createNodeArray([modifier], modifierStart);
24305             }
24306             return modifiers;
24307         }
24308         function parseClassElement() {
24309             if (token() === 26 /* SemicolonToken */) {
24310                 var result = createNode(222 /* SemicolonClassElement */);
24311                 nextToken();
24312                 return finishNode(result);
24313             }
24314             var node = createNodeWithJSDoc(0 /* Unknown */);
24315             node.decorators = parseDecorators();
24316             node.modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
24317             if (parseContextualModifier(131 /* GetKeyword */)) {
24318                 return parseAccessorDeclaration(node, 163 /* GetAccessor */);
24319             }
24320             if (parseContextualModifier(142 /* SetKeyword */)) {
24321                 return parseAccessorDeclaration(node, 164 /* SetAccessor */);
24322             }
24323             if (token() === 129 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
24324                 var constructorDeclaration = tryParseConstructorDeclaration(node);
24325                 if (constructorDeclaration) {
24326                     return constructorDeclaration;
24327                 }
24328             }
24329             if (isIndexSignature()) {
24330                 return parseIndexSignatureDeclaration(node);
24331             }
24332             // It is very important that we check this *after* checking indexers because
24333             // the [ token can start an index signature or a computed property name
24334             if (ts.tokenIsIdentifierOrKeyword(token()) ||
24335                 token() === 10 /* StringLiteral */ ||
24336                 token() === 8 /* NumericLiteral */ ||
24337                 token() === 41 /* AsteriskToken */ ||
24338                 token() === 22 /* OpenBracketToken */) {
24339                 var isAmbient = node.modifiers && ts.some(node.modifiers, isDeclareModifier);
24340                 if (isAmbient) {
24341                     for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
24342                         var m = _a[_i];
24343                         m.flags |= 8388608 /* Ambient */;
24344                     }
24345                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(node); });
24346                 }
24347                 else {
24348                     return parsePropertyOrMethodDeclaration(node);
24349                 }
24350             }
24351             if (node.decorators || node.modifiers) {
24352                 // treat this as a property declaration with a missing name.
24353                 node.name = createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
24354                 return parsePropertyDeclaration(node);
24355             }
24356             // 'isClassMemberStart' should have hinted not to attempt parsing.
24357             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
24358         }
24359         function parseClassExpression() {
24360             return parseClassDeclarationOrExpression(createNodeWithJSDoc(0 /* Unknown */), 214 /* ClassExpression */);
24361         }
24362         function parseClassDeclaration(node) {
24363             return parseClassDeclarationOrExpression(node, 245 /* ClassDeclaration */);
24364         }
24365         function parseClassDeclarationOrExpression(node, kind) {
24366             node.kind = kind;
24367             parseExpected(80 /* ClassKeyword */);
24368             node.name = parseNameOfClassDeclarationOrExpression();
24369             node.typeParameters = parseTypeParameters();
24370             node.heritageClauses = parseHeritageClauses();
24371             if (parseExpected(18 /* OpenBraceToken */)) {
24372                 // ClassTail[Yield,Await] : (Modified) See 14.5
24373                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24374                 node.members = parseClassMembers();
24375                 parseExpected(19 /* CloseBraceToken */);
24376             }
24377             else {
24378                 node.members = createMissingList();
24379             }
24380             return finishNode(node);
24381         }
24382         function parseNameOfClassDeclarationOrExpression() {
24383             // implements is a future reserved word so
24384             // 'class implements' might mean either
24385             // - class expression with omitted name, 'implements' starts heritage clause
24386             // - class with name 'implements'
24387             // 'isImplementsClause' helps to disambiguate between these two cases
24388             return isIdentifier() && !isImplementsClause()
24389                 ? parseIdentifier()
24390                 : undefined;
24391         }
24392         function isImplementsClause() {
24393             return token() === 113 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
24394         }
24395         function parseHeritageClauses() {
24396             // ClassTail[Yield,Await] : (Modified) See 14.5
24397             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
24398             if (isHeritageClause()) {
24399                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
24400             }
24401             return undefined;
24402         }
24403         function parseHeritageClause() {
24404             var tok = token();
24405             ts.Debug.assert(tok === 90 /* ExtendsKeyword */ || tok === 113 /* ImplementsKeyword */); // isListElement() should ensure this.
24406             var node = createNode(279 /* HeritageClause */);
24407             node.token = tok;
24408             nextToken();
24409             node.types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
24410             return finishNode(node);
24411         }
24412         function parseExpressionWithTypeArguments() {
24413             var node = createNode(216 /* ExpressionWithTypeArguments */);
24414             node.expression = parseLeftHandSideExpressionOrHigher();
24415             node.typeArguments = tryParseTypeArguments();
24416             return finishNode(node);
24417         }
24418         function tryParseTypeArguments() {
24419             return token() === 29 /* LessThanToken */ ?
24420                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
24421         }
24422         function isHeritageClause() {
24423             return token() === 90 /* ExtendsKeyword */ || token() === 113 /* ImplementsKeyword */;
24424         }
24425         function parseClassMembers() {
24426             return parseList(5 /* ClassMembers */, parseClassElement);
24427         }
24428         function parseInterfaceDeclaration(node) {
24429             node.kind = 246 /* InterfaceDeclaration */;
24430             parseExpected(114 /* InterfaceKeyword */);
24431             node.name = parseIdentifier();
24432             node.typeParameters = parseTypeParameters();
24433             node.heritageClauses = parseHeritageClauses();
24434             node.members = parseObjectTypeMembers();
24435             return finishNode(node);
24436         }
24437         function parseTypeAliasDeclaration(node) {
24438             node.kind = 247 /* TypeAliasDeclaration */;
24439             parseExpected(145 /* TypeKeyword */);
24440             node.name = parseIdentifier();
24441             node.typeParameters = parseTypeParameters();
24442             parseExpected(62 /* EqualsToken */);
24443             node.type = parseType();
24444             parseSemicolon();
24445             return finishNode(node);
24446         }
24447         // In an ambient declaration, the grammar only allows integer literals as initializers.
24448         // In a non-ambient declaration, the grammar allows uninitialized members only in a
24449         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
24450         // or any time an integer literal initializer is encountered.
24451         function parseEnumMember() {
24452             var node = createNodeWithJSDoc(284 /* EnumMember */);
24453             node.name = parsePropertyName();
24454             node.initializer = allowInAnd(parseInitializer);
24455             return finishNode(node);
24456         }
24457         function parseEnumDeclaration(node) {
24458             node.kind = 248 /* EnumDeclaration */;
24459             parseExpected(88 /* EnumKeyword */);
24460             node.name = parseIdentifier();
24461             if (parseExpected(18 /* OpenBraceToken */)) {
24462                 node.members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
24463                 parseExpected(19 /* CloseBraceToken */);
24464             }
24465             else {
24466                 node.members = createMissingList();
24467             }
24468             return finishNode(node);
24469         }
24470         function parseModuleBlock() {
24471             var node = createNode(250 /* ModuleBlock */);
24472             if (parseExpected(18 /* OpenBraceToken */)) {
24473                 node.statements = parseList(1 /* BlockStatements */, parseStatement);
24474                 parseExpected(19 /* CloseBraceToken */);
24475             }
24476             else {
24477                 node.statements = createMissingList();
24478             }
24479             return finishNode(node);
24480         }
24481         function parseModuleOrNamespaceDeclaration(node, flags) {
24482             node.kind = 249 /* ModuleDeclaration */;
24483             // If we are parsing a dotted namespace name, we want to
24484             // propagate the 'Namespace' flag across the names if set.
24485             var namespaceFlag = flags & 16 /* Namespace */;
24486             node.flags |= flags;
24487             node.name = parseIdentifier();
24488             node.body = parseOptional(24 /* DotToken */)
24489                 ? parseModuleOrNamespaceDeclaration(createNode(0 /* Unknown */), 4 /* NestedNamespace */ | namespaceFlag)
24490                 : parseModuleBlock();
24491             return finishNode(node);
24492         }
24493         function parseAmbientExternalModuleDeclaration(node) {
24494             node.kind = 249 /* ModuleDeclaration */;
24495             if (token() === 150 /* GlobalKeyword */) {
24496                 // parse 'global' as name of global scope augmentation
24497                 node.name = parseIdentifier();
24498                 node.flags |= 1024 /* GlobalAugmentation */;
24499             }
24500             else {
24501                 node.name = parseLiteralNode();
24502                 node.name.text = internIdentifier(node.name.text);
24503             }
24504             if (token() === 18 /* OpenBraceToken */) {
24505                 node.body = parseModuleBlock();
24506             }
24507             else {
24508                 parseSemicolon();
24509             }
24510             return finishNode(node);
24511         }
24512         function parseModuleDeclaration(node) {
24513             var flags = 0;
24514             if (token() === 150 /* GlobalKeyword */) {
24515                 // global augmentation
24516                 return parseAmbientExternalModuleDeclaration(node);
24517             }
24518             else if (parseOptional(136 /* NamespaceKeyword */)) {
24519                 flags |= 16 /* Namespace */;
24520             }
24521             else {
24522                 parseExpected(135 /* ModuleKeyword */);
24523                 if (token() === 10 /* StringLiteral */) {
24524                     return parseAmbientExternalModuleDeclaration(node);
24525                 }
24526             }
24527             return parseModuleOrNamespaceDeclaration(node, flags);
24528         }
24529         function isExternalModuleReference() {
24530             return token() === 139 /* RequireKeyword */ &&
24531                 lookAhead(nextTokenIsOpenParen);
24532         }
24533         function nextTokenIsOpenParen() {
24534             return nextToken() === 20 /* OpenParenToken */;
24535         }
24536         function nextTokenIsSlash() {
24537             return nextToken() === 43 /* SlashToken */;
24538         }
24539         function parseNamespaceExportDeclaration(node) {
24540             node.kind = 252 /* NamespaceExportDeclaration */;
24541             parseExpected(123 /* AsKeyword */);
24542             parseExpected(136 /* NamespaceKeyword */);
24543             node.name = parseIdentifier();
24544             parseSemicolon();
24545             return finishNode(node);
24546         }
24547         function parseImportDeclarationOrImportEqualsDeclaration(node) {
24548             parseExpected(96 /* ImportKeyword */);
24549             var afterImportPos = scanner.getStartPos();
24550             var identifier;
24551             if (isIdentifier()) {
24552                 identifier = parseIdentifier();
24553             }
24554             var isTypeOnly = false;
24555             if (token() !== 149 /* FromKeyword */ &&
24556                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
24557                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
24558                 isTypeOnly = true;
24559                 identifier = isIdentifier() ? parseIdentifier() : undefined;
24560             }
24561             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
24562                 return parseImportEqualsDeclaration(node, identifier, isTypeOnly);
24563             }
24564             // Import statement
24565             node.kind = 254 /* ImportDeclaration */;
24566             // ImportDeclaration:
24567             //  import ImportClause from ModuleSpecifier ;
24568             //  import ModuleSpecifier;
24569             if (identifier || // import id
24570                 token() === 41 /* AsteriskToken */ || // import *
24571                 token() === 18 /* OpenBraceToken */ // import {
24572             ) {
24573                 node.importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
24574                 parseExpected(149 /* FromKeyword */);
24575             }
24576             node.moduleSpecifier = parseModuleSpecifier();
24577             parseSemicolon();
24578             return finishNode(node);
24579         }
24580         function tokenAfterImportDefinitelyProducesImportDeclaration() {
24581             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
24582         }
24583         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
24584             // In `import id ___`, the current token decides whether to produce
24585             // an ImportDeclaration or ImportEqualsDeclaration.
24586             return token() === 27 /* CommaToken */ || token() === 149 /* FromKeyword */;
24587         }
24588         function parseImportEqualsDeclaration(node, identifier, isTypeOnly) {
24589             node.kind = 253 /* ImportEqualsDeclaration */;
24590             node.name = identifier;
24591             parseExpected(62 /* EqualsToken */);
24592             node.moduleReference = parseModuleReference();
24593             parseSemicolon();
24594             var finished = finishNode(node);
24595             if (isTypeOnly) {
24596                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
24597             }
24598             return finished;
24599         }
24600         function parseImportClause(identifier, fullStart, isTypeOnly) {
24601             // ImportClause:
24602             //  ImportedDefaultBinding
24603             //  NameSpaceImport
24604             //  NamedImports
24605             //  ImportedDefaultBinding, NameSpaceImport
24606             //  ImportedDefaultBinding, NamedImports
24607             var importClause = createNode(255 /* ImportClause */, fullStart);
24608             importClause.isTypeOnly = isTypeOnly;
24609             if (identifier) {
24610                 // ImportedDefaultBinding:
24611                 //  ImportedBinding
24612                 importClause.name = identifier;
24613             }
24614             // If there was no default import or if there is comma token after default import
24615             // parse namespace or named imports
24616             if (!importClause.name ||
24617                 parseOptional(27 /* CommaToken */)) {
24618                 importClause.namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(257 /* NamedImports */);
24619             }
24620             return finishNode(importClause);
24621         }
24622         function parseModuleReference() {
24623             return isExternalModuleReference()
24624                 ? parseExternalModuleReference()
24625                 : parseEntityName(/*allowReservedWords*/ false);
24626         }
24627         function parseExternalModuleReference() {
24628             var node = createNode(265 /* ExternalModuleReference */);
24629             parseExpected(139 /* RequireKeyword */);
24630             parseExpected(20 /* OpenParenToken */);
24631             node.expression = parseModuleSpecifier();
24632             parseExpected(21 /* CloseParenToken */);
24633             return finishNode(node);
24634         }
24635         function parseModuleSpecifier() {
24636             if (token() === 10 /* StringLiteral */) {
24637                 var result = parseLiteralNode();
24638                 result.text = internIdentifier(result.text);
24639                 return result;
24640             }
24641             else {
24642                 // We allow arbitrary expressions here, even though the grammar only allows string
24643                 // literals.  We check to ensure that it is only a string literal later in the grammar
24644                 // check pass.
24645                 return parseExpression();
24646             }
24647         }
24648         function parseNamespaceImport() {
24649             // NameSpaceImport:
24650             //  * as ImportedBinding
24651             var namespaceImport = createNode(256 /* NamespaceImport */);
24652             parseExpected(41 /* AsteriskToken */);
24653             parseExpected(123 /* AsKeyword */);
24654             namespaceImport.name = parseIdentifier();
24655             return finishNode(namespaceImport);
24656         }
24657         function parseNamedImportsOrExports(kind) {
24658             var node = createNode(kind);
24659             // NamedImports:
24660             //  { }
24661             //  { ImportsList }
24662             //  { ImportsList, }
24663             // ImportsList:
24664             //  ImportSpecifier
24665             //  ImportsList, ImportSpecifier
24666             node.elements = parseBracketedList(23 /* ImportOrExportSpecifiers */, kind === 257 /* NamedImports */ ? parseImportSpecifier : parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */);
24667             return finishNode(node);
24668         }
24669         function parseExportSpecifier() {
24670             return parseImportOrExportSpecifier(263 /* ExportSpecifier */);
24671         }
24672         function parseImportSpecifier() {
24673             return parseImportOrExportSpecifier(258 /* ImportSpecifier */);
24674         }
24675         function parseImportOrExportSpecifier(kind) {
24676             var node = createNode(kind);
24677             // ImportSpecifier:
24678             //   BindingIdentifier
24679             //   IdentifierName as BindingIdentifier
24680             // ExportSpecifier:
24681             //   IdentifierName
24682             //   IdentifierName as IdentifierName
24683             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24684             var checkIdentifierStart = scanner.getTokenPos();
24685             var checkIdentifierEnd = scanner.getTextPos();
24686             var identifierName = parseIdentifierName();
24687             if (token() === 123 /* AsKeyword */) {
24688                 node.propertyName = identifierName;
24689                 parseExpected(123 /* AsKeyword */);
24690                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
24691                 checkIdentifierStart = scanner.getTokenPos();
24692                 checkIdentifierEnd = scanner.getTextPos();
24693                 node.name = parseIdentifierName();
24694             }
24695             else {
24696                 node.name = identifierName;
24697             }
24698             if (kind === 258 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
24699                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
24700             }
24701             return finishNode(node);
24702         }
24703         function parseNamespaceExport(pos) {
24704             var node = createNode(262 /* NamespaceExport */, pos);
24705             node.name = parseIdentifier();
24706             return finishNode(node);
24707         }
24708         function parseExportDeclaration(node) {
24709             node.kind = 260 /* ExportDeclaration */;
24710             node.isTypeOnly = parseOptional(145 /* TypeKeyword */);
24711             var namespaceExportPos = scanner.getStartPos();
24712             if (parseOptional(41 /* AsteriskToken */)) {
24713                 if (parseOptional(123 /* AsKeyword */)) {
24714                     node.exportClause = parseNamespaceExport(namespaceExportPos);
24715                 }
24716                 parseExpected(149 /* FromKeyword */);
24717                 node.moduleSpecifier = parseModuleSpecifier();
24718             }
24719             else {
24720                 node.exportClause = parseNamedImportsOrExports(261 /* NamedExports */);
24721                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
24722                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
24723                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
24724                 if (token() === 149 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
24725                     parseExpected(149 /* FromKeyword */);
24726                     node.moduleSpecifier = parseModuleSpecifier();
24727                 }
24728             }
24729             parseSemicolon();
24730             return finishNode(node);
24731         }
24732         function parseExportAssignment(node) {
24733             node.kind = 259 /* ExportAssignment */;
24734             if (parseOptional(62 /* EqualsToken */)) {
24735                 node.isExportEquals = true;
24736             }
24737             else {
24738                 parseExpected(84 /* DefaultKeyword */);
24739             }
24740             node.expression = parseAssignmentExpressionOrHigher();
24741             parseSemicolon();
24742             return finishNode(node);
24743         }
24744         function setExternalModuleIndicator(sourceFile) {
24745             // Try to use the first top-level import/export when available, then
24746             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
24747             sourceFile.externalModuleIndicator =
24748                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
24749                     getImportMetaIfNecessary(sourceFile);
24750         }
24751         function isAnExternalModuleIndicatorNode(node) {
24752             return hasModifierOfKind(node, 89 /* ExportKeyword */)
24753                 || node.kind === 253 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 265 /* ExternalModuleReference */
24754                 || node.kind === 254 /* ImportDeclaration */
24755                 || node.kind === 259 /* ExportAssignment */
24756                 || node.kind === 260 /* ExportDeclaration */ ? node : undefined;
24757         }
24758         function getImportMetaIfNecessary(sourceFile) {
24759             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
24760                 walkTreeForExternalModuleIndicators(sourceFile) :
24761                 undefined;
24762         }
24763         function walkTreeForExternalModuleIndicators(node) {
24764             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
24765         }
24766         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
24767         function hasModifierOfKind(node, kind) {
24768             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
24769         }
24770         function isImportMeta(node) {
24771             return ts.isMetaProperty(node) && node.keywordToken === 96 /* ImportKeyword */ && node.name.escapedText === "meta";
24772         }
24773         var ParsingContext;
24774         (function (ParsingContext) {
24775             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
24776             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
24777             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
24778             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
24779             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
24780             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
24781             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
24782             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
24783             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
24784             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
24785             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
24786             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
24787             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
24788             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
24789             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
24790             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
24791             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
24792             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
24793             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
24794             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
24795             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
24796             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
24797             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
24798             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
24799             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
24800         })(ParsingContext || (ParsingContext = {}));
24801         var Tristate;
24802         (function (Tristate) {
24803             Tristate[Tristate["False"] = 0] = "False";
24804             Tristate[Tristate["True"] = 1] = "True";
24805             Tristate[Tristate["Unknown"] = 2] = "Unknown";
24806         })(Tristate || (Tristate = {}));
24807         var JSDocParser;
24808         (function (JSDocParser) {
24809             function parseJSDocTypeExpressionForTests(content, start, length) {
24810                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24811                 sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false);
24812                 scanner.setText(content, start, length);
24813                 currentToken = scanner.scan();
24814                 var jsDocTypeExpression = parseJSDocTypeExpression();
24815                 var diagnostics = parseDiagnostics;
24816                 clearState();
24817                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
24818             }
24819             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
24820             // Parses out a JSDoc type expression.
24821             function parseJSDocTypeExpression(mayOmitBraces) {
24822                 var result = createNode(294 /* JSDocTypeExpression */);
24823                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
24824                 result.type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
24825                 if (!mayOmitBraces || hasBrace) {
24826                     parseExpectedJSDoc(19 /* CloseBraceToken */);
24827                 }
24828                 fixupParentReferences(result);
24829                 return finishNode(result);
24830             }
24831             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
24832             function parseIsolatedJSDocComment(content, start, length) {
24833                 initializeState(content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
24834                 sourceFile = { languageVariant: 0 /* Standard */, text: content };
24835                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24836                 var diagnostics = parseDiagnostics;
24837                 clearState();
24838                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
24839             }
24840             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
24841             function parseJSDocComment(parent, start, length) {
24842                 var _a;
24843                 var saveToken = currentToken;
24844                 var saveParseDiagnosticsLength = parseDiagnostics.length;
24845                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
24846                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
24847                 if (comment) {
24848                     comment.parent = parent;
24849                 }
24850                 if (contextFlags & 131072 /* JavaScriptFile */) {
24851                     if (!sourceFile.jsDocDiagnostics) {
24852                         sourceFile.jsDocDiagnostics = [];
24853                     }
24854                     (_a = sourceFile.jsDocDiagnostics).push.apply(_a, parseDiagnostics);
24855                 }
24856                 currentToken = saveToken;
24857                 parseDiagnostics.length = saveParseDiagnosticsLength;
24858                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
24859                 return comment;
24860             }
24861             JSDocParser.parseJSDocComment = parseJSDocComment;
24862             var JSDocState;
24863             (function (JSDocState) {
24864                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
24865                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
24866                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
24867                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
24868             })(JSDocState || (JSDocState = {}));
24869             var PropertyLikeParse;
24870             (function (PropertyLikeParse) {
24871                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
24872                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
24873                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
24874             })(PropertyLikeParse || (PropertyLikeParse = {}));
24875             function parseJSDocCommentWorker(start, length) {
24876                 if (start === void 0) { start = 0; }
24877                 var content = sourceText;
24878                 var end = length === undefined ? content.length : start + length;
24879                 length = end - start;
24880                 ts.Debug.assert(start >= 0);
24881                 ts.Debug.assert(start <= end);
24882                 ts.Debug.assert(end <= content.length);
24883                 // Check for /** (JSDoc opening part)
24884                 if (!isJSDocLikeText(content, start)) {
24885                     return undefined;
24886                 }
24887                 var tags;
24888                 var tagsPos;
24889                 var tagsEnd;
24890                 var comments = [];
24891                 // + 3 for leading /**, - 5 in total for /** */
24892                 return scanner.scanRange(start + 3, length - 5, function () {
24893                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
24894                     // This is so that /** * @type */ doesn't parse.
24895                     var state = 1 /* SawAsterisk */;
24896                     var margin;
24897                     // + 4 for leading '/** '
24898                     var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4;
24899                     function pushComment(text) {
24900                         if (!margin) {
24901                             margin = indent;
24902                         }
24903                         comments.push(text);
24904                         indent += text.length;
24905                     }
24906                     nextTokenJSDoc();
24907                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
24908                         ;
24909                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
24910                         state = 0 /* BeginningOfLine */;
24911                         indent = 0;
24912                     }
24913                     loop: while (true) {
24914                         switch (token()) {
24915                             case 59 /* AtToken */:
24916                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
24917                                     removeTrailingWhitespace(comments);
24918                                     addTag(parseTag(indent));
24919                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
24920                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
24921                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
24922                                     state = 0 /* BeginningOfLine */;
24923                                     margin = undefined;
24924                                 }
24925                                 else {
24926                                     pushComment(scanner.getTokenText());
24927                                 }
24928                                 break;
24929                             case 4 /* NewLineTrivia */:
24930                                 comments.push(scanner.getTokenText());
24931                                 state = 0 /* BeginningOfLine */;
24932                                 indent = 0;
24933                                 break;
24934                             case 41 /* AsteriskToken */:
24935                                 var asterisk = scanner.getTokenText();
24936                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
24937                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
24938                                     state = 2 /* SavingComments */;
24939                                     pushComment(asterisk);
24940                                 }
24941                                 else {
24942                                     // Ignore the first asterisk on a line
24943                                     state = 1 /* SawAsterisk */;
24944                                     indent += asterisk.length;
24945                                 }
24946                                 break;
24947                             case 5 /* WhitespaceTrivia */:
24948                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
24949                                 var whitespace = scanner.getTokenText();
24950                                 if (state === 2 /* SavingComments */) {
24951                                     comments.push(whitespace);
24952                                 }
24953                                 else if (margin !== undefined && indent + whitespace.length > margin) {
24954                                     comments.push(whitespace.slice(margin - indent - 1));
24955                                 }
24956                                 indent += whitespace.length;
24957                                 break;
24958                             case 1 /* EndOfFileToken */:
24959                                 break loop;
24960                             default:
24961                                 // Anything else is doc comment text. We just save it. Because it
24962                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
24963                                 // line break.
24964                                 state = 2 /* SavingComments */;
24965                                 pushComment(scanner.getTokenText());
24966                                 break;
24967                         }
24968                         nextTokenJSDoc();
24969                     }
24970                     removeLeadingNewlines(comments);
24971                     removeTrailingWhitespace(comments);
24972                     return createJSDocComment();
24973                 });
24974                 function removeLeadingNewlines(comments) {
24975                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
24976                         comments.shift();
24977                     }
24978                 }
24979                 function removeTrailingWhitespace(comments) {
24980                     while (comments.length && comments[comments.length - 1].trim() === "") {
24981                         comments.pop();
24982                     }
24983                 }
24984                 function createJSDocComment() {
24985                     var result = createNode(303 /* JSDocComment */, start);
24986                     result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd);
24987                     result.comment = comments.length ? comments.join("") : undefined;
24988                     return finishNode(result, end);
24989                 }
24990                 function isNextNonwhitespaceTokenEndOfFile() {
24991                     // We must use infinite lookahead, as there could be any number of newlines :(
24992                     while (true) {
24993                         nextTokenJSDoc();
24994                         if (token() === 1 /* EndOfFileToken */) {
24995                             return true;
24996                         }
24997                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
24998                             return false;
24999                         }
25000                     }
25001                 }
25002                 function skipWhitespace() {
25003                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25004                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25005                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25006                         }
25007                     }
25008                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25009                         nextTokenJSDoc();
25010                     }
25011                 }
25012                 function skipWhitespaceOrAsterisk() {
25013                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25014                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
25015                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
25016                         }
25017                     }
25018                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
25019                     var seenLineBreak = false;
25020                     var indentText = "";
25021                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
25022                         indentText += scanner.getTokenText();
25023                         if (token() === 4 /* NewLineTrivia */) {
25024                             precedingLineBreak = true;
25025                             seenLineBreak = true;
25026                             indentText = "";
25027                         }
25028                         else if (token() === 41 /* AsteriskToken */) {
25029                             precedingLineBreak = false;
25030                         }
25031                         nextTokenJSDoc();
25032                     }
25033                     return seenLineBreak ? indentText : "";
25034                 }
25035                 function parseTag(margin) {
25036                     ts.Debug.assert(token() === 59 /* AtToken */);
25037                     var start = scanner.getTokenPos();
25038                     nextTokenJSDoc();
25039                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
25040                     var indentText = skipWhitespaceOrAsterisk();
25041                     var tag;
25042                     switch (tagName.escapedText) {
25043                         case "author":
25044                             tag = parseAuthorTag(start, tagName, margin);
25045                             break;
25046                         case "implements":
25047                             tag = parseImplementsTag(start, tagName);
25048                             break;
25049                         case "augments":
25050                         case "extends":
25051                             tag = parseAugmentsTag(start, tagName);
25052                             break;
25053                         case "class":
25054                         case "constructor":
25055                             tag = parseSimpleTag(start, 310 /* JSDocClassTag */, tagName);
25056                             break;
25057                         case "public":
25058                             tag = parseSimpleTag(start, 311 /* JSDocPublicTag */, tagName);
25059                             break;
25060                         case "private":
25061                             tag = parseSimpleTag(start, 312 /* JSDocPrivateTag */, tagName);
25062                             break;
25063                         case "protected":
25064                             tag = parseSimpleTag(start, 313 /* JSDocProtectedTag */, tagName);
25065                             break;
25066                         case "readonly":
25067                             tag = parseSimpleTag(start, 314 /* JSDocReadonlyTag */, tagName);
25068                             break;
25069                         case "this":
25070                             tag = parseThisTag(start, tagName);
25071                             break;
25072                         case "enum":
25073                             tag = parseEnumTag(start, tagName);
25074                             break;
25075                         case "arg":
25076                         case "argument":
25077                         case "param":
25078                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
25079                         case "return":
25080                         case "returns":
25081                             tag = parseReturnTag(start, tagName);
25082                             break;
25083                         case "template":
25084                             tag = parseTemplateTag(start, tagName);
25085                             break;
25086                         case "type":
25087                             tag = parseTypeTag(start, tagName);
25088                             break;
25089                         case "typedef":
25090                             tag = parseTypedefTag(start, tagName, margin);
25091                             break;
25092                         case "callback":
25093                             tag = parseCallbackTag(start, tagName, margin);
25094                             break;
25095                         default:
25096                             tag = parseUnknownTag(start, tagName);
25097                             break;
25098                     }
25099                     if (!tag.comment) {
25100                         // some tags, like typedef and callback, have already parsed their comments earlier
25101                         if (!indentText) {
25102                             margin += tag.end - tag.pos;
25103                         }
25104                         tag.comment = parseTagComments(margin, indentText.slice(margin));
25105                     }
25106                     return tag;
25107                 }
25108                 function parseTagComments(indent, initialMargin) {
25109                     var comments = [];
25110                     var state = 0 /* BeginningOfLine */;
25111                     var margin;
25112                     function pushComment(text) {
25113                         if (!margin) {
25114                             margin = indent;
25115                         }
25116                         comments.push(text);
25117                         indent += text.length;
25118                     }
25119                     if (initialMargin !== undefined) {
25120                         // jump straight to saving comments if there is some initial indentation
25121                         if (initialMargin !== "") {
25122                             pushComment(initialMargin);
25123                         }
25124                         state = 1 /* SawAsterisk */;
25125                     }
25126                     var tok = token();
25127                     loop: while (true) {
25128                         switch (tok) {
25129                             case 4 /* NewLineTrivia */:
25130                                 if (state >= 1 /* SawAsterisk */) {
25131                                     state = 0 /* BeginningOfLine */;
25132                                     // don't use pushComment here because we want to keep the margin unchanged
25133                                     comments.push(scanner.getTokenText());
25134                                 }
25135                                 indent = 0;
25136                                 break;
25137                             case 59 /* AtToken */:
25138                                 if (state === 3 /* SavingBackticks */) {
25139                                     comments.push(scanner.getTokenText());
25140                                     break;
25141                                 }
25142                                 scanner.setTextPos(scanner.getTextPos() - 1);
25143                             // falls through
25144                             case 1 /* EndOfFileToken */:
25145                                 // Done
25146                                 break loop;
25147                             case 5 /* WhitespaceTrivia */:
25148                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
25149                                     pushComment(scanner.getTokenText());
25150                                 }
25151                                 else {
25152                                     var whitespace = scanner.getTokenText();
25153                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
25154                                     if (margin !== undefined && indent + whitespace.length > margin) {
25155                                         comments.push(whitespace.slice(margin - indent));
25156                                     }
25157                                     indent += whitespace.length;
25158                                 }
25159                                 break;
25160                             case 18 /* OpenBraceToken */:
25161                                 state = 2 /* SavingComments */;
25162                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
25163                                     pushComment(scanner.getTokenText());
25164                                     nextTokenJSDoc();
25165                                     pushComment(scanner.getTokenText());
25166                                     nextTokenJSDoc();
25167                                 }
25168                                 pushComment(scanner.getTokenText());
25169                                 break;
25170                             case 61 /* BacktickToken */:
25171                                 if (state === 3 /* SavingBackticks */) {
25172                                     state = 2 /* SavingComments */;
25173                                 }
25174                                 else {
25175                                     state = 3 /* SavingBackticks */;
25176                                 }
25177                                 pushComment(scanner.getTokenText());
25178                                 break;
25179                             case 41 /* AsteriskToken */:
25180                                 if (state === 0 /* BeginningOfLine */) {
25181                                     // leading asterisks start recording on the *next* (non-whitespace) token
25182                                     state = 1 /* SawAsterisk */;
25183                                     indent += 1;
25184                                     break;
25185                                 }
25186                             // record the * as a comment
25187                             // falls through
25188                             default:
25189                                 if (state !== 3 /* SavingBackticks */) {
25190                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
25191                                 }
25192                                 pushComment(scanner.getTokenText());
25193                                 break;
25194                         }
25195                         tok = nextTokenJSDoc();
25196                     }
25197                     removeLeadingNewlines(comments);
25198                     removeTrailingWhitespace(comments);
25199                     return comments.length === 0 ? undefined : comments.join("");
25200                 }
25201                 function parseUnknownTag(start, tagName) {
25202                     var result = createNode(306 /* JSDocTag */, start);
25203                     result.tagName = tagName;
25204                     return finishNode(result);
25205                 }
25206                 function addTag(tag) {
25207                     if (!tag) {
25208                         return;
25209                     }
25210                     if (!tags) {
25211                         tags = [tag];
25212                         tagsPos = tag.pos;
25213                     }
25214                     else {
25215                         tags.push(tag);
25216                     }
25217                     tagsEnd = tag.end;
25218                 }
25219                 function tryParseTypeExpression() {
25220                     skipWhitespaceOrAsterisk();
25221                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
25222                 }
25223                 function parseBracketNameInPropertyAndParamTag() {
25224                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
25225                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
25226                     if (isBracketed) {
25227                         skipWhitespace();
25228                     }
25229                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
25230                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
25231                     var name = parseJSDocEntityName();
25232                     if (isBackquoted) {
25233                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
25234                     }
25235                     if (isBracketed) {
25236                         skipWhitespace();
25237                         // May have an optional default, e.g. '[foo = 42]'
25238                         if (parseOptionalToken(62 /* EqualsToken */)) {
25239                             parseExpression();
25240                         }
25241                         parseExpected(23 /* CloseBracketToken */);
25242                     }
25243                     return { name: name, isBracketed: isBracketed };
25244                 }
25245                 function isObjectOrObjectArrayTypeReference(node) {
25246                     switch (node.kind) {
25247                         case 141 /* ObjectKeyword */:
25248                             return true;
25249                         case 174 /* ArrayType */:
25250                             return isObjectOrObjectArrayTypeReference(node.elementType);
25251                         default:
25252                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
25253                     }
25254                 }
25255                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
25256                     var typeExpression = tryParseTypeExpression();
25257                     var isNameFirst = !typeExpression;
25258                     skipWhitespaceOrAsterisk();
25259                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
25260                     skipWhitespace();
25261                     if (isNameFirst) {
25262                         typeExpression = tryParseTypeExpression();
25263                     }
25264                     var result = target === 1 /* Property */ ?
25265                         createNode(323 /* JSDocPropertyTag */, start) :
25266                         createNode(317 /* JSDocParameterTag */, start);
25267                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
25268                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
25269                     if (nestedTypeLiteral) {
25270                         typeExpression = nestedTypeLiteral;
25271                         isNameFirst = true;
25272                     }
25273                     result.tagName = tagName;
25274                     result.typeExpression = typeExpression;
25275                     result.name = name;
25276                     result.isNameFirst = isNameFirst;
25277                     result.isBracketed = isBracketed;
25278                     result.comment = comment;
25279                     return finishNode(result);
25280                 }
25281                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
25282                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25283                         var typeLiteralExpression = createNode(294 /* JSDocTypeExpression */, scanner.getTokenPos());
25284                         var child = void 0;
25285                         var jsdocTypeLiteral = void 0;
25286                         var start_3 = scanner.getStartPos();
25287                         var children = void 0;
25288                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
25289                             if (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) {
25290                                 children = ts.append(children, child);
25291                             }
25292                         }
25293                         if (children) {
25294                             jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start_3);
25295                             jsdocTypeLiteral.jsDocPropertyTags = children;
25296                             if (typeExpression.type.kind === 174 /* ArrayType */) {
25297                                 jsdocTypeLiteral.isArrayType = true;
25298                             }
25299                             typeLiteralExpression.type = finishNode(jsdocTypeLiteral);
25300                             return finishNode(typeLiteralExpression);
25301                         }
25302                     }
25303                 }
25304                 function parseReturnTag(start, tagName) {
25305                     if (ts.some(tags, ts.isJSDocReturnTag)) {
25306                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25307                     }
25308                     var result = createNode(318 /* JSDocReturnTag */, start);
25309                     result.tagName = tagName;
25310                     result.typeExpression = tryParseTypeExpression();
25311                     return finishNode(result);
25312                 }
25313                 function parseTypeTag(start, tagName) {
25314                     if (ts.some(tags, ts.isJSDocTypeTag)) {
25315                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
25316                     }
25317                     var result = createNode(320 /* JSDocTypeTag */, start);
25318                     result.tagName = tagName;
25319                     result.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25320                     return finishNode(result);
25321                 }
25322                 function parseAuthorTag(start, tagName, indent) {
25323                     var result = createNode(309 /* JSDocAuthorTag */, start);
25324                     result.tagName = tagName;
25325                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
25326                     if (!authorInfoWithEmail) {
25327                         return finishNode(result);
25328                     }
25329                     result.comment = authorInfoWithEmail;
25330                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
25331                         var comment = parseTagComments(indent);
25332                         if (comment) {
25333                             result.comment += comment;
25334                         }
25335                     }
25336                     return finishNode(result);
25337                 }
25338                 function tryParseAuthorNameAndEmail() {
25339                     var comments = [];
25340                     var seenLessThan = false;
25341                     var seenGreaterThan = false;
25342                     var token = scanner.getToken();
25343                     loop: while (true) {
25344                         switch (token) {
25345                             case 75 /* Identifier */:
25346                             case 5 /* WhitespaceTrivia */:
25347                             case 24 /* DotToken */:
25348                             case 59 /* AtToken */:
25349                                 comments.push(scanner.getTokenText());
25350                                 break;
25351                             case 29 /* LessThanToken */:
25352                                 if (seenLessThan || seenGreaterThan) {
25353                                     return;
25354                                 }
25355                                 seenLessThan = true;
25356                                 comments.push(scanner.getTokenText());
25357                                 break;
25358                             case 31 /* GreaterThanToken */:
25359                                 if (!seenLessThan || seenGreaterThan) {
25360                                     return;
25361                                 }
25362                                 seenGreaterThan = true;
25363                                 comments.push(scanner.getTokenText());
25364                                 scanner.setTextPos(scanner.getTokenPos() + 1);
25365                                 break loop;
25366                             case 4 /* NewLineTrivia */:
25367                             case 1 /* EndOfFileToken */:
25368                                 break loop;
25369                         }
25370                         token = nextTokenJSDoc();
25371                     }
25372                     if (seenLessThan && seenGreaterThan) {
25373                         return comments.length === 0 ? undefined : comments.join("");
25374                     }
25375                 }
25376                 function parseImplementsTag(start, tagName) {
25377                     var result = createNode(308 /* JSDocImplementsTag */, start);
25378                     result.tagName = tagName;
25379                     result.class = parseExpressionWithTypeArgumentsForAugments();
25380                     return finishNode(result);
25381                 }
25382                 function parseAugmentsTag(start, tagName) {
25383                     var result = createNode(307 /* JSDocAugmentsTag */, start);
25384                     result.tagName = tagName;
25385                     result.class = parseExpressionWithTypeArgumentsForAugments();
25386                     return finishNode(result);
25387                 }
25388                 function parseExpressionWithTypeArgumentsForAugments() {
25389                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
25390                     var node = createNode(216 /* ExpressionWithTypeArguments */);
25391                     node.expression = parsePropertyAccessEntityNameExpression();
25392                     node.typeArguments = tryParseTypeArguments();
25393                     var res = finishNode(node);
25394                     if (usedBrace) {
25395                         parseExpected(19 /* CloseBraceToken */);
25396                     }
25397                     return res;
25398                 }
25399                 function parsePropertyAccessEntityNameExpression() {
25400                     var node = parseJSDocIdentifierName();
25401                     while (parseOptional(24 /* DotToken */)) {
25402                         var prop = createNode(194 /* PropertyAccessExpression */, node.pos);
25403                         prop.expression = node;
25404                         prop.name = parseJSDocIdentifierName();
25405                         node = finishNode(prop);
25406                     }
25407                     return node;
25408                 }
25409                 function parseSimpleTag(start, kind, tagName) {
25410                     var tag = createNode(kind, start);
25411                     tag.tagName = tagName;
25412                     return finishNode(tag);
25413                 }
25414                 function parseThisTag(start, tagName) {
25415                     var tag = createNode(319 /* JSDocThisTag */, start);
25416                     tag.tagName = tagName;
25417                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25418                     skipWhitespace();
25419                     return finishNode(tag);
25420                 }
25421                 function parseEnumTag(start, tagName) {
25422                     var tag = createNode(316 /* JSDocEnumTag */, start);
25423                     tag.tagName = tagName;
25424                     tag.typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
25425                     skipWhitespace();
25426                     return finishNode(tag);
25427                 }
25428                 function parseTypedefTag(start, tagName, indent) {
25429                     var typeExpression = tryParseTypeExpression();
25430                     skipWhitespaceOrAsterisk();
25431                     var typedefTag = createNode(322 /* JSDocTypedefTag */, start);
25432                     typedefTag.tagName = tagName;
25433                     typedefTag.fullName = parseJSDocTypeNameWithNamespace();
25434                     typedefTag.name = getJSDocTypeAliasName(typedefTag.fullName);
25435                     skipWhitespace();
25436                     typedefTag.comment = parseTagComments(indent);
25437                     typedefTag.typeExpression = typeExpression;
25438                     var end;
25439                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
25440                         var child = void 0;
25441                         var jsdocTypeLiteral = void 0;
25442                         var childTypeTag = void 0;
25443                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
25444                             if (!jsdocTypeLiteral) {
25445                                 jsdocTypeLiteral = createNode(304 /* JSDocTypeLiteral */, start);
25446                             }
25447                             if (child.kind === 320 /* JSDocTypeTag */) {
25448                                 if (childTypeTag) {
25449                                     break;
25450                                 }
25451                                 else {
25452                                     childTypeTag = child;
25453                                 }
25454                             }
25455                             else {
25456                                 jsdocTypeLiteral.jsDocPropertyTags = ts.append(jsdocTypeLiteral.jsDocPropertyTags, child);
25457                             }
25458                         }
25459                         if (jsdocTypeLiteral) {
25460                             if (typeExpression && typeExpression.type.kind === 174 /* ArrayType */) {
25461                                 jsdocTypeLiteral.isArrayType = true;
25462                             }
25463                             typedefTag.typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
25464                                 childTypeTag.typeExpression :
25465                                 finishNode(jsdocTypeLiteral);
25466                             end = typedefTag.typeExpression.end;
25467                         }
25468                     }
25469                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
25470                     return finishNode(typedefTag, end || typedefTag.comment !== undefined ? scanner.getStartPos() : (typedefTag.fullName || typedefTag.typeExpression || typedefTag.tagName).end);
25471                 }
25472                 function parseJSDocTypeNameWithNamespace(nested) {
25473                     var pos = scanner.getTokenPos();
25474                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25475                         return undefined;
25476                     }
25477                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
25478                     if (parseOptional(24 /* DotToken */)) {
25479                         var jsDocNamespaceNode = createNode(249 /* ModuleDeclaration */, pos);
25480                         if (nested) {
25481                             jsDocNamespaceNode.flags |= 4 /* NestedNamespace */;
25482                         }
25483                         jsDocNamespaceNode.name = typeNameOrNamespaceName;
25484                         jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
25485                         return finishNode(jsDocNamespaceNode);
25486                     }
25487                     if (nested) {
25488                         typeNameOrNamespaceName.isInJSDocNamespace = true;
25489                     }
25490                     return typeNameOrNamespaceName;
25491                 }
25492                 function parseCallbackTag(start, tagName, indent) {
25493                     var callbackTag = createNode(315 /* JSDocCallbackTag */, start);
25494                     callbackTag.tagName = tagName;
25495                     callbackTag.fullName = parseJSDocTypeNameWithNamespace();
25496                     callbackTag.name = getJSDocTypeAliasName(callbackTag.fullName);
25497                     skipWhitespace();
25498                     callbackTag.comment = parseTagComments(indent);
25499                     var child;
25500                     var jsdocSignature = createNode(305 /* JSDocSignature */, start);
25501                     jsdocSignature.parameters = [];
25502                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
25503                         jsdocSignature.parameters = ts.append(jsdocSignature.parameters, child);
25504                     }
25505                     var returnTag = tryParse(function () {
25506                         if (parseOptionalJsdoc(59 /* AtToken */)) {
25507                             var tag = parseTag(indent);
25508                             if (tag && tag.kind === 318 /* JSDocReturnTag */) {
25509                                 return tag;
25510                             }
25511                         }
25512                     });
25513                     if (returnTag) {
25514                         jsdocSignature.type = returnTag;
25515                     }
25516                     callbackTag.typeExpression = finishNode(jsdocSignature);
25517                     return finishNode(callbackTag);
25518                 }
25519                 function getJSDocTypeAliasName(fullName) {
25520                     if (fullName) {
25521                         var rightNode = fullName;
25522                         while (true) {
25523                             if (ts.isIdentifier(rightNode) || !rightNode.body) {
25524                                 return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
25525                             }
25526                             rightNode = rightNode.body;
25527                         }
25528                     }
25529                 }
25530                 function escapedTextsEqual(a, b) {
25531                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
25532                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
25533                             a = a.left;
25534                             b = b.left;
25535                         }
25536                         else {
25537                             return false;
25538                         }
25539                     }
25540                     return a.escapedText === b.escapedText;
25541                 }
25542                 function parseChildPropertyTag(indent) {
25543                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
25544                 }
25545                 function parseChildParameterOrPropertyTag(target, indent, name) {
25546                     var canParseTag = true;
25547                     var seenAsterisk = false;
25548                     while (true) {
25549                         switch (nextTokenJSDoc()) {
25550                             case 59 /* AtToken */:
25551                                 if (canParseTag) {
25552                                     var child = tryParseChildTag(target, indent);
25553                                     if (child && (child.kind === 317 /* JSDocParameterTag */ || child.kind === 323 /* JSDocPropertyTag */) &&
25554                                         target !== 4 /* CallbackParameter */ &&
25555                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
25556                                         return false;
25557                                     }
25558                                     return child;
25559                                 }
25560                                 seenAsterisk = false;
25561                                 break;
25562                             case 4 /* NewLineTrivia */:
25563                                 canParseTag = true;
25564                                 seenAsterisk = false;
25565                                 break;
25566                             case 41 /* AsteriskToken */:
25567                                 if (seenAsterisk) {
25568                                     canParseTag = false;
25569                                 }
25570                                 seenAsterisk = true;
25571                                 break;
25572                             case 75 /* Identifier */:
25573                                 canParseTag = false;
25574                                 break;
25575                             case 1 /* EndOfFileToken */:
25576                                 return false;
25577                         }
25578                     }
25579                 }
25580                 function tryParseChildTag(target, indent) {
25581                     ts.Debug.assert(token() === 59 /* AtToken */);
25582                     var start = scanner.getStartPos();
25583                     nextTokenJSDoc();
25584                     var tagName = parseJSDocIdentifierName();
25585                     skipWhitespace();
25586                     var t;
25587                     switch (tagName.escapedText) {
25588                         case "type":
25589                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
25590                         case "prop":
25591                         case "property":
25592                             t = 1 /* Property */;
25593                             break;
25594                         case "arg":
25595                         case "argument":
25596                         case "param":
25597                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
25598                             break;
25599                         default:
25600                             return false;
25601                     }
25602                     if (!(target & t)) {
25603                         return false;
25604                     }
25605                     return parseParameterOrPropertyTag(start, tagName, target, indent);
25606                 }
25607                 function parseTemplateTag(start, tagName) {
25608                     // the template tag looks like '@template {Constraint} T,U,V'
25609                     var constraint;
25610                     if (token() === 18 /* OpenBraceToken */) {
25611                         constraint = parseJSDocTypeExpression();
25612                     }
25613                     var typeParameters = [];
25614                     var typeParametersPos = getNodePos();
25615                     do {
25616                         skipWhitespace();
25617                         var typeParameter = createNode(155 /* TypeParameter */);
25618                         typeParameter.name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
25619                         finishNode(typeParameter);
25620                         skipWhitespaceOrAsterisk();
25621                         typeParameters.push(typeParameter);
25622                     } while (parseOptionalJsdoc(27 /* CommaToken */));
25623                     var result = createNode(321 /* JSDocTemplateTag */, start);
25624                     result.tagName = tagName;
25625                     result.constraint = constraint;
25626                     result.typeParameters = createNodeArray(typeParameters, typeParametersPos);
25627                     finishNode(result);
25628                     return result;
25629                 }
25630                 function parseOptionalJsdoc(t) {
25631                     if (token() === t) {
25632                         nextTokenJSDoc();
25633                         return true;
25634                     }
25635                     return false;
25636                 }
25637                 function parseJSDocEntityName() {
25638                     var entity = parseJSDocIdentifierName();
25639                     if (parseOptional(22 /* OpenBracketToken */)) {
25640                         parseExpected(23 /* CloseBracketToken */);
25641                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
25642                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
25643                         // but it's not worth it to enforce that restriction.
25644                     }
25645                     while (parseOptional(24 /* DotToken */)) {
25646                         var name = parseJSDocIdentifierName();
25647                         if (parseOptional(22 /* OpenBracketToken */)) {
25648                             parseExpected(23 /* CloseBracketToken */);
25649                         }
25650                         entity = createQualifiedName(entity, name);
25651                     }
25652                     return entity;
25653                 }
25654                 function parseJSDocIdentifierName(message) {
25655                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
25656                         return createMissingNode(75 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
25657                     }
25658                     identifierCount++;
25659                     var pos = scanner.getTokenPos();
25660                     var end = scanner.getTextPos();
25661                     var result = createNode(75 /* Identifier */, pos);
25662                     if (token() !== 75 /* Identifier */) {
25663                         result.originalKeywordKind = token();
25664                     }
25665                     result.escapedText = ts.escapeLeadingUnderscores(internIdentifier(scanner.getTokenValue()));
25666                     finishNode(result, end);
25667                     nextTokenJSDoc();
25668                     return result;
25669                 }
25670             }
25671         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
25672     })(Parser || (Parser = {}));
25673     var IncrementalParser;
25674     (function (IncrementalParser) {
25675         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
25676             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
25677             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
25678             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
25679                 // if the text didn't change, then we can just return our current source file as-is.
25680                 return sourceFile;
25681             }
25682             if (sourceFile.statements.length === 0) {
25683                 // If we don't have any statements in the current source file, then there's no real
25684                 // way to incrementally parse.  So just do a full parse instead.
25685                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
25686             }
25687             // Make sure we're not trying to incrementally update a source file more than once.  Once
25688             // we do an update the original source file is considered unusable from that point onwards.
25689             //
25690             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
25691             // tree and give them new positions and parents.  From that point on, trusting the old
25692             // tree at all is not possible as far too much of it may violate invariants.
25693             var incrementalSourceFile = sourceFile;
25694             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
25695             incrementalSourceFile.hasBeenIncrementallyParsed = true;
25696             var oldText = sourceFile.text;
25697             var syntaxCursor = createSyntaxCursor(sourceFile);
25698             // Make the actual change larger so that we know to reparse anything whose lookahead
25699             // might have intersected the change.
25700             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
25701             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
25702             // Ensure that extending the affected range only moved the start of the change range
25703             // earlier in the file.
25704             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
25705             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
25706             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
25707             // The is the amount the nodes after the edit range need to be adjusted.  It can be
25708             // positive (if the edit added characters), negative (if the edit deleted characters)
25709             // or zero (if this was a pure overwrite with nothing added/removed).
25710             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
25711             // If we added or removed characters during the edit, then we need to go and adjust all
25712             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
25713             // may move backward (if we deleted chars).
25714             //
25715             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
25716             // to reuse are already at the appropriate position in the new text.  That way when we
25717             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
25718             // it very easy to determine if we can reuse a node.  If the node's position is at where
25719             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
25720             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
25721             // us, then we'll need to skip it or crumble it as appropriate
25722             //
25723             // We will also adjust the positions of nodes that intersect the change range as well.
25724             // By doing this, we ensure that all the positions in the old tree are consistent, not
25725             // just the positions of nodes entirely before/after the change range.  By being
25726             // consistent, we can then easily map from positions to nodes in the old tree easily.
25727             //
25728             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
25729             // that we cannot reuse these elements.
25730             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
25731             // Now that we've set up our internal incremental state just proceed and parse the
25732             // source file in the normal fashion.  When possible the parser will retrieve and
25733             // reuse nodes from the old tree.
25734             //
25735             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
25736             // parsing, we will be reusing nodes from the old tree, and placing it into new
25737             // parents.  If we don't set the parents now, we'll end up with an observably
25738             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
25739             // will immediately bail out of walking any subtrees when we can see that their parents
25740             // are already correct.
25741             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
25742             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
25743             return result;
25744         }
25745         IncrementalParser.updateSourceFile = updateSourceFile;
25746         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
25747             if (!oldDirectives)
25748                 return newDirectives;
25749             var commentDirectives;
25750             var addedNewlyScannedDirectives = false;
25751             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
25752                 var directive = oldDirectives_1[_i];
25753                 var range = directive.range, type = directive.type;
25754                 // Range before the change
25755                 if (range.end < changeStart) {
25756                     commentDirectives = ts.append(commentDirectives, directive);
25757                 }
25758                 else if (range.pos > changeRangeOldEnd) {
25759                     addNewlyScannedDirectives();
25760                     // Node is entirely past the change range.  We need to move both its pos and
25761                     // end, forward or backward appropriately.
25762                     var updatedDirective = {
25763                         range: { pos: range.pos + delta, end: range.end + delta },
25764                         type: type
25765                     };
25766                     commentDirectives = ts.append(commentDirectives, updatedDirective);
25767                     if (aggressiveChecks) {
25768                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
25769                     }
25770                 }
25771                 // Ignore ranges that fall in change range
25772             }
25773             addNewlyScannedDirectives();
25774             return commentDirectives;
25775             function addNewlyScannedDirectives() {
25776                 if (addedNewlyScannedDirectives)
25777                     return;
25778                 addedNewlyScannedDirectives = true;
25779                 if (!commentDirectives) {
25780                     commentDirectives = newDirectives;
25781                 }
25782                 else if (newDirectives) {
25783                     commentDirectives.push.apply(commentDirectives, newDirectives);
25784                 }
25785             }
25786         }
25787         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
25788             if (isArray) {
25789                 visitArray(element);
25790             }
25791             else {
25792                 visitNode(element);
25793             }
25794             return;
25795             function visitNode(node) {
25796                 var text = "";
25797                 if (aggressiveChecks && shouldCheckNode(node)) {
25798                     text = oldText.substring(node.pos, node.end);
25799                 }
25800                 // Ditch any existing LS children we may have created.  This way we can avoid
25801                 // moving them forward.
25802                 if (node._children) {
25803                     node._children = undefined;
25804                 }
25805                 node.pos += delta;
25806                 node.end += delta;
25807                 if (aggressiveChecks && shouldCheckNode(node)) {
25808                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
25809                 }
25810                 forEachChild(node, visitNode, visitArray);
25811                 if (ts.hasJSDocNodes(node)) {
25812                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25813                         var jsDocComment = _a[_i];
25814                         visitNode(jsDocComment);
25815                     }
25816                 }
25817                 checkNodePositions(node, aggressiveChecks);
25818             }
25819             function visitArray(array) {
25820                 array._children = undefined;
25821                 array.pos += delta;
25822                 array.end += delta;
25823                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
25824                     var node = array_8[_i];
25825                     visitNode(node);
25826                 }
25827             }
25828         }
25829         function shouldCheckNode(node) {
25830             switch (node.kind) {
25831                 case 10 /* StringLiteral */:
25832                 case 8 /* NumericLiteral */:
25833                 case 75 /* Identifier */:
25834                     return true;
25835             }
25836             return false;
25837         }
25838         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
25839             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
25840             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
25841             ts.Debug.assert(element.pos <= element.end);
25842             // We have an element that intersects the change range in some way.  It may have its
25843             // start, or its end (or both) in the changed range.  We want to adjust any part
25844             // that intersects such that the final tree is in a consistent state.  i.e. all
25845             // children have spans within the span of their parent, and all siblings are ordered
25846             // properly.
25847             // We may need to update both the 'pos' and the 'end' of the element.
25848             // If the 'pos' is before the start of the change, then we don't need to touch it.
25849             // If it isn't, then the 'pos' must be inside the change.  How we update it will
25850             // depend if delta is positive or negative. If delta is positive then we have
25851             // something like:
25852             //
25853             //  -------------------AAA-----------------
25854             //  -------------------BBBCCCCCCC-----------------
25855             //
25856             // In this case, we consider any node that started in the change range to still be
25857             // starting at the same position.
25858             //
25859             // however, if the delta is negative, then we instead have something like this:
25860             //
25861             //  -------------------XXXYYYYYYY-----------------
25862             //  -------------------ZZZ-----------------
25863             //
25864             // In this case, any element that started in the 'X' range will keep its position.
25865             // However any element that started after that will have their pos adjusted to be
25866             // at the end of the new range.  i.e. any node that started in the 'Y' range will
25867             // be adjusted to have their start at the end of the 'Z' range.
25868             //
25869             // The element will keep its position if possible.  Or Move backward to the new-end
25870             // if it's in the 'Y' range.
25871             element.pos = Math.min(element.pos, changeRangeNewEnd);
25872             // If the 'end' is after the change range, then we always adjust it by the delta
25873             // amount.  However, if the end is in the change range, then how we adjust it
25874             // will depend on if delta is positive or negative.  If delta is positive then we
25875             // have something like:
25876             //
25877             //  -------------------AAA-----------------
25878             //  -------------------BBBCCCCCCC-----------------
25879             //
25880             // In this case, we consider any node that ended inside the change range to keep its
25881             // end position.
25882             //
25883             // however, if the delta is negative, then we instead have something like this:
25884             //
25885             //  -------------------XXXYYYYYYY-----------------
25886             //  -------------------ZZZ-----------------
25887             //
25888             // In this case, any element that ended in the 'X' range will keep its position.
25889             // However any element that ended after that will have their pos adjusted to be
25890             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
25891             // be adjusted to have their end at the end of the 'Z' range.
25892             if (element.end >= changeRangeOldEnd) {
25893                 // Element ends after the change range.  Always adjust the end pos.
25894                 element.end += delta;
25895             }
25896             else {
25897                 // Element ends in the change range.  The element will keep its position if
25898                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
25899                 element.end = Math.min(element.end, changeRangeNewEnd);
25900             }
25901             ts.Debug.assert(element.pos <= element.end);
25902             if (element.parent) {
25903                 ts.Debug.assert(element.pos >= element.parent.pos);
25904                 ts.Debug.assert(element.end <= element.parent.end);
25905             }
25906         }
25907         function checkNodePositions(node, aggressiveChecks) {
25908             if (aggressiveChecks) {
25909                 var pos_2 = node.pos;
25910                 var visitNode_1 = function (child) {
25911                     ts.Debug.assert(child.pos >= pos_2);
25912                     pos_2 = child.end;
25913                 };
25914                 if (ts.hasJSDocNodes(node)) {
25915                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
25916                         var jsDocComment = _a[_i];
25917                         visitNode_1(jsDocComment);
25918                     }
25919                 }
25920                 forEachChild(node, visitNode_1);
25921                 ts.Debug.assert(pos_2 <= node.end);
25922             }
25923         }
25924         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
25925             visitNode(sourceFile);
25926             return;
25927             function visitNode(child) {
25928                 ts.Debug.assert(child.pos <= child.end);
25929                 if (child.pos > changeRangeOldEnd) {
25930                     // Node is entirely past the change range.  We need to move both its pos and
25931                     // end, forward or backward appropriately.
25932                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
25933                     return;
25934                 }
25935                 // Check if the element intersects the change range.  If it does, then it is not
25936                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25937                 // be able to use.
25938                 var fullEnd = child.end;
25939                 if (fullEnd >= changeStart) {
25940                     child.intersectsChange = true;
25941                     child._children = undefined;
25942                     // Adjust the pos or end (or both) of the intersecting element accordingly.
25943                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25944                     forEachChild(child, visitNode, visitArray);
25945                     if (ts.hasJSDocNodes(child)) {
25946                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
25947                             var jsDocComment = _a[_i];
25948                             visitNode(jsDocComment);
25949                         }
25950                     }
25951                     checkNodePositions(child, aggressiveChecks);
25952                     return;
25953                 }
25954                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
25955                 ts.Debug.assert(fullEnd < changeStart);
25956             }
25957             function visitArray(array) {
25958                 ts.Debug.assert(array.pos <= array.end);
25959                 if (array.pos > changeRangeOldEnd) {
25960                     // Array is entirely after the change range.  We need to move it, and move any of
25961                     // its children.
25962                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
25963                     return;
25964                 }
25965                 // Check if the element intersects the change range.  If it does, then it is not
25966                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
25967                 // be able to use.
25968                 var fullEnd = array.end;
25969                 if (fullEnd >= changeStart) {
25970                     array.intersectsChange = true;
25971                     array._children = undefined;
25972                     // Adjust the pos or end (or both) of the intersecting array accordingly.
25973                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
25974                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
25975                         var node = array_9[_i];
25976                         visitNode(node);
25977                     }
25978                     return;
25979                 }
25980                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
25981                 ts.Debug.assert(fullEnd < changeStart);
25982             }
25983         }
25984         function extendToAffectedRange(sourceFile, changeRange) {
25985             // Consider the following code:
25986             //      void foo() { /; }
25987             //
25988             // If the text changes with an insertion of / just before the semicolon then we end up with:
25989             //      void foo() { //; }
25990             //
25991             // If we were to just use the changeRange a is, then we would not rescan the { token
25992             // (as it does not intersect the actual original change range).  Because an edit may
25993             // change the token touching it, we actually need to look back *at least* one token so
25994             // that the prior token sees that change.
25995             var maxLookahead = 1;
25996             var start = changeRange.span.start;
25997             // the first iteration aligns us with the change start. subsequent iteration move us to
25998             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
25999             // start of the tree.
26000             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
26001                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
26002                 ts.Debug.assert(nearestNode.pos <= start);
26003                 var position = nearestNode.pos;
26004                 start = Math.max(0, position - 1);
26005             }
26006             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
26007             var finalLength = changeRange.newLength + (changeRange.span.start - start);
26008             return ts.createTextChangeRange(finalSpan, finalLength);
26009         }
26010         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
26011             var bestResult = sourceFile;
26012             var lastNodeEntirelyBeforePosition;
26013             forEachChild(sourceFile, visit);
26014             if (lastNodeEntirelyBeforePosition) {
26015                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
26016                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
26017                     bestResult = lastChildOfLastEntireNodeBeforePosition;
26018                 }
26019             }
26020             return bestResult;
26021             function getLastDescendant(node) {
26022                 while (true) {
26023                     var lastChild = ts.getLastChild(node);
26024                     if (lastChild) {
26025                         node = lastChild;
26026                     }
26027                     else {
26028                         return node;
26029                     }
26030                 }
26031             }
26032             function visit(child) {
26033                 if (ts.nodeIsMissing(child)) {
26034                     // Missing nodes are effectively invisible to us.  We never even consider them
26035                     // When trying to find the nearest node before us.
26036                     return;
26037                 }
26038                 // If the child intersects this position, then this node is currently the nearest
26039                 // node that starts before the position.
26040                 if (child.pos <= position) {
26041                     if (child.pos >= bestResult.pos) {
26042                         // This node starts before the position, and is closer to the position than
26043                         // the previous best node we found.  It is now the new best node.
26044                         bestResult = child;
26045                     }
26046                     // Now, the node may overlap the position, or it may end entirely before the
26047                     // position.  If it overlaps with the position, then either it, or one of its
26048                     // children must be the nearest node before the position.  So we can just
26049                     // recurse into this child to see if we can find something better.
26050                     if (position < child.end) {
26051                         // The nearest node is either this child, or one of the children inside
26052                         // of it.  We've already marked this child as the best so far.  Recurse
26053                         // in case one of the children is better.
26054                         forEachChild(child, visit);
26055                         // Once we look at the children of this node, then there's no need to
26056                         // continue any further.
26057                         return true;
26058                     }
26059                     else {
26060                         ts.Debug.assert(child.end <= position);
26061                         // The child ends entirely before this position.  Say you have the following
26062                         // (where $ is the position)
26063                         //
26064                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
26065                         //
26066                         // We would want to find the nearest preceding node in "complex expr 2".
26067                         // To support that, we keep track of this node, and once we're done searching
26068                         // for a best node, we recurse down this node to see if we can find a good
26069                         // result in it.
26070                         //
26071                         // This approach allows us to quickly skip over nodes that are entirely
26072                         // before the position, while still allowing us to find any nodes in the
26073                         // last one that might be what we want.
26074                         lastNodeEntirelyBeforePosition = child;
26075                     }
26076                 }
26077                 else {
26078                     ts.Debug.assert(child.pos > position);
26079                     // We're now at a node that is entirely past the position we're searching for.
26080                     // This node (and all following nodes) could never contribute to the result,
26081                     // so just skip them by returning 'true' here.
26082                     return true;
26083                 }
26084             }
26085         }
26086         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
26087             var oldText = sourceFile.text;
26088             if (textChangeRange) {
26089                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
26090                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
26091                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
26092                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
26093                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
26094                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
26095                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
26096                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
26097                 }
26098             }
26099         }
26100         function createSyntaxCursor(sourceFile) {
26101             var currentArray = sourceFile.statements;
26102             var currentArrayIndex = 0;
26103             ts.Debug.assert(currentArrayIndex < currentArray.length);
26104             var current = currentArray[currentArrayIndex];
26105             var lastQueriedPosition = -1 /* Value */;
26106             return {
26107                 currentNode: function (position) {
26108                     // Only compute the current node if the position is different than the last time
26109                     // we were asked.  The parser commonly asks for the node at the same position
26110                     // twice.  Once to know if can read an appropriate list element at a certain point,
26111                     // and then to actually read and consume the node.
26112                     if (position !== lastQueriedPosition) {
26113                         // Much of the time the parser will need the very next node in the array that
26114                         // we just returned a node from.So just simply check for that case and move
26115                         // forward in the array instead of searching for the node again.
26116                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
26117                             currentArrayIndex++;
26118                             current = currentArray[currentArrayIndex];
26119                         }
26120                         // If we don't have a node, or the node we have isn't in the right position,
26121                         // then try to find a viable node at the position requested.
26122                         if (!current || current.pos !== position) {
26123                             findHighestListElementThatStartsAtPosition(position);
26124                         }
26125                     }
26126                     // Cache this query so that we don't do any extra work if the parser calls back
26127                     // into us.  Note: this is very common as the parser will make pairs of calls like
26128                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
26129                     // called with 'isListElement', we don't want to redo the work when parseListElement
26130                     // is called immediately after.
26131                     lastQueriedPosition = position;
26132                     // Either we don'd have a node, or we have a node at the position being asked for.
26133                     ts.Debug.assert(!current || current.pos === position);
26134                     return current;
26135                 }
26136             };
26137             // Finds the highest element in the tree we can find that starts at the provided position.
26138             // The element must be a direct child of some node list in the tree.  This way after we
26139             // return it, we can easily return its next sibling in the list.
26140             function findHighestListElementThatStartsAtPosition(position) {
26141                 // Clear out any cached state about the last node we found.
26142                 currentArray = undefined;
26143                 currentArrayIndex = -1 /* Value */;
26144                 current = undefined;
26145                 // Recurse into the source file to find the highest node at this position.
26146                 forEachChild(sourceFile, visitNode, visitArray);
26147                 return;
26148                 function visitNode(node) {
26149                     if (position >= node.pos && position < node.end) {
26150                         // Position was within this node.  Keep searching deeper to find the node.
26151                         forEachChild(node, visitNode, visitArray);
26152                         // don't proceed any further in the search.
26153                         return true;
26154                     }
26155                     // position wasn't in this node, have to keep searching.
26156                     return false;
26157                 }
26158                 function visitArray(array) {
26159                     if (position >= array.pos && position < array.end) {
26160                         // position was in this array.  Search through this array to see if we find a
26161                         // viable element.
26162                         for (var i = 0; i < array.length; i++) {
26163                             var child = array[i];
26164                             if (child) {
26165                                 if (child.pos === position) {
26166                                     // Found the right node.  We're done.
26167                                     currentArray = array;
26168                                     currentArrayIndex = i;
26169                                     current = child;
26170                                     return true;
26171                                 }
26172                                 else {
26173                                     if (child.pos < position && position < child.end) {
26174                                         // Position in somewhere within this child.  Search in it and
26175                                         // stop searching in this array.
26176                                         forEachChild(child, visitNode, visitArray);
26177                                         return true;
26178                                     }
26179                                 }
26180                             }
26181                         }
26182                     }
26183                     // position wasn't in this array, have to keep searching.
26184                     return false;
26185                 }
26186             }
26187         }
26188         var InvalidPosition;
26189         (function (InvalidPosition) {
26190             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
26191         })(InvalidPosition || (InvalidPosition = {}));
26192     })(IncrementalParser || (IncrementalParser = {}));
26193     /** @internal */
26194     function isDeclarationFileName(fileName) {
26195         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
26196     }
26197     ts.isDeclarationFileName = isDeclarationFileName;
26198     /*@internal*/
26199     function processCommentPragmas(context, sourceText) {
26200         var pragmas = [];
26201         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
26202             var range = _a[_i];
26203             var comment = sourceText.substring(range.pos, range.end);
26204             extractPragmas(pragmas, range, comment);
26205         }
26206         context.pragmas = ts.createMap();
26207         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
26208             var pragma = pragmas_1[_b];
26209             if (context.pragmas.has(pragma.name)) {
26210                 var currentValue = context.pragmas.get(pragma.name);
26211                 if (currentValue instanceof Array) {
26212                     currentValue.push(pragma.args);
26213                 }
26214                 else {
26215                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
26216                 }
26217                 continue;
26218             }
26219             context.pragmas.set(pragma.name, pragma.args);
26220         }
26221     }
26222     ts.processCommentPragmas = processCommentPragmas;
26223     /*@internal*/
26224     function processPragmasIntoFields(context, reportDiagnostic) {
26225         context.checkJsDirective = undefined;
26226         context.referencedFiles = [];
26227         context.typeReferenceDirectives = [];
26228         context.libReferenceDirectives = [];
26229         context.amdDependencies = [];
26230         context.hasNoDefaultLib = false;
26231         context.pragmas.forEach(function (entryOrList, key) {
26232             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
26233             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
26234             switch (key) {
26235                 case "reference": {
26236                     var referencedFiles_1 = context.referencedFiles;
26237                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
26238                     var libReferenceDirectives_1 = context.libReferenceDirectives;
26239                     ts.forEach(ts.toArray(entryOrList), function (arg) {
26240                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
26241                         if (arg.arguments["no-default-lib"]) {
26242                             context.hasNoDefaultLib = true;
26243                         }
26244                         else if (types) {
26245                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
26246                         }
26247                         else if (lib) {
26248                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
26249                         }
26250                         else if (path) {
26251                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
26252                         }
26253                         else {
26254                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
26255                         }
26256                     });
26257                     break;
26258                 }
26259                 case "amd-dependency": {
26260                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
26261                     break;
26262                 }
26263                 case "amd-module": {
26264                     if (entryOrList instanceof Array) {
26265                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
26266                             var entry = entryOrList_1[_i];
26267                             if (context.moduleName) {
26268                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
26269                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
26270                             }
26271                             context.moduleName = entry.arguments.name;
26272                         }
26273                     }
26274                     else {
26275                         context.moduleName = entryOrList.arguments.name;
26276                     }
26277                     break;
26278                 }
26279                 case "ts-nocheck":
26280                 case "ts-check": {
26281                     // _last_ of either nocheck or check in a file is the "winner"
26282                     ts.forEach(ts.toArray(entryOrList), function (entry) {
26283                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
26284                             context.checkJsDirective = {
26285                                 enabled: key === "ts-check",
26286                                 end: entry.range.end,
26287                                 pos: entry.range.pos
26288                             };
26289                         }
26290                     });
26291                     break;
26292                 }
26293                 case "jsx": return; // Accessed directly
26294                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
26295             }
26296         });
26297     }
26298     ts.processPragmasIntoFields = processPragmasIntoFields;
26299     var namedArgRegExCache = ts.createMap();
26300     function getNamedArgRegEx(name) {
26301         if (namedArgRegExCache.has(name)) {
26302             return namedArgRegExCache.get(name);
26303         }
26304         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
26305         namedArgRegExCache.set(name, result);
26306         return result;
26307     }
26308     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
26309     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
26310     function extractPragmas(pragmas, range, text) {
26311         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
26312         if (tripleSlash) {
26313             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
26314             var pragma = ts.commentPragmas[name];
26315             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
26316                 return;
26317             }
26318             if (pragma.args) {
26319                 var argument = {};
26320                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
26321                     var arg = _a[_i];
26322                     var matcher = getNamedArgRegEx(arg.name);
26323                     var matchResult = matcher.exec(text);
26324                     if (!matchResult && !arg.optional) {
26325                         return; // Missing required argument, don't parse
26326                     }
26327                     else if (matchResult) {
26328                         if (arg.captureSpan) {
26329                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
26330                             argument[arg.name] = {
26331                                 value: matchResult[3],
26332                                 pos: startPos,
26333                                 end: startPos + matchResult[3].length
26334                             };
26335                         }
26336                         else {
26337                             argument[arg.name] = matchResult[3];
26338                         }
26339                     }
26340                 }
26341                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
26342             }
26343             else {
26344                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
26345             }
26346             return;
26347         }
26348         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
26349         if (singleLine) {
26350             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
26351         }
26352         if (range.kind === 3 /* MultiLineCommentTrivia */) {
26353             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
26354             var multiLineMatch = void 0;
26355             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
26356                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
26357             }
26358         }
26359     }
26360     function addPragmaForMatch(pragmas, range, kind, match) {
26361         if (!match)
26362             return;
26363         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
26364         var pragma = ts.commentPragmas[name];
26365         if (!pragma || !(pragma.kind & kind)) {
26366             return;
26367         }
26368         var args = match[2]; // Split on spaces and match up positionally with definition
26369         var argument = getNamedPragmaArguments(pragma, args);
26370         if (argument === "fail")
26371             return; // Missing required argument, fail to parse it
26372         pragmas.push({ name: name, args: { arguments: argument, range: range } });
26373         return;
26374     }
26375     function getNamedPragmaArguments(pragma, text) {
26376         if (!text)
26377             return {};
26378         if (!pragma.args)
26379             return {};
26380         var args = text.split(/\s+/);
26381         var argMap = {};
26382         for (var i = 0; i < pragma.args.length; i++) {
26383             var argument = pragma.args[i];
26384             if (!args[i] && !argument.optional) {
26385                 return "fail";
26386             }
26387             if (argument.captureSpan) {
26388                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
26389             }
26390             argMap[argument.name] = args[i];
26391         }
26392         return argMap;
26393     }
26394     /** @internal */
26395     function tagNamesAreEquivalent(lhs, rhs) {
26396         if (lhs.kind !== rhs.kind) {
26397             return false;
26398         }
26399         if (lhs.kind === 75 /* Identifier */) {
26400             return lhs.escapedText === rhs.escapedText;
26401         }
26402         if (lhs.kind === 104 /* ThisKeyword */) {
26403             return true;
26404         }
26405         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
26406         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
26407         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
26408         return lhs.name.escapedText === rhs.name.escapedText &&
26409             tagNamesAreEquivalent(lhs.expression, rhs.expression);
26410     }
26411     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
26412 })(ts || (ts = {}));
26413 var ts;
26414 (function (ts) {
26415     /* @internal */
26416     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
26417     // NOTE: The order here is important to default lib ordering as entries will have the same
26418     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
26419     //       order also affects overload resolution when a type declared in one lib is
26420     //       augmented in another lib.
26421     var libEntries = [
26422         // JavaScript only
26423         ["es5", "lib.es5.d.ts"],
26424         ["es6", "lib.es2015.d.ts"],
26425         ["es2015", "lib.es2015.d.ts"],
26426         ["es7", "lib.es2016.d.ts"],
26427         ["es2016", "lib.es2016.d.ts"],
26428         ["es2017", "lib.es2017.d.ts"],
26429         ["es2018", "lib.es2018.d.ts"],
26430         ["es2019", "lib.es2019.d.ts"],
26431         ["es2020", "lib.es2020.d.ts"],
26432         ["esnext", "lib.esnext.d.ts"],
26433         // Host only
26434         ["dom", "lib.dom.d.ts"],
26435         ["dom.iterable", "lib.dom.iterable.d.ts"],
26436         ["webworker", "lib.webworker.d.ts"],
26437         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
26438         ["scripthost", "lib.scripthost.d.ts"],
26439         // ES2015 Or ESNext By-feature options
26440         ["es2015.core", "lib.es2015.core.d.ts"],
26441         ["es2015.collection", "lib.es2015.collection.d.ts"],
26442         ["es2015.generator", "lib.es2015.generator.d.ts"],
26443         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
26444         ["es2015.promise", "lib.es2015.promise.d.ts"],
26445         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
26446         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
26447         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
26448         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
26449         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
26450         ["es2017.object", "lib.es2017.object.d.ts"],
26451         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
26452         ["es2017.string", "lib.es2017.string.d.ts"],
26453         ["es2017.intl", "lib.es2017.intl.d.ts"],
26454         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
26455         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
26456         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
26457         ["es2018.intl", "lib.es2018.intl.d.ts"],
26458         ["es2018.promise", "lib.es2018.promise.d.ts"],
26459         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
26460         ["es2019.array", "lib.es2019.array.d.ts"],
26461         ["es2019.object", "lib.es2019.object.d.ts"],
26462         ["es2019.string", "lib.es2019.string.d.ts"],
26463         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
26464         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
26465         ["es2020.promise", "lib.es2020.promise.d.ts"],
26466         ["es2020.string", "lib.es2020.string.d.ts"],
26467         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
26468         ["esnext.array", "lib.es2019.array.d.ts"],
26469         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
26470         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
26471         ["esnext.intl", "lib.esnext.intl.d.ts"],
26472         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
26473         ["esnext.string", "lib.esnext.string.d.ts"],
26474         ["esnext.promise", "lib.esnext.promise.d.ts"]
26475     ];
26476     /**
26477      * An array of supported "lib" reference file names used to determine the order for inclusion
26478      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
26479      * overload resolution when a type declared in one lib is extended by another.
26480      */
26481     /* @internal */
26482     ts.libs = libEntries.map(function (entry) { return entry[0]; });
26483     /**
26484      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
26485      * option as well as for resolving lib reference directives.
26486      */
26487     /* @internal */
26488     ts.libMap = ts.createMapFromEntries(libEntries);
26489     // Watch related options
26490     /* @internal */
26491     ts.optionsForWatch = [
26492         {
26493             name: "watchFile",
26494             type: ts.createMapFromTemplate({
26495                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
26496                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
26497                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
26498                 usefsevents: ts.WatchFileKind.UseFsEvents,
26499                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
26500             }),
26501             category: ts.Diagnostics.Advanced_Options,
26502             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
26503         },
26504         {
26505             name: "watchDirectory",
26506             type: ts.createMapFromTemplate({
26507                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
26508                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
26509                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
26510             }),
26511             category: ts.Diagnostics.Advanced_Options,
26512             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
26513         },
26514         {
26515             name: "fallbackPolling",
26516             type: ts.createMapFromTemplate({
26517                 fixedinterval: ts.PollingWatchKind.FixedInterval,
26518                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
26519                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
26520             }),
26521             category: ts.Diagnostics.Advanced_Options,
26522             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
26523         },
26524         {
26525             name: "synchronousWatchDirectory",
26526             type: "boolean",
26527             category: ts.Diagnostics.Advanced_Options,
26528             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
26529         },
26530     ];
26531     /* @internal */
26532     ts.commonOptionsWithBuild = [
26533         {
26534             name: "help",
26535             shortName: "h",
26536             type: "boolean",
26537             showInSimplifiedHelpView: true,
26538             category: ts.Diagnostics.Command_line_Options,
26539             description: ts.Diagnostics.Print_this_message,
26540         },
26541         {
26542             name: "help",
26543             shortName: "?",
26544             type: "boolean"
26545         },
26546         {
26547             name: "watch",
26548             shortName: "w",
26549             type: "boolean",
26550             showInSimplifiedHelpView: true,
26551             category: ts.Diagnostics.Command_line_Options,
26552             description: ts.Diagnostics.Watch_input_files,
26553         },
26554         {
26555             name: "preserveWatchOutput",
26556             type: "boolean",
26557             showInSimplifiedHelpView: false,
26558             category: ts.Diagnostics.Command_line_Options,
26559             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
26560         },
26561         {
26562             name: "listFiles",
26563             type: "boolean",
26564             category: ts.Diagnostics.Advanced_Options,
26565             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
26566         },
26567         {
26568             name: "listEmittedFiles",
26569             type: "boolean",
26570             category: ts.Diagnostics.Advanced_Options,
26571             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
26572         },
26573         {
26574             name: "pretty",
26575             type: "boolean",
26576             showInSimplifiedHelpView: true,
26577             category: ts.Diagnostics.Command_line_Options,
26578             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
26579         },
26580         {
26581             name: "traceResolution",
26582             type: "boolean",
26583             category: ts.Diagnostics.Advanced_Options,
26584             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
26585         },
26586         {
26587             name: "diagnostics",
26588             type: "boolean",
26589             category: ts.Diagnostics.Advanced_Options,
26590             description: ts.Diagnostics.Show_diagnostic_information
26591         },
26592         {
26593             name: "extendedDiagnostics",
26594             type: "boolean",
26595             category: ts.Diagnostics.Advanced_Options,
26596             description: ts.Diagnostics.Show_verbose_diagnostic_information
26597         },
26598         {
26599             name: "generateCpuProfile",
26600             type: "string",
26601             isFilePath: true,
26602             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26603             category: ts.Diagnostics.Advanced_Options,
26604             description: ts.Diagnostics.Generates_a_CPU_profile
26605         },
26606         {
26607             name: "incremental",
26608             shortName: "i",
26609             type: "boolean",
26610             category: ts.Diagnostics.Basic_Options,
26611             description: ts.Diagnostics.Enable_incremental_compilation,
26612             transpileOptionValue: undefined
26613         },
26614         {
26615             name: "assumeChangesOnlyAffectDirectDependencies",
26616             type: "boolean",
26617             affectsSemanticDiagnostics: true,
26618             affectsEmit: true,
26619             category: ts.Diagnostics.Advanced_Options,
26620             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
26621         },
26622         {
26623             name: "locale",
26624             type: "string",
26625             category: ts.Diagnostics.Advanced_Options,
26626             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
26627         },
26628     ];
26629     /* @internal */
26630     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
26631         {
26632             name: "all",
26633             type: "boolean",
26634             showInSimplifiedHelpView: true,
26635             category: ts.Diagnostics.Command_line_Options,
26636             description: ts.Diagnostics.Show_all_compiler_options,
26637         },
26638         {
26639             name: "version",
26640             shortName: "v",
26641             type: "boolean",
26642             showInSimplifiedHelpView: true,
26643             category: ts.Diagnostics.Command_line_Options,
26644             description: ts.Diagnostics.Print_the_compiler_s_version,
26645         },
26646         {
26647             name: "init",
26648             type: "boolean",
26649             showInSimplifiedHelpView: true,
26650             category: ts.Diagnostics.Command_line_Options,
26651             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
26652         },
26653         {
26654             name: "project",
26655             shortName: "p",
26656             type: "string",
26657             isFilePath: true,
26658             showInSimplifiedHelpView: true,
26659             category: ts.Diagnostics.Command_line_Options,
26660             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
26661             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
26662         },
26663         {
26664             name: "build",
26665             type: "boolean",
26666             shortName: "b",
26667             showInSimplifiedHelpView: true,
26668             category: ts.Diagnostics.Command_line_Options,
26669             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
26670         },
26671         {
26672             name: "showConfig",
26673             type: "boolean",
26674             category: ts.Diagnostics.Command_line_Options,
26675             isCommandLineOnly: true,
26676             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
26677         },
26678         {
26679             name: "listFilesOnly",
26680             type: "boolean",
26681             category: ts.Diagnostics.Command_line_Options,
26682             affectsSemanticDiagnostics: true,
26683             affectsEmit: true,
26684             isCommandLineOnly: true,
26685             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
26686         },
26687         // Basic
26688         {
26689             name: "target",
26690             shortName: "t",
26691             type: ts.createMapFromTemplate({
26692                 es3: 0 /* ES3 */,
26693                 es5: 1 /* ES5 */,
26694                 es6: 2 /* ES2015 */,
26695                 es2015: 2 /* ES2015 */,
26696                 es2016: 3 /* ES2016 */,
26697                 es2017: 4 /* ES2017 */,
26698                 es2018: 5 /* ES2018 */,
26699                 es2019: 6 /* ES2019 */,
26700                 es2020: 7 /* ES2020 */,
26701                 esnext: 99 /* ESNext */,
26702             }),
26703             affectsSourceFile: true,
26704             affectsModuleResolution: true,
26705             affectsEmit: true,
26706             paramType: ts.Diagnostics.VERSION,
26707             showInSimplifiedHelpView: true,
26708             category: ts.Diagnostics.Basic_Options,
26709             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
26710         },
26711         {
26712             name: "module",
26713             shortName: "m",
26714             type: ts.createMapFromTemplate({
26715                 none: ts.ModuleKind.None,
26716                 commonjs: ts.ModuleKind.CommonJS,
26717                 amd: ts.ModuleKind.AMD,
26718                 system: ts.ModuleKind.System,
26719                 umd: ts.ModuleKind.UMD,
26720                 es6: ts.ModuleKind.ES2015,
26721                 es2015: ts.ModuleKind.ES2015,
26722                 es2020: ts.ModuleKind.ES2020,
26723                 esnext: ts.ModuleKind.ESNext
26724             }),
26725             affectsModuleResolution: true,
26726             affectsEmit: true,
26727             paramType: ts.Diagnostics.KIND,
26728             showInSimplifiedHelpView: true,
26729             category: ts.Diagnostics.Basic_Options,
26730             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
26731         },
26732         {
26733             name: "lib",
26734             type: "list",
26735             element: {
26736                 name: "lib",
26737                 type: ts.libMap
26738             },
26739             affectsModuleResolution: true,
26740             showInSimplifiedHelpView: true,
26741             category: ts.Diagnostics.Basic_Options,
26742             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
26743             transpileOptionValue: undefined
26744         },
26745         {
26746             name: "allowJs",
26747             type: "boolean",
26748             affectsModuleResolution: true,
26749             showInSimplifiedHelpView: true,
26750             category: ts.Diagnostics.Basic_Options,
26751             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
26752         },
26753         {
26754             name: "checkJs",
26755             type: "boolean",
26756             category: ts.Diagnostics.Basic_Options,
26757             description: ts.Diagnostics.Report_errors_in_js_files
26758         },
26759         {
26760             name: "jsx",
26761             type: ts.createMapFromTemplate({
26762                 "preserve": 1 /* Preserve */,
26763                 "react-native": 3 /* ReactNative */,
26764                 "react": 2 /* React */
26765             }),
26766             affectsSourceFile: true,
26767             paramType: ts.Diagnostics.KIND,
26768             showInSimplifiedHelpView: true,
26769             category: ts.Diagnostics.Basic_Options,
26770             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
26771         },
26772         {
26773             name: "declaration",
26774             shortName: "d",
26775             type: "boolean",
26776             affectsEmit: true,
26777             showInSimplifiedHelpView: true,
26778             category: ts.Diagnostics.Basic_Options,
26779             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
26780             transpileOptionValue: undefined
26781         },
26782         {
26783             name: "declarationMap",
26784             type: "boolean",
26785             affectsEmit: true,
26786             showInSimplifiedHelpView: true,
26787             category: ts.Diagnostics.Basic_Options,
26788             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
26789             transpileOptionValue: undefined
26790         },
26791         {
26792             name: "emitDeclarationOnly",
26793             type: "boolean",
26794             affectsEmit: true,
26795             category: ts.Diagnostics.Advanced_Options,
26796             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
26797             transpileOptionValue: undefined
26798         },
26799         {
26800             name: "sourceMap",
26801             type: "boolean",
26802             affectsEmit: true,
26803             showInSimplifiedHelpView: true,
26804             category: ts.Diagnostics.Basic_Options,
26805             description: ts.Diagnostics.Generates_corresponding_map_file,
26806         },
26807         {
26808             name: "outFile",
26809             type: "string",
26810             affectsEmit: true,
26811             isFilePath: true,
26812             paramType: ts.Diagnostics.FILE,
26813             showInSimplifiedHelpView: true,
26814             category: ts.Diagnostics.Basic_Options,
26815             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
26816             transpileOptionValue: undefined
26817         },
26818         {
26819             name: "outDir",
26820             type: "string",
26821             affectsEmit: true,
26822             isFilePath: true,
26823             paramType: ts.Diagnostics.DIRECTORY,
26824             showInSimplifiedHelpView: true,
26825             category: ts.Diagnostics.Basic_Options,
26826             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
26827         },
26828         {
26829             name: "rootDir",
26830             type: "string",
26831             affectsEmit: true,
26832             isFilePath: true,
26833             paramType: ts.Diagnostics.LOCATION,
26834             category: ts.Diagnostics.Basic_Options,
26835             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
26836         },
26837         {
26838             name: "composite",
26839             type: "boolean",
26840             affectsEmit: true,
26841             isTSConfigOnly: true,
26842             category: ts.Diagnostics.Basic_Options,
26843             description: ts.Diagnostics.Enable_project_compilation,
26844             transpileOptionValue: undefined
26845         },
26846         {
26847             name: "tsBuildInfoFile",
26848             type: "string",
26849             affectsEmit: true,
26850             isFilePath: true,
26851             paramType: ts.Diagnostics.FILE,
26852             category: ts.Diagnostics.Basic_Options,
26853             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
26854             transpileOptionValue: undefined
26855         },
26856         {
26857             name: "removeComments",
26858             type: "boolean",
26859             affectsEmit: true,
26860             showInSimplifiedHelpView: true,
26861             category: ts.Diagnostics.Basic_Options,
26862             description: ts.Diagnostics.Do_not_emit_comments_to_output,
26863         },
26864         {
26865             name: "noEmit",
26866             type: "boolean",
26867             affectsEmit: true,
26868             showInSimplifiedHelpView: true,
26869             category: ts.Diagnostics.Basic_Options,
26870             description: ts.Diagnostics.Do_not_emit_outputs,
26871             transpileOptionValue: undefined
26872         },
26873         {
26874             name: "importHelpers",
26875             type: "boolean",
26876             affectsEmit: true,
26877             category: ts.Diagnostics.Basic_Options,
26878             description: ts.Diagnostics.Import_emit_helpers_from_tslib
26879         },
26880         {
26881             name: "importsNotUsedAsValues",
26882             type: ts.createMapFromTemplate({
26883                 remove: 0 /* Remove */,
26884                 preserve: 1 /* Preserve */,
26885                 error: 2 /* Error */
26886             }),
26887             affectsEmit: true,
26888             affectsSemanticDiagnostics: true,
26889             category: ts.Diagnostics.Advanced_Options,
26890             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
26891         },
26892         {
26893             name: "downlevelIteration",
26894             type: "boolean",
26895             affectsEmit: true,
26896             category: ts.Diagnostics.Basic_Options,
26897             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
26898         },
26899         {
26900             name: "isolatedModules",
26901             type: "boolean",
26902             category: ts.Diagnostics.Basic_Options,
26903             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
26904             transpileOptionValue: true
26905         },
26906         // Strict Type Checks
26907         {
26908             name: "strict",
26909             type: "boolean",
26910             showInSimplifiedHelpView: true,
26911             category: ts.Diagnostics.Strict_Type_Checking_Options,
26912             description: ts.Diagnostics.Enable_all_strict_type_checking_options
26913         },
26914         {
26915             name: "noImplicitAny",
26916             type: "boolean",
26917             affectsSemanticDiagnostics: true,
26918             strictFlag: true,
26919             showInSimplifiedHelpView: true,
26920             category: ts.Diagnostics.Strict_Type_Checking_Options,
26921             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
26922         },
26923         {
26924             name: "strictNullChecks",
26925             type: "boolean",
26926             affectsSemanticDiagnostics: true,
26927             strictFlag: true,
26928             showInSimplifiedHelpView: true,
26929             category: ts.Diagnostics.Strict_Type_Checking_Options,
26930             description: ts.Diagnostics.Enable_strict_null_checks
26931         },
26932         {
26933             name: "strictFunctionTypes",
26934             type: "boolean",
26935             affectsSemanticDiagnostics: true,
26936             strictFlag: true,
26937             showInSimplifiedHelpView: true,
26938             category: ts.Diagnostics.Strict_Type_Checking_Options,
26939             description: ts.Diagnostics.Enable_strict_checking_of_function_types
26940         },
26941         {
26942             name: "strictBindCallApply",
26943             type: "boolean",
26944             strictFlag: true,
26945             showInSimplifiedHelpView: true,
26946             category: ts.Diagnostics.Strict_Type_Checking_Options,
26947             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
26948         },
26949         {
26950             name: "strictPropertyInitialization",
26951             type: "boolean",
26952             affectsSemanticDiagnostics: true,
26953             strictFlag: true,
26954             showInSimplifiedHelpView: true,
26955             category: ts.Diagnostics.Strict_Type_Checking_Options,
26956             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
26957         },
26958         {
26959             name: "noImplicitThis",
26960             type: "boolean",
26961             affectsSemanticDiagnostics: true,
26962             strictFlag: true,
26963             showInSimplifiedHelpView: true,
26964             category: ts.Diagnostics.Strict_Type_Checking_Options,
26965             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
26966         },
26967         {
26968             name: "alwaysStrict",
26969             type: "boolean",
26970             affectsSourceFile: true,
26971             strictFlag: true,
26972             showInSimplifiedHelpView: true,
26973             category: ts.Diagnostics.Strict_Type_Checking_Options,
26974             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
26975         },
26976         // Additional Checks
26977         {
26978             name: "noUnusedLocals",
26979             type: "boolean",
26980             affectsSemanticDiagnostics: true,
26981             showInSimplifiedHelpView: true,
26982             category: ts.Diagnostics.Additional_Checks,
26983             description: ts.Diagnostics.Report_errors_on_unused_locals,
26984         },
26985         {
26986             name: "noUnusedParameters",
26987             type: "boolean",
26988             affectsSemanticDiagnostics: true,
26989             showInSimplifiedHelpView: true,
26990             category: ts.Diagnostics.Additional_Checks,
26991             description: ts.Diagnostics.Report_errors_on_unused_parameters,
26992         },
26993         {
26994             name: "noImplicitReturns",
26995             type: "boolean",
26996             affectsSemanticDiagnostics: true,
26997             showInSimplifiedHelpView: true,
26998             category: ts.Diagnostics.Additional_Checks,
26999             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
27000         },
27001         {
27002             name: "noFallthroughCasesInSwitch",
27003             type: "boolean",
27004             affectsBindDiagnostics: true,
27005             affectsSemanticDiagnostics: true,
27006             showInSimplifiedHelpView: true,
27007             category: ts.Diagnostics.Additional_Checks,
27008             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
27009         },
27010         // Module Resolution
27011         {
27012             name: "moduleResolution",
27013             type: ts.createMapFromTemplate({
27014                 node: ts.ModuleResolutionKind.NodeJs,
27015                 classic: ts.ModuleResolutionKind.Classic,
27016             }),
27017             affectsModuleResolution: true,
27018             paramType: ts.Diagnostics.STRATEGY,
27019             category: ts.Diagnostics.Module_Resolution_Options,
27020             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
27021         },
27022         {
27023             name: "baseUrl",
27024             type: "string",
27025             affectsModuleResolution: true,
27026             isFilePath: true,
27027             category: ts.Diagnostics.Module_Resolution_Options,
27028             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
27029         },
27030         {
27031             // this option can only be specified in tsconfig.json
27032             // use type = object to copy the value as-is
27033             name: "paths",
27034             type: "object",
27035             affectsModuleResolution: true,
27036             isTSConfigOnly: true,
27037             category: ts.Diagnostics.Module_Resolution_Options,
27038             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
27039             transpileOptionValue: undefined
27040         },
27041         {
27042             // this option can only be specified in tsconfig.json
27043             // use type = object to copy the value as-is
27044             name: "rootDirs",
27045             type: "list",
27046             isTSConfigOnly: true,
27047             element: {
27048                 name: "rootDirs",
27049                 type: "string",
27050                 isFilePath: true
27051             },
27052             affectsModuleResolution: true,
27053             category: ts.Diagnostics.Module_Resolution_Options,
27054             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
27055             transpileOptionValue: undefined
27056         },
27057         {
27058             name: "typeRoots",
27059             type: "list",
27060             element: {
27061                 name: "typeRoots",
27062                 type: "string",
27063                 isFilePath: true
27064             },
27065             affectsModuleResolution: true,
27066             category: ts.Diagnostics.Module_Resolution_Options,
27067             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
27068         },
27069         {
27070             name: "types",
27071             type: "list",
27072             element: {
27073                 name: "types",
27074                 type: "string"
27075             },
27076             affectsModuleResolution: true,
27077             showInSimplifiedHelpView: true,
27078             category: ts.Diagnostics.Module_Resolution_Options,
27079             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
27080             transpileOptionValue: undefined
27081         },
27082         {
27083             name: "allowSyntheticDefaultImports",
27084             type: "boolean",
27085             affectsSemanticDiagnostics: true,
27086             category: ts.Diagnostics.Module_Resolution_Options,
27087             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
27088         },
27089         {
27090             name: "esModuleInterop",
27091             type: "boolean",
27092             affectsSemanticDiagnostics: true,
27093             affectsEmit: true,
27094             showInSimplifiedHelpView: true,
27095             category: ts.Diagnostics.Module_Resolution_Options,
27096             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
27097         },
27098         {
27099             name: "preserveSymlinks",
27100             type: "boolean",
27101             category: ts.Diagnostics.Module_Resolution_Options,
27102             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
27103         },
27104         {
27105             name: "allowUmdGlobalAccess",
27106             type: "boolean",
27107             affectsSemanticDiagnostics: true,
27108             category: ts.Diagnostics.Module_Resolution_Options,
27109             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
27110         },
27111         // Source Maps
27112         {
27113             name: "sourceRoot",
27114             type: "string",
27115             affectsEmit: true,
27116             paramType: ts.Diagnostics.LOCATION,
27117             category: ts.Diagnostics.Source_Map_Options,
27118             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
27119         },
27120         {
27121             name: "mapRoot",
27122             type: "string",
27123             affectsEmit: true,
27124             paramType: ts.Diagnostics.LOCATION,
27125             category: ts.Diagnostics.Source_Map_Options,
27126             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
27127         },
27128         {
27129             name: "inlineSourceMap",
27130             type: "boolean",
27131             affectsEmit: true,
27132             category: ts.Diagnostics.Source_Map_Options,
27133             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
27134         },
27135         {
27136             name: "inlineSources",
27137             type: "boolean",
27138             affectsEmit: true,
27139             category: ts.Diagnostics.Source_Map_Options,
27140             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
27141         },
27142         // Experimental
27143         {
27144             name: "experimentalDecorators",
27145             type: "boolean",
27146             affectsSemanticDiagnostics: true,
27147             category: ts.Diagnostics.Experimental_Options,
27148             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
27149         },
27150         {
27151             name: "emitDecoratorMetadata",
27152             type: "boolean",
27153             affectsSemanticDiagnostics: true,
27154             affectsEmit: true,
27155             category: ts.Diagnostics.Experimental_Options,
27156             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
27157         },
27158         // Advanced
27159         {
27160             name: "jsxFactory",
27161             type: "string",
27162             category: ts.Diagnostics.Advanced_Options,
27163             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
27164         },
27165         {
27166             name: "resolveJsonModule",
27167             type: "boolean",
27168             affectsModuleResolution: true,
27169             category: ts.Diagnostics.Advanced_Options,
27170             description: ts.Diagnostics.Include_modules_imported_with_json_extension
27171         },
27172         {
27173             name: "out",
27174             type: "string",
27175             affectsEmit: true,
27176             isFilePath: false,
27177             // for correct behaviour, please use outFile
27178             category: ts.Diagnostics.Advanced_Options,
27179             paramType: ts.Diagnostics.FILE,
27180             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
27181             transpileOptionValue: undefined
27182         },
27183         {
27184             name: "reactNamespace",
27185             type: "string",
27186             affectsEmit: true,
27187             category: ts.Diagnostics.Advanced_Options,
27188             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
27189         },
27190         {
27191             name: "skipDefaultLibCheck",
27192             type: "boolean",
27193             category: ts.Diagnostics.Advanced_Options,
27194             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
27195         },
27196         {
27197             name: "charset",
27198             type: "string",
27199             category: ts.Diagnostics.Advanced_Options,
27200             description: ts.Diagnostics.The_character_set_of_the_input_files
27201         },
27202         {
27203             name: "emitBOM",
27204             type: "boolean",
27205             affectsEmit: true,
27206             category: ts.Diagnostics.Advanced_Options,
27207             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
27208         },
27209         {
27210             name: "newLine",
27211             type: ts.createMapFromTemplate({
27212                 crlf: 0 /* CarriageReturnLineFeed */,
27213                 lf: 1 /* LineFeed */
27214             }),
27215             affectsEmit: true,
27216             paramType: ts.Diagnostics.NEWLINE,
27217             category: ts.Diagnostics.Advanced_Options,
27218             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
27219         },
27220         {
27221             name: "noErrorTruncation",
27222             type: "boolean",
27223             affectsSemanticDiagnostics: true,
27224             category: ts.Diagnostics.Advanced_Options,
27225             description: ts.Diagnostics.Do_not_truncate_error_messages
27226         },
27227         {
27228             name: "noLib",
27229             type: "boolean",
27230             affectsModuleResolution: true,
27231             category: ts.Diagnostics.Advanced_Options,
27232             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
27233             // We are not returning a sourceFile for lib file when asked by the program,
27234             // so pass --noLib to avoid reporting a file not found error.
27235             transpileOptionValue: true
27236         },
27237         {
27238             name: "noResolve",
27239             type: "boolean",
27240             affectsModuleResolution: true,
27241             category: ts.Diagnostics.Advanced_Options,
27242             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
27243             // We are not doing a full typecheck, we are not resolving the whole context,
27244             // so pass --noResolve to avoid reporting missing file errors.
27245             transpileOptionValue: true
27246         },
27247         {
27248             name: "stripInternal",
27249             type: "boolean",
27250             affectsEmit: true,
27251             category: ts.Diagnostics.Advanced_Options,
27252             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
27253         },
27254         {
27255             name: "disableSizeLimit",
27256             type: "boolean",
27257             affectsSourceFile: true,
27258             category: ts.Diagnostics.Advanced_Options,
27259             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
27260         },
27261         {
27262             name: "disableSourceOfProjectReferenceRedirect",
27263             type: "boolean",
27264             isTSConfigOnly: true,
27265             category: ts.Diagnostics.Advanced_Options,
27266             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
27267         },
27268         {
27269             name: "disableSolutionSearching",
27270             type: "boolean",
27271             isTSConfigOnly: true,
27272             category: ts.Diagnostics.Advanced_Options,
27273             description: ts.Diagnostics.Disable_solution_searching_for_this_project
27274         },
27275         {
27276             name: "noImplicitUseStrict",
27277             type: "boolean",
27278             affectsSemanticDiagnostics: true,
27279             category: ts.Diagnostics.Advanced_Options,
27280             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
27281         },
27282         {
27283             name: "noEmitHelpers",
27284             type: "boolean",
27285             affectsEmit: true,
27286             category: ts.Diagnostics.Advanced_Options,
27287             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
27288         },
27289         {
27290             name: "noEmitOnError",
27291             type: "boolean",
27292             affectsEmit: true,
27293             category: ts.Diagnostics.Advanced_Options,
27294             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
27295             transpileOptionValue: undefined
27296         },
27297         {
27298             name: "preserveConstEnums",
27299             type: "boolean",
27300             affectsEmit: true,
27301             category: ts.Diagnostics.Advanced_Options,
27302             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
27303         },
27304         {
27305             name: "declarationDir",
27306             type: "string",
27307             affectsEmit: true,
27308             isFilePath: true,
27309             paramType: ts.Diagnostics.DIRECTORY,
27310             category: ts.Diagnostics.Advanced_Options,
27311             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
27312             transpileOptionValue: undefined
27313         },
27314         {
27315             name: "skipLibCheck",
27316             type: "boolean",
27317             category: ts.Diagnostics.Advanced_Options,
27318             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
27319         },
27320         {
27321             name: "allowUnusedLabels",
27322             type: "boolean",
27323             affectsBindDiagnostics: true,
27324             affectsSemanticDiagnostics: true,
27325             category: ts.Diagnostics.Advanced_Options,
27326             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
27327         },
27328         {
27329             name: "allowUnreachableCode",
27330             type: "boolean",
27331             affectsBindDiagnostics: true,
27332             affectsSemanticDiagnostics: true,
27333             category: ts.Diagnostics.Advanced_Options,
27334             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
27335         },
27336         {
27337             name: "suppressExcessPropertyErrors",
27338             type: "boolean",
27339             affectsSemanticDiagnostics: true,
27340             category: ts.Diagnostics.Advanced_Options,
27341             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
27342         },
27343         {
27344             name: "suppressImplicitAnyIndexErrors",
27345             type: "boolean",
27346             affectsSemanticDiagnostics: true,
27347             category: ts.Diagnostics.Advanced_Options,
27348             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
27349         },
27350         {
27351             name: "forceConsistentCasingInFileNames",
27352             type: "boolean",
27353             affectsModuleResolution: true,
27354             category: ts.Diagnostics.Advanced_Options,
27355             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
27356         },
27357         {
27358             name: "maxNodeModuleJsDepth",
27359             type: "number",
27360             affectsModuleResolution: true,
27361             category: ts.Diagnostics.Advanced_Options,
27362             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
27363         },
27364         {
27365             name: "noStrictGenericChecks",
27366             type: "boolean",
27367             affectsSemanticDiagnostics: true,
27368             category: ts.Diagnostics.Advanced_Options,
27369             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
27370         },
27371         {
27372             name: "useDefineForClassFields",
27373             type: "boolean",
27374             affectsSemanticDiagnostics: true,
27375             affectsEmit: true,
27376             category: ts.Diagnostics.Advanced_Options,
27377             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
27378         },
27379         {
27380             name: "keyofStringsOnly",
27381             type: "boolean",
27382             category: ts.Diagnostics.Advanced_Options,
27383             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
27384         },
27385         {
27386             // A list of plugins to load in the language service
27387             name: "plugins",
27388             type: "list",
27389             isTSConfigOnly: true,
27390             element: {
27391                 name: "plugin",
27392                 type: "object"
27393             },
27394             description: ts.Diagnostics.List_of_language_service_plugins
27395         },
27396     ]);
27397     /* @internal */
27398     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
27399     /* @internal */
27400     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
27401     /* @internal */
27402     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
27403     /* @internal */
27404     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
27405         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
27406     });
27407     /* @internal */
27408     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
27409         return ts.hasProperty(option, "transpileOptionValue");
27410     });
27411     /* @internal */
27412     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
27413         {
27414             name: "verbose",
27415             shortName: "v",
27416             category: ts.Diagnostics.Command_line_Options,
27417             description: ts.Diagnostics.Enable_verbose_logging,
27418             type: "boolean"
27419         },
27420         {
27421             name: "dry",
27422             shortName: "d",
27423             category: ts.Diagnostics.Command_line_Options,
27424             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
27425             type: "boolean"
27426         },
27427         {
27428             name: "force",
27429             shortName: "f",
27430             category: ts.Diagnostics.Command_line_Options,
27431             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
27432             type: "boolean"
27433         },
27434         {
27435             name: "clean",
27436             category: ts.Diagnostics.Command_line_Options,
27437             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
27438             type: "boolean"
27439         }
27440     ]);
27441     /* @internal */
27442     ts.typeAcquisitionDeclarations = [
27443         {
27444             /* @deprecated typingOptions.enableAutoDiscovery
27445              * Use typeAcquisition.enable instead.
27446              */
27447             name: "enableAutoDiscovery",
27448             type: "boolean",
27449         },
27450         {
27451             name: "enable",
27452             type: "boolean",
27453         },
27454         {
27455             name: "include",
27456             type: "list",
27457             element: {
27458                 name: "include",
27459                 type: "string"
27460             }
27461         },
27462         {
27463             name: "exclude",
27464             type: "list",
27465             element: {
27466                 name: "exclude",
27467                 type: "string"
27468             }
27469         }
27470     ];
27471     /*@internal*/
27472     function createOptionNameMap(optionDeclarations) {
27473         var optionsNameMap = ts.createMap();
27474         var shortOptionNames = ts.createMap();
27475         ts.forEach(optionDeclarations, function (option) {
27476             optionsNameMap.set(option.name.toLowerCase(), option);
27477             if (option.shortName) {
27478                 shortOptionNames.set(option.shortName, option.name);
27479             }
27480         });
27481         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
27482     }
27483     ts.createOptionNameMap = createOptionNameMap;
27484     var optionsNameMapCache;
27485     /* @internal */
27486     function getOptionsNameMap() {
27487         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
27488     }
27489     ts.getOptionsNameMap = getOptionsNameMap;
27490     /* @internal */
27491     ts.defaultInitCompilerOptions = {
27492         module: ts.ModuleKind.CommonJS,
27493         target: 1 /* ES5 */,
27494         strict: true,
27495         esModuleInterop: true,
27496         forceConsistentCasingInFileNames: true,
27497         skipLibCheck: true
27498     };
27499     /* @internal */
27500     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
27501         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
27502         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
27503             return {
27504                 enable: typeAcquisition.enableAutoDiscovery,
27505                 include: typeAcquisition.include || [],
27506                 exclude: typeAcquisition.exclude || []
27507             };
27508         }
27509         return typeAcquisition;
27510     }
27511     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
27512     /* @internal */
27513     function createCompilerDiagnosticForInvalidCustomType(opt) {
27514         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
27515     }
27516     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
27517     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
27518         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
27519         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
27520     }
27521     /* @internal */
27522     function parseCustomTypeOption(opt, value, errors) {
27523         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
27524     }
27525     ts.parseCustomTypeOption = parseCustomTypeOption;
27526     /* @internal */
27527     function parseListTypeOption(opt, value, errors) {
27528         if (value === void 0) { value = ""; }
27529         value = trimString(value);
27530         if (ts.startsWith(value, "-")) {
27531             return undefined;
27532         }
27533         if (value === "") {
27534             return [];
27535         }
27536         var values = value.split(",");
27537         switch (opt.element.type) {
27538             case "number":
27539                 return ts.map(values, parseInt);
27540             case "string":
27541                 return ts.map(values, function (v) { return v || ""; });
27542             default:
27543                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
27544         }
27545     }
27546     ts.parseListTypeOption = parseListTypeOption;
27547     function getOptionName(option) {
27548         return option.name;
27549     }
27550     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
27551         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
27552         return possibleOption ?
27553             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
27554             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
27555     }
27556     /*@internal*/
27557     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
27558         var options = {};
27559         var watchOptions;
27560         var fileNames = [];
27561         var errors = [];
27562         parseStrings(commandLine);
27563         return {
27564             options: options,
27565             watchOptions: watchOptions,
27566             fileNames: fileNames,
27567             errors: errors
27568         };
27569         function parseStrings(args) {
27570             var i = 0;
27571             while (i < args.length) {
27572                 var s = args[i];
27573                 i++;
27574                 if (s.charCodeAt(0) === 64 /* at */) {
27575                     parseResponseFile(s.slice(1));
27576                 }
27577                 else if (s.charCodeAt(0) === 45 /* minus */) {
27578                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
27579                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27580                     if (opt) {
27581                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
27582                     }
27583                     else {
27584                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
27585                         if (watchOpt) {
27586                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
27587                         }
27588                         else {
27589                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
27590                         }
27591                     }
27592                 }
27593                 else {
27594                     fileNames.push(s);
27595                 }
27596             }
27597         }
27598         function parseResponseFile(fileName) {
27599             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
27600             if (!ts.isString(text)) {
27601                 errors.push(text);
27602                 return;
27603             }
27604             var args = [];
27605             var pos = 0;
27606             while (true) {
27607                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
27608                     pos++;
27609                 if (pos >= text.length)
27610                     break;
27611                 var start = pos;
27612                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
27613                     pos++;
27614                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
27615                         pos++;
27616                     if (pos < text.length) {
27617                         args.push(text.substring(start + 1, pos));
27618                         pos++;
27619                     }
27620                     else {
27621                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
27622                     }
27623                 }
27624                 else {
27625                     while (text.charCodeAt(pos) > 32 /* space */)
27626                         pos++;
27627                     args.push(text.substring(start, pos));
27628                 }
27629             }
27630             parseStrings(args);
27631         }
27632     }
27633     ts.parseCommandLineWorker = parseCommandLineWorker;
27634     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
27635         if (opt.isTSConfigOnly) {
27636             var optValue = args[i];
27637             if (optValue === "null") {
27638                 options[opt.name] = undefined;
27639                 i++;
27640             }
27641             else if (opt.type === "boolean") {
27642                 if (optValue === "false") {
27643                     options[opt.name] = false;
27644                     i++;
27645                 }
27646                 else {
27647                     if (optValue === "true")
27648                         i++;
27649                     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));
27650                 }
27651             }
27652             else {
27653                 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));
27654                 if (optValue && !ts.startsWith(optValue, "-"))
27655                     i++;
27656             }
27657         }
27658         else {
27659             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
27660             if (!args[i] && opt.type !== "boolean") {
27661                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
27662             }
27663             if (args[i] !== "null") {
27664                 switch (opt.type) {
27665                     case "number":
27666                         options[opt.name] = parseInt(args[i]);
27667                         i++;
27668                         break;
27669                     case "boolean":
27670                         // boolean flag has optional value true, false, others
27671                         var optValue = args[i];
27672                         options[opt.name] = optValue !== "false";
27673                         // consume next argument as boolean flag value
27674                         if (optValue === "false" || optValue === "true") {
27675                             i++;
27676                         }
27677                         break;
27678                     case "string":
27679                         options[opt.name] = args[i] || "";
27680                         i++;
27681                         break;
27682                     case "list":
27683                         var result = parseListTypeOption(opt, args[i], errors);
27684                         options[opt.name] = result || [];
27685                         if (result) {
27686                             i++;
27687                         }
27688                         break;
27689                     // If not a primitive, the possible types are specified in what is effectively a map of options.
27690                     default:
27691                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
27692                         i++;
27693                         break;
27694                 }
27695             }
27696             else {
27697                 options[opt.name] = undefined;
27698                 i++;
27699             }
27700         }
27701         return i;
27702     }
27703     /*@internal*/
27704     ts.compilerOptionsDidYouMeanDiagnostics = {
27705         getOptionsNameMap: getOptionsNameMap,
27706         optionDeclarations: ts.optionDeclarations,
27707         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
27708         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
27709         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
27710     };
27711     function parseCommandLine(commandLine, readFile) {
27712         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
27713     }
27714     ts.parseCommandLine = parseCommandLine;
27715     /** @internal */
27716     function getOptionFromName(optionName, allowShort) {
27717         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
27718     }
27719     ts.getOptionFromName = getOptionFromName;
27720     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
27721         if (allowShort === void 0) { allowShort = false; }
27722         optionName = optionName.toLowerCase();
27723         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
27724         // Try to translate short option names to their full equivalents.
27725         if (allowShort) {
27726             var short = shortOptionNames.get(optionName);
27727             if (short !== undefined) {
27728                 optionName = short;
27729             }
27730         }
27731         return optionsNameMap.get(optionName);
27732     }
27733     var buildOptionsNameMapCache;
27734     function getBuildOptionsNameMap() {
27735         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
27736     }
27737     var buildOptionsDidYouMeanDiagnostics = {
27738         getOptionsNameMap: getBuildOptionsNameMap,
27739         optionDeclarations: ts.buildOpts,
27740         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
27741         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
27742         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
27743     };
27744     /*@internal*/
27745     function parseBuildCommand(args) {
27746         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
27747         var buildOptions = options;
27748         if (projects.length === 0) {
27749             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
27750             projects.push(".");
27751         }
27752         // Nonsensical combinations
27753         if (buildOptions.clean && buildOptions.force) {
27754             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
27755         }
27756         if (buildOptions.clean && buildOptions.verbose) {
27757             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
27758         }
27759         if (buildOptions.clean && buildOptions.watch) {
27760             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
27761         }
27762         if (buildOptions.watch && buildOptions.dry) {
27763             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
27764         }
27765         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
27766     }
27767     ts.parseBuildCommand = parseBuildCommand;
27768     /* @internal */
27769     function getDiagnosticText(_message) {
27770         var _args = [];
27771         for (var _i = 1; _i < arguments.length; _i++) {
27772             _args[_i - 1] = arguments[_i];
27773         }
27774         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
27775         return diagnostic.messageText;
27776     }
27777     ts.getDiagnosticText = getDiagnosticText;
27778     /**
27779      * Reads the config file, reports errors if any and exits if the config file cannot be found
27780      */
27781     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
27782         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
27783         if (!ts.isString(configFileText)) {
27784             host.onUnRecoverableConfigFileDiagnostic(configFileText);
27785             return undefined;
27786         }
27787         var result = ts.parseJsonText(configFileName, configFileText);
27788         var cwd = host.getCurrentDirectory();
27789         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
27790         result.resolvedPath = result.path;
27791         result.originalFileName = result.fileName;
27792         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
27793         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
27794     }
27795     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
27796     /**
27797      * Read tsconfig.json file
27798      * @param fileName The path to the config file
27799      */
27800     function readConfigFile(fileName, readFile) {
27801         var textOrDiagnostic = tryReadFile(fileName, readFile);
27802         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
27803     }
27804     ts.readConfigFile = readConfigFile;
27805     /**
27806      * Parse the text of the tsconfig.json file
27807      * @param fileName The path to the config file
27808      * @param jsonText The text of the config file
27809      */
27810     function parseConfigFileTextToJson(fileName, jsonText) {
27811         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
27812         return {
27813             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
27814             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
27815         };
27816     }
27817     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
27818     /**
27819      * Read tsconfig.json file
27820      * @param fileName The path to the config file
27821      */
27822     function readJsonConfigFile(fileName, readFile) {
27823         var textOrDiagnostic = tryReadFile(fileName, readFile);
27824         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { parseDiagnostics: [textOrDiagnostic] };
27825     }
27826     ts.readJsonConfigFile = readJsonConfigFile;
27827     /*@internal*/
27828     function tryReadFile(fileName, readFile) {
27829         var text;
27830         try {
27831             text = readFile(fileName);
27832         }
27833         catch (e) {
27834             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
27835         }
27836         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
27837     }
27838     ts.tryReadFile = tryReadFile;
27839     function commandLineOptionsToMap(options) {
27840         return ts.arrayToMap(options, getOptionName);
27841     }
27842     var typeAcquisitionDidYouMeanDiagnostics = {
27843         optionDeclarations: ts.typeAcquisitionDeclarations,
27844         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
27845         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
27846     };
27847     var watchOptionsNameMapCache;
27848     function getWatchOptionsNameMap() {
27849         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
27850     }
27851     var watchOptionsDidYouMeanDiagnostics = {
27852         getOptionsNameMap: getWatchOptionsNameMap,
27853         optionDeclarations: ts.optionsForWatch,
27854         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
27855         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
27856         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
27857     };
27858     var commandLineCompilerOptionsMapCache;
27859     function getCommandLineCompilerOptionsMap() {
27860         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
27861     }
27862     var commandLineWatchOptionsMapCache;
27863     function getCommandLineWatchOptionsMap() {
27864         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
27865     }
27866     var commandLineTypeAcquisitionMapCache;
27867     function getCommandLineTypeAcquisitionMap() {
27868         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
27869     }
27870     var _tsconfigRootOptions;
27871     function getTsconfigRootOptionsMap() {
27872         if (_tsconfigRootOptions === undefined) {
27873             _tsconfigRootOptions = {
27874                 name: undefined,
27875                 type: "object",
27876                 elementOptions: commandLineOptionsToMap([
27877                     {
27878                         name: "compilerOptions",
27879                         type: "object",
27880                         elementOptions: getCommandLineCompilerOptionsMap(),
27881                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
27882                     },
27883                     {
27884                         name: "watchOptions",
27885                         type: "object",
27886                         elementOptions: getCommandLineWatchOptionsMap(),
27887                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
27888                     },
27889                     {
27890                         name: "typingOptions",
27891                         type: "object",
27892                         elementOptions: getCommandLineTypeAcquisitionMap(),
27893                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
27894                     },
27895                     {
27896                         name: "typeAcquisition",
27897                         type: "object",
27898                         elementOptions: getCommandLineTypeAcquisitionMap(),
27899                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
27900                     },
27901                     {
27902                         name: "extends",
27903                         type: "string"
27904                     },
27905                     {
27906                         name: "references",
27907                         type: "list",
27908                         element: {
27909                             name: "references",
27910                             type: "object"
27911                         }
27912                     },
27913                     {
27914                         name: "files",
27915                         type: "list",
27916                         element: {
27917                             name: "files",
27918                             type: "string"
27919                         }
27920                     },
27921                     {
27922                         name: "include",
27923                         type: "list",
27924                         element: {
27925                             name: "include",
27926                             type: "string"
27927                         }
27928                     },
27929                     {
27930                         name: "exclude",
27931                         type: "list",
27932                         element: {
27933                             name: "exclude",
27934                             type: "string"
27935                         }
27936                     },
27937                     ts.compileOnSaveCommandLineOption
27938                 ])
27939             };
27940         }
27941         return _tsconfigRootOptions;
27942     }
27943     /**
27944      * Convert the json syntax tree into the json value
27945      */
27946     function convertToObject(sourceFile, errors) {
27947         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
27948     }
27949     ts.convertToObject = convertToObject;
27950     /**
27951      * Convert the json syntax tree into the json value and report errors
27952      * This returns the json value (apart from checking errors) only if returnValue provided is true.
27953      * Otherwise it just checks the errors and returns undefined
27954      */
27955     /*@internal*/
27956     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
27957         if (!sourceFile.statements.length) {
27958             return returnValue ? {} : undefined;
27959         }
27960         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
27961         function isRootOptionMap(knownOptions) {
27962             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
27963         }
27964         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
27965             var result = returnValue ? {} : undefined;
27966             var _loop_3 = function (element) {
27967                 if (element.kind !== 281 /* PropertyAssignment */) {
27968                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
27969                     return "continue";
27970                 }
27971                 if (element.questionToken) {
27972                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
27973                 }
27974                 if (!isDoubleQuotedString(element.name)) {
27975                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
27976                 }
27977                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
27978                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
27979                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
27980                 if (keyText && extraKeyDiagnostics && !option) {
27981                     if (knownOptions) {
27982                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
27983                     }
27984                     else {
27985                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
27986                     }
27987                 }
27988                 var value = convertPropertyValueToJson(element.initializer, option);
27989                 if (typeof keyText !== "undefined") {
27990                     if (returnValue) {
27991                         result[keyText] = value;
27992                     }
27993                     // Notify key value set, if user asked for it
27994                     if (jsonConversionNotifier &&
27995                         // Current callbacks are only on known parent option or if we are setting values in the root
27996                         (parentOption || isRootOptionMap(knownOptions))) {
27997                         var isValidOptionValue = isCompilerOptionsValue(option, value);
27998                         if (parentOption) {
27999                             if (isValidOptionValue) {
28000                                 // Notify option set in the parent if its a valid option value
28001                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
28002                             }
28003                         }
28004                         else if (isRootOptionMap(knownOptions)) {
28005                             if (isValidOptionValue) {
28006                                 // Notify about the valid root key value being set
28007                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28008                             }
28009                             else if (!option) {
28010                                 // Notify about the unknown root key value being set
28011                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
28012                             }
28013                         }
28014                     }
28015                 }
28016             };
28017             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
28018                 var element = _a[_i];
28019                 _loop_3(element);
28020             }
28021             return result;
28022         }
28023         function convertArrayLiteralExpressionToJson(elements, elementOption) {
28024             if (!returnValue) {
28025                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
28026             }
28027             // Filter out invalid values
28028             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
28029         }
28030         function convertPropertyValueToJson(valueExpression, option) {
28031             switch (valueExpression.kind) {
28032                 case 106 /* TrueKeyword */:
28033                     reportInvalidOptionValue(option && option.type !== "boolean");
28034                     return true;
28035                 case 91 /* FalseKeyword */:
28036                     reportInvalidOptionValue(option && option.type !== "boolean");
28037                     return false;
28038                 case 100 /* NullKeyword */:
28039                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
28040                     return null; // eslint-disable-line no-null/no-null
28041                 case 10 /* StringLiteral */:
28042                     if (!isDoubleQuotedString(valueExpression)) {
28043                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
28044                     }
28045                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
28046                     var text = valueExpression.text;
28047                     if (option && !ts.isString(option.type)) {
28048                         var customOption = option;
28049                         // Validate custom option type
28050                         if (!customOption.type.has(text.toLowerCase())) {
28051                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
28052                         }
28053                     }
28054                     return text;
28055                 case 8 /* NumericLiteral */:
28056                     reportInvalidOptionValue(option && option.type !== "number");
28057                     return Number(valueExpression.text);
28058                 case 207 /* PrefixUnaryExpression */:
28059                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
28060                         break; // not valid JSON syntax
28061                     }
28062                     reportInvalidOptionValue(option && option.type !== "number");
28063                     return -Number(valueExpression.operand.text);
28064                 case 193 /* ObjectLiteralExpression */:
28065                     reportInvalidOptionValue(option && option.type !== "object");
28066                     var objectLiteralExpression = valueExpression;
28067                     // Currently having element option declaration in the tsconfig with type "object"
28068                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
28069                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
28070                     // that satifies it and need it to modify options set in them (for normalizing file paths)
28071                     // vs what we set in the json
28072                     // If need arises, we can modify this interface and callbacks as needed
28073                     if (option) {
28074                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
28075                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
28076                     }
28077                     else {
28078                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
28079                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
28080                     }
28081                 case 192 /* ArrayLiteralExpression */:
28082                     reportInvalidOptionValue(option && option.type !== "list");
28083                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
28084             }
28085             // Not in expected format
28086             if (option) {
28087                 reportInvalidOptionValue(/*isError*/ true);
28088             }
28089             else {
28090                 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));
28091             }
28092             return undefined;
28093             function reportInvalidOptionValue(isError) {
28094                 if (isError) {
28095                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
28096                 }
28097             }
28098         }
28099         function isDoubleQuotedString(node) {
28100             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
28101         }
28102     }
28103     ts.convertToObjectWorker = convertToObjectWorker;
28104     function getCompilerOptionValueTypeString(option) {
28105         return option.type === "list" ?
28106             "Array" :
28107             ts.isString(option.type) ? option.type : "string";
28108     }
28109     function isCompilerOptionsValue(option, value) {
28110         if (option) {
28111             if (isNullOrUndefined(value))
28112                 return true; // All options are undefinable/nullable
28113             if (option.type === "list") {
28114                 return ts.isArray(value);
28115             }
28116             var expectedType = ts.isString(option.type) ? option.type : "string";
28117             return typeof value === expectedType;
28118         }
28119         return false;
28120     }
28121     /**
28122      * Generate an uncommented, complete tsconfig for use with "--showConfig"
28123      * @param configParseResult options to be generated into tsconfig.json
28124      * @param configFileName name of the parsed config file - output paths will be generated relative to this
28125      * @param host provides current directory and case sensitivity services
28126      */
28127     /** @internal */
28128     function convertToTSConfig(configParseResult, configFileName, host) {
28129         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28130         var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); });
28131         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
28132         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
28133         var config = __assign(__assign({ compilerOptions: __assign(__assign({}, optionMapToObject(optionMap)), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), watchOptions: watchOptionMap && optionMapToObject(watchOptionMap), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign(__assign({}, r), { path: r.originalPath ? r.originalPath : "", originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? {
28134             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
28135             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
28136         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
28137         return config;
28138     }
28139     ts.convertToTSConfig = convertToTSConfig;
28140     function optionMapToObject(optionMap) {
28141         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
28142             var _a;
28143             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
28144         }, {}));
28145     }
28146     function filterSameAsDefaultInclude(specs) {
28147         if (!ts.length(specs))
28148             return undefined;
28149         if (ts.length(specs) !== 1)
28150             return specs;
28151         if (specs[0] === "**/*")
28152             return undefined;
28153         return specs;
28154     }
28155     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
28156         if (!includeSpecs)
28157             return function (_) { return true; };
28158         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
28159         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
28160         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
28161         if (includeRe) {
28162             if (excludeRe) {
28163                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
28164             }
28165             return function (path) { return !includeRe.test(path); };
28166         }
28167         if (excludeRe) {
28168             return function (path) { return excludeRe.test(path); };
28169         }
28170         return function (_) { return true; };
28171     }
28172     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
28173         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
28174             // this is of a type CommandLineOptionOfPrimitiveType
28175             return undefined;
28176         }
28177         else if (optionDefinition.type === "list") {
28178             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
28179         }
28180         else {
28181             return optionDefinition.type;
28182         }
28183     }
28184     function getNameOfCompilerOptionValue(value, customTypeMap) {
28185         // There is a typeMap associated with this command-line option so use it to map value back to its name
28186         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
28187             if (mapValue === value) {
28188                 return key;
28189             }
28190         });
28191     }
28192     function serializeCompilerOptions(options, pathOptions) {
28193         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
28194     }
28195     function serializeWatchOptions(options) {
28196         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
28197     }
28198     function serializeOptionBaseObject(options, _a, pathOptions) {
28199         var optionsNameMap = _a.optionsNameMap;
28200         var result = ts.createMap();
28201         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
28202         var _loop_4 = function (name) {
28203             if (ts.hasProperty(options, name)) {
28204                 // tsconfig only options cannot be specified via command line,
28205                 // so we can assume that only types that can appear here string | number | boolean
28206                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
28207                     return "continue";
28208                 }
28209                 var value = options[name];
28210                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
28211                 if (optionDefinition) {
28212                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
28213                     if (!customTypeMap_1) {
28214                         // There is no map associated with this compiler option then use the value as-is
28215                         // This is the case if the value is expect to be string, number, boolean or list of string
28216                         if (pathOptions && optionDefinition.isFilePath) {
28217                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
28218                         }
28219                         else {
28220                             result.set(name, value);
28221                         }
28222                     }
28223                     else {
28224                         if (optionDefinition.type === "list") {
28225                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
28226                         }
28227                         else {
28228                             // There is a typeMap associated with this command-line option so use it to map value back to its name
28229                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
28230                         }
28231                     }
28232                 }
28233             }
28234         };
28235         for (var name in options) {
28236             _loop_4(name);
28237         }
28238         return result;
28239     }
28240     /**
28241      * Generate tsconfig configuration when running command line "--init"
28242      * @param options commandlineOptions to be generated into tsconfig.json
28243      * @param fileNames array of filenames to be generated into tsconfig.json
28244      */
28245     /* @internal */
28246     function generateTSConfig(options, fileNames, newLine) {
28247         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
28248         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
28249         return writeConfigurations();
28250         function getDefaultValueForOption(option) {
28251             switch (option.type) {
28252                 case "number":
28253                     return 1;
28254                 case "boolean":
28255                     return true;
28256                 case "string":
28257                     return option.isFilePath ? "./" : "";
28258                 case "list":
28259                     return [];
28260                 case "object":
28261                     return {};
28262                 default:
28263                     var iterResult = option.type.keys().next();
28264                     if (!iterResult.done)
28265                         return iterResult.value;
28266                     return ts.Debug.fail("Expected 'option.type' to have entries.");
28267             }
28268         }
28269         function makePadding(paddingLength) {
28270             return Array(paddingLength + 1).join(" ");
28271         }
28272         function isAllowedOption(_a) {
28273             var category = _a.category, name = _a.name;
28274             // Skip options which do not have a category or have category `Command_line_Options`
28275             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
28276             return category !== undefined
28277                 && category !== ts.Diagnostics.Command_line_Options
28278                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
28279         }
28280         function writeConfigurations() {
28281             // Filter applicable options to place in the file
28282             var categorizedOptions = ts.createMultiMap();
28283             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
28284                 var option = optionDeclarations_1[_i];
28285                 var category = option.category;
28286                 if (isAllowedOption(option)) {
28287                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
28288                 }
28289             }
28290             // Serialize all options and their descriptions
28291             var marginLength = 0;
28292             var seenKnownKeys = 0;
28293             var entries = [];
28294             categorizedOptions.forEach(function (options, category) {
28295                 if (entries.length !== 0) {
28296                     entries.push({ value: "" });
28297                 }
28298                 entries.push({ value: "/* " + category + " */" });
28299                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
28300                     var option = options_1[_i];
28301                     var optionName = void 0;
28302                     if (compilerOptionsMap.has(option.name)) {
28303                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
28304                     }
28305                     else {
28306                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
28307                     }
28308                     entries.push({
28309                         value: optionName,
28310                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
28311                     });
28312                     marginLength = Math.max(optionName.length, marginLength);
28313                 }
28314             });
28315             // Write the output
28316             var tab = makePadding(2);
28317             var result = [];
28318             result.push("{");
28319             result.push(tab + "\"compilerOptions\": {");
28320             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
28321             result.push("");
28322             // Print out each row, aligning all the descriptions on the same column.
28323             for (var _a = 0, entries_3 = entries; _a < entries_3.length; _a++) {
28324                 var entry = entries_3[_a];
28325                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
28326                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
28327             }
28328             if (fileNames.length) {
28329                 result.push(tab + "},");
28330                 result.push(tab + "\"files\": [");
28331                 for (var i = 0; i < fileNames.length; i++) {
28332                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
28333                 }
28334                 result.push(tab + "]");
28335             }
28336             else {
28337                 result.push(tab + "}");
28338             }
28339             result.push("}");
28340             return result.join(newLine) + newLine;
28341         }
28342     }
28343     ts.generateTSConfig = generateTSConfig;
28344     /* @internal */
28345     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
28346         var result = {};
28347         var optionsNameMap = getOptionsNameMap().optionsNameMap;
28348         for (var name in options) {
28349             if (ts.hasProperty(options, name)) {
28350                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
28351             }
28352         }
28353         if (result.configFilePath) {
28354             result.configFilePath = toAbsolutePath(result.configFilePath);
28355         }
28356         return result;
28357     }
28358     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
28359     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
28360         if (option && !isNullOrUndefined(value)) {
28361             if (option.type === "list") {
28362                 var values = value;
28363                 if (option.element.isFilePath && values.length) {
28364                     return values.map(toAbsolutePath);
28365                 }
28366             }
28367             else if (option.isFilePath) {
28368                 return toAbsolutePath(value);
28369             }
28370         }
28371         return value;
28372     }
28373     /**
28374      * Parse the contents of a config file (tsconfig.json).
28375      * @param json The contents of the config file to parse
28376      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28377      * @param basePath A root directory to resolve relative path entries in the config
28378      *    file to. e.g. outDir
28379      */
28380     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28381         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28382     }
28383     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
28384     /**
28385      * Parse the contents of a config file (tsconfig.json).
28386      * @param jsonNode The contents of the config file to parse
28387      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28388      * @param basePath A root directory to resolve relative path entries in the config
28389      *    file to. e.g. outDir
28390      */
28391     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
28392         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
28393     }
28394     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
28395     /*@internal*/
28396     function setConfigFileInOptions(options, configFile) {
28397         if (configFile) {
28398             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
28399         }
28400     }
28401     ts.setConfigFileInOptions = setConfigFileInOptions;
28402     function isNullOrUndefined(x) {
28403         return x === undefined || x === null; // eslint-disable-line no-null/no-null
28404     }
28405     function directoryOfCombinedPath(fileName, basePath) {
28406         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
28407         // until consistent casing errors are reported
28408         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
28409     }
28410     /**
28411      * Parse the contents of a config file from json or json source file (tsconfig.json).
28412      * @param json The contents of the config file to parse
28413      * @param sourceFile sourceFile corresponding to the Json
28414      * @param host Instance of ParseConfigHost used to enumerate files in folder.
28415      * @param basePath A root directory to resolve relative path entries in the config
28416      *    file to. e.g. outDir
28417      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
28418      */
28419     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
28420         if (existingOptions === void 0) { existingOptions = {}; }
28421         if (resolutionStack === void 0) { resolutionStack = []; }
28422         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28423         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
28424         var errors = [];
28425         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
28426         var raw = parsedConfig.raw;
28427         var options = ts.extend(existingOptions, parsedConfig.options || {});
28428         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
28429             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
28430             parsedConfig.watchOptions || existingWatchOptions;
28431         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
28432         setConfigFileInOptions(options, sourceFile);
28433         var projectReferences;
28434         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
28435         return {
28436             options: options,
28437             watchOptions: watchOptions,
28438             fileNames: fileNames,
28439             projectReferences: projectReferences,
28440             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
28441             raw: raw,
28442             errors: errors,
28443             wildcardDirectories: wildcardDirectories,
28444             compileOnSave: !!raw.compileOnSave,
28445             configFileSpecs: spec
28446         };
28447         function getFileNames() {
28448             var filesSpecs;
28449             if (ts.hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) {
28450                 if (ts.isArray(raw.files)) {
28451                     filesSpecs = raw.files;
28452                     var hasReferences = ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references);
28453                     var hasZeroOrNoReferences = !hasReferences || raw.references.length === 0;
28454                     var hasExtends = ts.hasProperty(raw, "extends");
28455                     if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
28456                         if (sourceFile) {
28457                             var fileName = configFileName || "tsconfig.json";
28458                             var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
28459                             var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
28460                             var error = nodeValue
28461                                 ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
28462                                 : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
28463                             errors.push(error);
28464                         }
28465                         else {
28466                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
28467                         }
28468                     }
28469                 }
28470                 else {
28471                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array");
28472                 }
28473             }
28474             var includeSpecs;
28475             if (ts.hasProperty(raw, "include") && !isNullOrUndefined(raw.include)) {
28476                 if (ts.isArray(raw.include)) {
28477                     includeSpecs = raw.include;
28478                 }
28479                 else {
28480                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "include", "Array");
28481                 }
28482             }
28483             var excludeSpecs;
28484             if (ts.hasProperty(raw, "exclude") && !isNullOrUndefined(raw.exclude)) {
28485                 if (ts.isArray(raw.exclude)) {
28486                     excludeSpecs = raw.exclude;
28487                 }
28488                 else {
28489                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "exclude", "Array");
28490                 }
28491             }
28492             else if (raw.compilerOptions) {
28493                 var outDir = raw.compilerOptions.outDir;
28494                 var declarationDir = raw.compilerOptions.declarationDir;
28495                 if (outDir || declarationDir) {
28496                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
28497                 }
28498             }
28499             if (filesSpecs === undefined && includeSpecs === undefined) {
28500                 includeSpecs = ["**/*"];
28501             }
28502             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
28503             if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles(raw), resolutionStack)) {
28504                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
28505             }
28506             if (ts.hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) {
28507                 if (ts.isArray(raw.references)) {
28508                     for (var _i = 0, _a = raw.references; _i < _a.length; _i++) {
28509                         var ref = _a[_i];
28510                         if (typeof ref.path !== "string") {
28511                             createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
28512                         }
28513                         else {
28514                             (projectReferences || (projectReferences = [])).push({
28515                                 path: ts.getNormalizedAbsolutePath(ref.path, basePath),
28516                                 originalPath: ref.path,
28517                                 prepend: ref.prepend,
28518                                 circular: ref.circular
28519                             });
28520                         }
28521                     }
28522                 }
28523                 else {
28524                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array");
28525                 }
28526             }
28527             return result;
28528         }
28529         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
28530             if (!sourceFile) {
28531                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
28532             }
28533         }
28534     }
28535     function isErrorNoInputFiles(error) {
28536         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
28537     }
28538     function getErrorForNoInputFiles(_a, configFileName) {
28539         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
28540         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 || []));
28541     }
28542     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
28543         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
28544     }
28545     /*@internal*/
28546     function canJsonReportNoInutFiles(raw) {
28547         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
28548     }
28549     ts.canJsonReportNoInutFiles = canJsonReportNoInutFiles;
28550     /*@internal*/
28551     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
28552         var existingErrors = configParseDiagnostics.length;
28553         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
28554             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
28555         }
28556         else {
28557             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
28558         }
28559         return existingErrors !== configParseDiagnostics.length;
28560     }
28561     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
28562     function isSuccessfulParsedTsconfig(value) {
28563         return !!value.options;
28564     }
28565     /**
28566      * This *just* extracts options/include/exclude/files out of a config file.
28567      * It does *not* resolve the included files.
28568      */
28569     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
28570         basePath = ts.normalizeSlashes(basePath);
28571         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
28572         if (resolutionStack.indexOf(resolvedPath) >= 0) {
28573             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
28574             return { raw: json || convertToObject(sourceFile, errors) };
28575         }
28576         var ownConfig = json ?
28577             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
28578             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
28579         if (ownConfig.extendedConfigPath) {
28580             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
28581             resolutionStack = resolutionStack.concat([resolvedPath]);
28582             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
28583             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
28584                 var baseRaw_1 = extendedConfig.raw;
28585                 var raw_1 = ownConfig.raw;
28586                 var setPropertyInRawIfNotUndefined = function (propertyName) {
28587                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
28588                     if (value) {
28589                         raw_1[propertyName] = value;
28590                     }
28591                 };
28592                 setPropertyInRawIfNotUndefined("include");
28593                 setPropertyInRawIfNotUndefined("exclude");
28594                 setPropertyInRawIfNotUndefined("files");
28595                 if (raw_1.compileOnSave === undefined) {
28596                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
28597                 }
28598                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
28599                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
28600                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
28601                     ownConfig.watchOptions || extendedConfig.watchOptions;
28602                 // TODO extend type typeAcquisition
28603             }
28604         }
28605         return ownConfig;
28606     }
28607     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
28608         if (ts.hasProperty(json, "excludes")) {
28609             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28610         }
28611         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
28612         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
28613         // It should be removed in future releases - use typeAcquisition instead.
28614         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
28615         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
28616         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
28617         var extendedConfigPath;
28618         if (json.extends) {
28619             if (!ts.isString(json.extends)) {
28620                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
28621             }
28622             else {
28623                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28624                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
28625             }
28626         }
28627         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28628     }
28629     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
28630         var options = getDefaultCompilerOptions(configFileName);
28631         var typeAcquisition, typingOptionstypeAcquisition;
28632         var watchOptions;
28633         var extendedConfigPath;
28634         var optionsIterator = {
28635             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
28636                 var currentOption;
28637                 switch (parentOption) {
28638                     case "compilerOptions":
28639                         currentOption = options;
28640                         break;
28641                     case "watchOptions":
28642                         currentOption = (watchOptions || (watchOptions = {}));
28643                         break;
28644                     case "typeAcquisition":
28645                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
28646                         break;
28647                     case "typingOptions":
28648                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
28649                         break;
28650                     default:
28651                         ts.Debug.fail("Unknown option");
28652                 }
28653                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
28654             },
28655             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
28656                 switch (key) {
28657                     case "extends":
28658                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
28659                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
28660                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
28661                         });
28662                         return;
28663                 }
28664             },
28665             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
28666                 if (key === "excludes") {
28667                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
28668                 }
28669             }
28670         };
28671         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
28672         if (!typeAcquisition) {
28673             if (typingOptionstypeAcquisition) {
28674                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
28675                     {
28676                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
28677                         include: typingOptionstypeAcquisition.include,
28678                         exclude: typingOptionstypeAcquisition.exclude
28679                     } :
28680                     typingOptionstypeAcquisition;
28681             }
28682             else {
28683                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
28684             }
28685         }
28686         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
28687     }
28688     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
28689         extendedConfig = ts.normalizeSlashes(extendedConfig);
28690         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
28691             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
28692             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
28693                 extendedConfigPath = extendedConfigPath + ".json";
28694                 if (!host.fileExists(extendedConfigPath)) {
28695                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28696                     return undefined;
28697                 }
28698             }
28699             return extendedConfigPath;
28700         }
28701         // If the path isn't a rooted or relative path, resolve like a module
28702         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
28703         if (resolved.resolvedModule) {
28704             return resolved.resolvedModule.resolvedFileName;
28705         }
28706         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
28707         return undefined;
28708     }
28709     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
28710         var _a;
28711         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
28712         var value;
28713         var extendedResult;
28714         var extendedConfig;
28715         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
28716             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
28717         }
28718         else {
28719             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
28720             if (!extendedResult.parseDiagnostics.length) {
28721                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
28722                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
28723                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
28724                     // Update the paths to reflect base path
28725                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
28726                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
28727                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
28728                         if (raw_2[propertyName]) {
28729                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
28730                         }
28731                     };
28732                     var raw_2 = extendedConfig.raw;
28733                     mapPropertiesInRawIfNotUndefined("include");
28734                     mapPropertiesInRawIfNotUndefined("exclude");
28735                     mapPropertiesInRawIfNotUndefined("files");
28736                 }
28737             }
28738             if (extendedConfigCache) {
28739                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
28740             }
28741         }
28742         if (sourceFile) {
28743             sourceFile.extendedSourceFiles = [extendedResult.fileName];
28744             if (extendedResult.extendedSourceFiles) {
28745                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
28746             }
28747         }
28748         if (extendedResult.parseDiagnostics.length) {
28749             errors.push.apply(errors, extendedResult.parseDiagnostics);
28750             return undefined;
28751         }
28752         return extendedConfig;
28753     }
28754     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
28755         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
28756             return false;
28757         }
28758         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
28759         return typeof result === "boolean" && result;
28760     }
28761     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
28762         var errors = [];
28763         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28764         return { options: options, errors: errors };
28765     }
28766     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
28767     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
28768         var errors = [];
28769         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
28770         return { options: options, errors: errors };
28771     }
28772     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
28773     function getDefaultCompilerOptions(configFileName) {
28774         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
28775             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
28776             : {};
28777         return options;
28778     }
28779     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28780         var options = getDefaultCompilerOptions(configFileName);
28781         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
28782         if (configFileName) {
28783             options.configFilePath = ts.normalizeSlashes(configFileName);
28784         }
28785         return options;
28786     }
28787     function getDefaultTypeAcquisition(configFileName) {
28788         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
28789     }
28790     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
28791         var options = getDefaultTypeAcquisition(configFileName);
28792         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
28793         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
28794         return options;
28795     }
28796     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
28797         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
28798     }
28799     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
28800         if (!jsonOptions) {
28801             return;
28802         }
28803         for (var id in jsonOptions) {
28804             var opt = optionsNameMap.get(id);
28805             if (opt) {
28806                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
28807             }
28808             else {
28809                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
28810             }
28811         }
28812         return defaultOptions;
28813     }
28814     function convertJsonOption(opt, value, basePath, errors) {
28815         if (isCompilerOptionsValue(opt, value)) {
28816             var optType = opt.type;
28817             if (optType === "list" && ts.isArray(value)) {
28818                 return convertJsonOptionOfListType(opt, value, basePath, errors);
28819             }
28820             else if (!ts.isString(optType)) {
28821                 return convertJsonOptionOfCustomType(opt, value, errors);
28822             }
28823             return normalizeNonListOptionValue(opt, basePath, value);
28824         }
28825         else {
28826             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
28827         }
28828     }
28829     function normalizeOptionValue(option, basePath, value) {
28830         if (isNullOrUndefined(value))
28831             return undefined;
28832         if (option.type === "list") {
28833             var listOption_1 = option;
28834             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
28835                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
28836             }
28837             return value;
28838         }
28839         else if (!ts.isString(option.type)) {
28840             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
28841         }
28842         return normalizeNonListOptionValue(option, basePath, value);
28843     }
28844     function normalizeNonListOptionValue(option, basePath, value) {
28845         if (option.isFilePath) {
28846             value = ts.getNormalizedAbsolutePath(value, basePath);
28847             if (value === "") {
28848                 value = ".";
28849             }
28850         }
28851         return value;
28852     }
28853     function convertJsonOptionOfCustomType(opt, value, errors) {
28854         if (isNullOrUndefined(value))
28855             return undefined;
28856         var key = value.toLowerCase();
28857         var val = opt.type.get(key);
28858         if (val !== undefined) {
28859             return val;
28860         }
28861         else {
28862             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
28863         }
28864     }
28865     function convertJsonOptionOfListType(option, values, basePath, errors) {
28866         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
28867     }
28868     function trimString(s) {
28869         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
28870     }
28871     /**
28872      * Tests for a path that ends in a recursive directory wildcard.
28873      * Matches **, \**, **\, and \**\, but not a**b.
28874      *
28875      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28876      *
28877      * Breakdown:
28878      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28879      *  \*\*        # matches the recursive directory wildcard "**".
28880      *  \/?$        # matches an optional trailing directory separator at the end of the string.
28881      */
28882     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
28883     /**
28884      * Tests for a path where .. appears after a recursive directory wildcard.
28885      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
28886      *
28887      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28888      *
28889      * Breakdown:
28890      *  (^|\/)      # matches either the beginning of the string or a directory separator.
28891      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
28892      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
28893      *  \.\.        # matches a parent directory path component ".."
28894      *  ($|\/)      # matches either the end of the string or a directory separator.
28895      */
28896     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
28897     /**
28898      * Tests for a path containing a wildcard character in a directory component of the path.
28899      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
28900      *
28901      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28902      *
28903      * Breakdown:
28904      *  \/          # matches a directory separator.
28905      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
28906      *  [*?]        # matches either a wildcard character (* or ?)
28907      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
28908      *  \/          # matches a directory separator.
28909      */
28910     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
28911     /**
28912      * Matches the portion of a wildcard path that does not contain wildcards.
28913      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
28914      *
28915      * NOTE: used \ in place of / above to avoid issues with multiline comments.
28916      *
28917      * Breakdown:
28918      *  ^                   # matches the beginning of the string
28919      *  [^*?]*              # matches any number of non-wildcard characters
28920      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
28921      *                      # a path component that contains at least one wildcard character (* or ?).
28922      */
28923     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
28924     /**
28925      * Expands an array of file specifications.
28926      *
28927      * @param filesSpecs The literal file names to include.
28928      * @param includeSpecs The wildcard file specifications to include.
28929      * @param excludeSpecs The wildcard file specifications to exclude.
28930      * @param basePath The base path for any relative file specifications.
28931      * @param options Compiler options.
28932      * @param host The host used to resolve files and directories.
28933      * @param errors An array for diagnostic reporting.
28934      */
28935     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
28936         basePath = ts.normalizePath(basePath);
28937         var validatedIncludeSpecs, validatedExcludeSpecs;
28938         // The exclude spec list is converted into a regular expression, which allows us to quickly
28939         // test whether a file or directory should be excluded before recursively traversing the
28940         // file system.
28941         if (includeSpecs) {
28942             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
28943         }
28944         if (excludeSpecs) {
28945             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
28946         }
28947         // Wildcard directories (provided as part of a wildcard path) are stored in a
28948         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
28949         // or a recursive directory. This information is used by filesystem watchers to monitor for
28950         // new entries in these paths.
28951         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
28952         var spec = { filesSpecs: filesSpecs, includeSpecs: includeSpecs, excludeSpecs: excludeSpecs, validatedIncludeSpecs: validatedIncludeSpecs, validatedExcludeSpecs: validatedExcludeSpecs, wildcardDirectories: wildcardDirectories };
28953         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
28954     }
28955     /**
28956      * Gets the file names from the provided config file specs that contain, files, include, exclude and
28957      * other properties needed to resolve the file names
28958      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
28959      * @param basePath The base path for any relative file specifications.
28960      * @param options Compiler options.
28961      * @param host The host used to resolve files and directories.
28962      * @param extraFileExtensions optionaly file extra file extension information from host
28963      */
28964     /* @internal */
28965     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
28966         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
28967         basePath = ts.normalizePath(basePath);
28968         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
28969         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
28970         // file map with a possibly case insensitive key. We use this map later when when including
28971         // wildcard paths.
28972         var literalFileMap = ts.createMap();
28973         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
28974         // file map with a possibly case insensitive key. We use this map to store paths matched
28975         // via wildcard, and to handle extension priority.
28976         var wildcardFileMap = ts.createMap();
28977         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
28978         // file map with a possibly case insensitive key. We use this map to store paths matched
28979         // via wildcard of *.json kind
28980         var wildCardJsonFileMap = ts.createMap();
28981         var filesSpecs = spec.filesSpecs, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
28982         // Rather than requery this for each file and filespec, we query the supported extensions
28983         // once and store it on the expansion context.
28984         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
28985         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
28986         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
28987         // remove a literal file.
28988         if (filesSpecs) {
28989             for (var _i = 0, filesSpecs_1 = filesSpecs; _i < filesSpecs_1.length; _i++) {
28990                 var fileName = filesSpecs_1[_i];
28991                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
28992                 literalFileMap.set(keyMapper(file), file);
28993             }
28994         }
28995         var jsonOnlyIncludeRegexes;
28996         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
28997             var _loop_5 = function (file) {
28998                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
28999                     // Valid only if *.json specified
29000                     if (!jsonOnlyIncludeRegexes) {
29001                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
29002                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
29003                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
29004                     }
29005                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
29006                     if (includeIndex !== -1) {
29007                         var key_1 = keyMapper(file);
29008                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
29009                             wildCardJsonFileMap.set(key_1, file);
29010                         }
29011                     }
29012                     return "continue";
29013                 }
29014                 // If we have already included a literal or wildcard path with a
29015                 // higher priority extension, we should skip this file.
29016                 //
29017                 // This handles cases where we may encounter both <file>.ts and
29018                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
29019                 // directory when they are compilation outputs.
29020                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
29021                     return "continue";
29022                 }
29023                 // We may have included a wildcard path with a lower priority
29024                 // extension due to the user-defined order of entries in the
29025                 // "include" array. If there is a lower priority extension in the
29026                 // same directory, we should remove it.
29027                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
29028                 var key = keyMapper(file);
29029                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
29030                     wildcardFileMap.set(key, file);
29031                 }
29032             };
29033             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
29034                 var file = _b[_a];
29035                 _loop_5(file);
29036             }
29037         }
29038         var literalFiles = ts.arrayFrom(literalFileMap.values());
29039         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
29040         return {
29041             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
29042             wildcardDirectories: wildcardDirectories,
29043             spec: spec
29044         };
29045     }
29046     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
29047     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
29048         return specs.filter(function (spec) {
29049             var diag = specToDiagnostic(spec, allowTrailingRecursion);
29050             if (diag !== undefined) {
29051                 errors.push(createDiagnostic(diag, spec));
29052             }
29053             return diag === undefined;
29054         });
29055         function createDiagnostic(message, spec) {
29056             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
29057             return element ?
29058                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
29059                 ts.createCompilerDiagnostic(message, spec);
29060         }
29061     }
29062     function specToDiagnostic(spec, allowTrailingRecursion) {
29063         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
29064             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29065         }
29066         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
29067             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
29068         }
29069     }
29070     /**
29071      * Gets directories in a set of include patterns that should be watched for changes.
29072      */
29073     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
29074         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
29075         // of the pattern:
29076         //
29077         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
29078         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
29079         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
29080         //
29081         // We watch a directory without recursion if it contains a wildcard in the file segment of
29082         // the pattern:
29083         //
29084         //  /a/b/*      - Watch /a/b directly to catch any new file
29085         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
29086         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
29087         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
29088         var wildcardDirectories = {};
29089         if (include !== undefined) {
29090             var recursiveKeys = [];
29091             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
29092                 var file = include_1[_i];
29093                 var spec = ts.normalizePath(ts.combinePaths(path, file));
29094                 if (excludeRegex && excludeRegex.test(spec)) {
29095                     continue;
29096                 }
29097                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
29098                 if (match) {
29099                     var key = match.key, flags = match.flags;
29100                     var existingFlags = wildcardDirectories[key];
29101                     if (existingFlags === undefined || existingFlags < flags) {
29102                         wildcardDirectories[key] = flags;
29103                         if (flags === 1 /* Recursive */) {
29104                             recursiveKeys.push(key);
29105                         }
29106                     }
29107                 }
29108             }
29109             // Remove any subpaths under an existing recursively watched directory.
29110             for (var key in wildcardDirectories) {
29111                 if (ts.hasProperty(wildcardDirectories, key)) {
29112                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
29113                         var recursiveKey = recursiveKeys_1[_a];
29114                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
29115                             delete wildcardDirectories[key];
29116                         }
29117                     }
29118                 }
29119             }
29120         }
29121         return wildcardDirectories;
29122     }
29123     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
29124         var match = wildcardDirectoryPattern.exec(spec);
29125         if (match) {
29126             return {
29127                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
29128                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
29129             };
29130         }
29131         if (ts.isImplicitGlob(spec)) {
29132             return { key: spec, flags: 1 /* Recursive */ };
29133         }
29134         return undefined;
29135     }
29136     /**
29137      * Determines whether a literal or wildcard file has already been included that has a higher
29138      * extension priority.
29139      *
29140      * @param file The path to the file.
29141      * @param extensionPriority The priority of the extension.
29142      * @param context The expansion context.
29143      */
29144     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
29145         var extensionPriority = ts.getExtensionPriority(file, extensions);
29146         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
29147         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
29148             var higherPriorityExtension = extensions[i];
29149             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
29150             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
29151                 return true;
29152             }
29153         }
29154         return false;
29155     }
29156     /**
29157      * Removes files included via wildcard expansion with a lower extension priority that have
29158      * already been included.
29159      *
29160      * @param file The path to the file.
29161      * @param extensionPriority The priority of the extension.
29162      * @param context The expansion context.
29163      */
29164     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
29165         var extensionPriority = ts.getExtensionPriority(file, extensions);
29166         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
29167         for (var i = nextExtensionPriority; i < extensions.length; i++) {
29168             var lowerPriorityExtension = extensions[i];
29169             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
29170             wildcardFiles.delete(lowerPriorityPath);
29171         }
29172     }
29173     /**
29174      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
29175      * Also converts enum values back to strings.
29176      */
29177     /* @internal */
29178     function convertCompilerOptionsForTelemetry(opts) {
29179         var out = {};
29180         for (var key in opts) {
29181             if (opts.hasOwnProperty(key)) {
29182                 var type = getOptionFromName(key);
29183                 if (type !== undefined) { // Ignore unknown options
29184                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
29185                 }
29186             }
29187         }
29188         return out;
29189     }
29190     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
29191     function getOptionValueWithEmptyStrings(value, option) {
29192         switch (option.type) {
29193             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
29194                 return "";
29195             case "string": // Could be any arbitrary string -- use empty string instead.
29196                 return "";
29197             case "number": // Allow numbers, but be sure to check it's actually a number.
29198                 return typeof value === "number" ? value : "";
29199             case "boolean":
29200                 return typeof value === "boolean" ? value : "";
29201             case "list":
29202                 var elementType_1 = option.element;
29203                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
29204             default:
29205                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
29206                     if (optionEnumValue === value) {
29207                         return optionStringValue;
29208                     }
29209                 }); // TODO: GH#18217
29210         }
29211     }
29212 })(ts || (ts = {}));
29213 var ts;
29214 (function (ts) {
29215     function trace(host) {
29216         host.trace(ts.formatMessage.apply(undefined, arguments));
29217     }
29218     ts.trace = trace;
29219     /* @internal */
29220     function isTraceEnabled(compilerOptions, host) {
29221         return !!compilerOptions.traceResolution && host.trace !== undefined;
29222     }
29223     ts.isTraceEnabled = isTraceEnabled;
29224     function withPackageId(packageInfo, r) {
29225         var packageId;
29226         if (r && packageInfo) {
29227             var packageJsonContent = packageInfo.packageJsonContent;
29228             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
29229                 packageId = {
29230                     name: packageJsonContent.name,
29231                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
29232                     version: packageJsonContent.version
29233                 };
29234             }
29235         }
29236         return r && { path: r.path, extension: r.ext, packageId: packageId };
29237     }
29238     function noPackageId(r) {
29239         return withPackageId(/*packageInfo*/ undefined, r);
29240     }
29241     function removeIgnoredPackageId(r) {
29242         if (r) {
29243             ts.Debug.assert(r.packageId === undefined);
29244             return { path: r.path, ext: r.extension };
29245         }
29246     }
29247     /**
29248      * Kinds of file that we are currently looking for.
29249      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
29250      */
29251     var Extensions;
29252     (function (Extensions) {
29253         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
29254         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
29255         Extensions[Extensions["Json"] = 2] = "Json";
29256         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
29257         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
29258     })(Extensions || (Extensions = {}));
29259     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
29260     function resolvedTypeScriptOnly(resolved) {
29261         if (!resolved) {
29262             return undefined;
29263         }
29264         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
29265         return { fileName: resolved.path, packageId: resolved.packageId };
29266     }
29267     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
29268         var _a;
29269         if (resultFromCache) {
29270             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
29271             return resultFromCache;
29272         }
29273         return {
29274             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
29275             failedLookupLocations: failedLookupLocations
29276         };
29277     }
29278     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
29279         if (!ts.hasProperty(jsonContent, fieldName)) {
29280             if (state.traceEnabled) {
29281                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
29282             }
29283             return;
29284         }
29285         var value = jsonContent[fieldName];
29286         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
29287             if (state.traceEnabled) {
29288                 // eslint-disable-next-line no-null/no-null
29289                 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);
29290             }
29291             return;
29292         }
29293         return value;
29294     }
29295     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
29296         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
29297         if (fileName === undefined) {
29298             return;
29299         }
29300         if (!fileName) {
29301             if (state.traceEnabled) {
29302                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
29303             }
29304             return;
29305         }
29306         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
29307         if (state.traceEnabled) {
29308             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
29309         }
29310         return path;
29311     }
29312     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
29313         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
29314             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
29315     }
29316     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
29317         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
29318     }
29319     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
29320         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
29321     }
29322     function readPackageJsonTypesVersionsField(jsonContent, state) {
29323         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
29324         if (typesVersions === undefined)
29325             return;
29326         if (state.traceEnabled) {
29327             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
29328         }
29329         return typesVersions;
29330     }
29331     function readPackageJsonTypesVersionPaths(jsonContent, state) {
29332         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
29333         if (typesVersions === undefined)
29334             return;
29335         if (state.traceEnabled) {
29336             for (var key in typesVersions) {
29337                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
29338                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
29339                 }
29340             }
29341         }
29342         var result = getPackageJsonTypesVersionsPaths(typesVersions);
29343         if (!result) {
29344             if (state.traceEnabled) {
29345                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
29346             }
29347             return;
29348         }
29349         var bestVersionKey = result.version, bestVersionPaths = result.paths;
29350         if (typeof bestVersionPaths !== "object") {
29351             if (state.traceEnabled) {
29352                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
29353             }
29354             return;
29355         }
29356         return result;
29357     }
29358     var typeScriptVersion;
29359     /* @internal */
29360     function getPackageJsonTypesVersionsPaths(typesVersions) {
29361         if (!typeScriptVersion)
29362             typeScriptVersion = new ts.Version(ts.version);
29363         for (var key in typesVersions) {
29364             if (!ts.hasProperty(typesVersions, key))
29365                 continue;
29366             var keyRange = ts.VersionRange.tryParse(key);
29367             if (keyRange === undefined) {
29368                 continue;
29369             }
29370             // return the first entry whose range matches the current compiler version.
29371             if (keyRange.test(typeScriptVersion)) {
29372                 return { version: key, paths: typesVersions[key] };
29373             }
29374         }
29375     }
29376     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
29377     function getEffectiveTypeRoots(options, host) {
29378         if (options.typeRoots) {
29379             return options.typeRoots;
29380         }
29381         var currentDirectory;
29382         if (options.configFilePath) {
29383             currentDirectory = ts.getDirectoryPath(options.configFilePath);
29384         }
29385         else if (host.getCurrentDirectory) {
29386             currentDirectory = host.getCurrentDirectory();
29387         }
29388         if (currentDirectory !== undefined) {
29389             return getDefaultTypeRoots(currentDirectory, host);
29390         }
29391     }
29392     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
29393     /**
29394      * Returns the path to every node_modules/@types directory from some ancestor directory.
29395      * Returns undefined if there are none.
29396      */
29397     function getDefaultTypeRoots(currentDirectory, host) {
29398         if (!host.directoryExists) {
29399             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
29400             // And if it doesn't exist, tough.
29401         }
29402         var typeRoots;
29403         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
29404             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
29405             if (host.directoryExists(atTypes)) {
29406                 (typeRoots || (typeRoots = [])).push(atTypes);
29407             }
29408             return undefined;
29409         });
29410         return typeRoots;
29411     }
29412     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
29413     /**
29414      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
29415      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
29416      * is assumed to be the same as root directory of the project.
29417      */
29418     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
29419         var traceEnabled = isTraceEnabled(options, host);
29420         if (redirectedReference) {
29421             options = redirectedReference.commandLine.options;
29422         }
29423         var failedLookupLocations = [];
29424         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29425         var typeRoots = getEffectiveTypeRoots(options, host);
29426         if (traceEnabled) {
29427             if (containingFile === undefined) {
29428                 if (typeRoots === undefined) {
29429                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
29430                 }
29431                 else {
29432                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
29433                 }
29434             }
29435             else {
29436                 if (typeRoots === undefined) {
29437                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
29438                 }
29439                 else {
29440                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
29441                 }
29442             }
29443             if (redirectedReference) {
29444                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29445             }
29446         }
29447         var resolved = primaryLookup();
29448         var primary = true;
29449         if (!resolved) {
29450             resolved = secondaryLookup();
29451             primary = false;
29452         }
29453         var resolvedTypeReferenceDirective;
29454         if (resolved) {
29455             var fileName = resolved.fileName, packageId = resolved.packageId;
29456             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
29457             if (traceEnabled) {
29458                 if (packageId) {
29459                     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);
29460                 }
29461                 else {
29462                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
29463                 }
29464             }
29465             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
29466         }
29467         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
29468         function primaryLookup() {
29469             // Check primary library paths
29470             if (typeRoots && typeRoots.length) {
29471                 if (traceEnabled) {
29472                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
29473                 }
29474                 return ts.firstDefined(typeRoots, function (typeRoot) {
29475                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
29476                     var candidateDirectory = ts.getDirectoryPath(candidate);
29477                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
29478                     if (!directoryExists && traceEnabled) {
29479                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
29480                     }
29481                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
29482                 });
29483             }
29484             else {
29485                 if (traceEnabled) {
29486                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
29487                 }
29488             }
29489         }
29490         function secondaryLookup() {
29491             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
29492             if (initialLocationForSecondaryLookup !== undefined) {
29493                 // check secondary locations
29494                 if (traceEnabled) {
29495                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
29496                 }
29497                 var result = void 0;
29498                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
29499                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
29500                     result = searchResult && searchResult.value;
29501                 }
29502                 else {
29503                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
29504                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
29505                 }
29506                 var resolvedFile = resolvedTypeScriptOnly(result);
29507                 if (!resolvedFile && traceEnabled) {
29508                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
29509                 }
29510                 return resolvedFile;
29511             }
29512             else {
29513                 if (traceEnabled) {
29514                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
29515                 }
29516             }
29517         }
29518     }
29519     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
29520     /**
29521      * Given a set of options, returns the set of type directive names
29522      *   that should be included for this program automatically.
29523      * This list could either come from the config file,
29524      *   or from enumerating the types root + initial secondary types lookup location.
29525      * More type directives might appear in the program later as a result of loading actual source files;
29526      *   this list is only the set of defaults that are implicitly included.
29527      */
29528     function getAutomaticTypeDirectiveNames(options, host) {
29529         // Use explicit type list from tsconfig.json
29530         if (options.types) {
29531             return options.types;
29532         }
29533         // Walk the primary type lookup locations
29534         var result = [];
29535         if (host.directoryExists && host.getDirectories) {
29536             var typeRoots = getEffectiveTypeRoots(options, host);
29537             if (typeRoots) {
29538                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
29539                     var root = typeRoots_1[_i];
29540                     if (host.directoryExists(root)) {
29541                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
29542                             var typeDirectivePath = _b[_a];
29543                             var normalized = ts.normalizePath(typeDirectivePath);
29544                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
29545                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
29546                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
29547                             // eslint-disable-next-line no-null/no-null
29548                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
29549                             if (!isNotNeededPackage) {
29550                                 var baseFileName = ts.getBaseFileName(normalized);
29551                                 // At this stage, skip results with leading dot.
29552                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
29553                                     // Return just the type directive names
29554                                     result.push(baseFileName);
29555                                 }
29556                             }
29557                         }
29558                     }
29559                 }
29560             }
29561         }
29562         return result;
29563     }
29564     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
29565     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
29566         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
29567     }
29568     ts.createModuleResolutionCache = createModuleResolutionCache;
29569     /*@internal*/
29570     function createCacheWithRedirects(options) {
29571         var ownMap = ts.createMap();
29572         var redirectsMap = ts.createMap();
29573         return {
29574             ownMap: ownMap,
29575             redirectsMap: redirectsMap,
29576             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
29577             clear: clear,
29578             setOwnOptions: setOwnOptions,
29579             setOwnMap: setOwnMap
29580         };
29581         function setOwnOptions(newOptions) {
29582             options = newOptions;
29583         }
29584         function setOwnMap(newOwnMap) {
29585             ownMap = newOwnMap;
29586         }
29587         function getOrCreateMapOfCacheRedirects(redirectedReference) {
29588             if (!redirectedReference) {
29589                 return ownMap;
29590             }
29591             var path = redirectedReference.sourceFile.path;
29592             var redirects = redirectsMap.get(path);
29593             if (!redirects) {
29594                 // Reuse map if redirected reference map uses same resolution
29595                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? ts.createMap() : ownMap;
29596                 redirectsMap.set(path, redirects);
29597             }
29598             return redirects;
29599         }
29600         function clear() {
29601             ownMap.clear();
29602             redirectsMap.clear();
29603         }
29604     }
29605     ts.createCacheWithRedirects = createCacheWithRedirects;
29606     /*@internal*/
29607     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
29608         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
29609         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
29610             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
29611             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, ts.createMap);
29612         }
29613         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
29614             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
29615             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
29616         }
29617         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
29618             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
29619             var result = cache.get(key);
29620             if (!result) {
29621                 result = create();
29622                 cache.set(key, result);
29623             }
29624             return result;
29625         }
29626         function createPerModuleNameCache() {
29627             var directoryPathMap = ts.createMap();
29628             return { get: get, set: set };
29629             function get(directory) {
29630                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
29631             }
29632             /**
29633              * At first this function add entry directory -> module resolution result to the table.
29634              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
29635              * and for every parent folder in set it adds entry: parent -> module resolution. .
29636              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
29637              * Set of parent folders that should have the same result will be:
29638              * [
29639              *     /a/b/c/d, /a/b/c, /a/b
29640              * ]
29641              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
29642              */
29643             function set(directory, result) {
29644                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
29645                 // if entry is already in cache do nothing
29646                 if (directoryPathMap.has(path)) {
29647                     return;
29648                 }
29649                 directoryPathMap.set(path, result);
29650                 var resolvedFileName = result.resolvedModule &&
29651                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
29652                 // find common prefix between directory and resolved file name
29653                 // this common prefix should be the shortest path that has the same resolution
29654                 // directory: /a/b/c/d/e
29655                 // resolvedFileName: /a/b/foo.d.ts
29656                 // commonPrefix: /a/b
29657                 // for failed lookups cache the result for every directory up to root
29658                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
29659                 var current = path;
29660                 while (current !== commonPrefix) {
29661                     var parent = ts.getDirectoryPath(current);
29662                     if (parent === current || directoryPathMap.has(parent)) {
29663                         break;
29664                     }
29665                     directoryPathMap.set(parent, result);
29666                     current = parent;
29667                 }
29668             }
29669             function getCommonPrefix(directory, resolution) {
29670                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
29671                 // find first position where directory and resolution differs
29672                 var i = 0;
29673                 var limit = Math.min(directory.length, resolutionDirectory.length);
29674                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
29675                     i++;
29676                 }
29677                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
29678                     return directory;
29679                 }
29680                 var rootLength = ts.getRootLength(directory);
29681                 if (i < rootLength) {
29682                     return undefined;
29683                 }
29684                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
29685                 if (sep === -1) {
29686                     return undefined;
29687                 }
29688                 return directory.substr(0, Math.max(sep, rootLength));
29689             }
29690         }
29691     }
29692     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
29693     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
29694         var containingDirectory = ts.getDirectoryPath(containingFile);
29695         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
29696         return perFolderCache && perFolderCache.get(moduleName);
29697     }
29698     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
29699     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
29700         var traceEnabled = isTraceEnabled(compilerOptions, host);
29701         if (redirectedReference) {
29702             compilerOptions = redirectedReference.commandLine.options;
29703         }
29704         if (traceEnabled) {
29705             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
29706             if (redirectedReference) {
29707                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
29708             }
29709         }
29710         var containingDirectory = ts.getDirectoryPath(containingFile);
29711         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
29712         var result = perFolderCache && perFolderCache.get(moduleName);
29713         if (result) {
29714             if (traceEnabled) {
29715                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
29716             }
29717         }
29718         else {
29719             var moduleResolution = compilerOptions.moduleResolution;
29720             if (moduleResolution === undefined) {
29721                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
29722                 if (traceEnabled) {
29723                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
29724                 }
29725             }
29726             else {
29727                 if (traceEnabled) {
29728                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
29729                 }
29730             }
29731             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
29732             switch (moduleResolution) {
29733                 case ts.ModuleResolutionKind.NodeJs:
29734                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29735                     break;
29736                 case ts.ModuleResolutionKind.Classic:
29737                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
29738                     break;
29739                 default:
29740                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
29741             }
29742             if (result && result.resolvedModule)
29743                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
29744             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
29745             if (perFolderCache) {
29746                 perFolderCache.set(moduleName, result);
29747                 if (!ts.isExternalModuleNameRelative(moduleName)) {
29748                     // put result in per-module name cache
29749                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
29750                 }
29751             }
29752         }
29753         if (traceEnabled) {
29754             if (result.resolvedModule) {
29755                 if (result.resolvedModule.packageId) {
29756                     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));
29757                 }
29758                 else {
29759                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
29760                 }
29761             }
29762             else {
29763                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
29764             }
29765         }
29766         return result;
29767     }
29768     ts.resolveModuleName = resolveModuleName;
29769     /**
29770      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
29771      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
29772      * can be resolved successfully by TypeScript compiler and runtime module loader.
29773      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
29774      * fallback to standard resolution routine.
29775      *
29776      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
29777      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
29778      * be '/a/b/c/d'
29779      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
29780      * will be resolved based on the content of the module name.
29781      * Structure of 'paths' compiler options
29782      * 'paths': {
29783      *    pattern-1: [...substitutions],
29784      *    pattern-2: [...substitutions],
29785      *    ...
29786      *    pattern-n: [...substitutions]
29787      * }
29788      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
29789      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
29790      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
29791      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
29792      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
29793      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
29794      * from the candidate location.
29795      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
29796      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
29797      * will be converted to absolute using baseUrl.
29798      * For example:
29799      * baseUrl: /a/b/c
29800      * "paths": {
29801      *     // match all module names
29802      *     "*": [
29803      *         "*",        // use matched name as is,
29804      *                     // <matched name> will be looked as /a/b/c/<matched name>
29805      *
29806      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
29807      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
29808      *     ],
29809      *     // match module names that start with 'components/'
29810      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
29811      *                                              // it is rooted so it will be final candidate location
29812      * }
29813      *
29814      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
29815      * they were in the same location. For example lets say there are two files
29816      * '/local/src/content/file1.ts'
29817      * '/shared/components/contracts/src/content/protocols/file2.ts'
29818      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
29819      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
29820      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
29821      * root dirs were merged together.
29822      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
29823      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
29824      * '/local/src/content/protocols/file2' and try to load it - failure.
29825      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
29826      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
29827      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
29828      */
29829     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
29830         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
29831         if (resolved)
29832             return resolved.value;
29833         if (!ts.isExternalModuleNameRelative(moduleName)) {
29834             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
29835         }
29836         else {
29837             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
29838         }
29839     }
29840     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
29841         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
29842         if (baseUrl && paths && !ts.pathIsRelative(moduleName)) {
29843             if (state.traceEnabled) {
29844                 trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29845                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
29846             }
29847             return tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state);
29848         }
29849     }
29850     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
29851         if (!state.compilerOptions.rootDirs) {
29852             return undefined;
29853         }
29854         if (state.traceEnabled) {
29855             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
29856         }
29857         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
29858         var matchedRootDir;
29859         var matchedNormalizedPrefix;
29860         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
29861             var rootDir = _a[_i];
29862             // rootDirs are expected to be absolute
29863             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
29864             // using location of tsconfig.json as base location
29865             var normalizedRoot = ts.normalizePath(rootDir);
29866             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
29867                 normalizedRoot += ts.directorySeparator;
29868             }
29869             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
29870                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
29871             if (state.traceEnabled) {
29872                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
29873             }
29874             if (isLongestMatchingPrefix) {
29875                 matchedNormalizedPrefix = normalizedRoot;
29876                 matchedRootDir = rootDir;
29877             }
29878         }
29879         if (matchedNormalizedPrefix) {
29880             if (state.traceEnabled) {
29881                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
29882             }
29883             var suffix = candidate.substr(matchedNormalizedPrefix.length);
29884             // first - try to load from a initial location
29885             if (state.traceEnabled) {
29886                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
29887             }
29888             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
29889             if (resolvedFileName) {
29890                 return resolvedFileName;
29891             }
29892             if (state.traceEnabled) {
29893                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
29894             }
29895             // then try to resolve using remaining entries in rootDirs
29896             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
29897                 var rootDir = _c[_b];
29898                 if (rootDir === matchedRootDir) {
29899                     // skip the initially matched entry
29900                     continue;
29901                 }
29902                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
29903                 if (state.traceEnabled) {
29904                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
29905                 }
29906                 var baseDirectory = ts.getDirectoryPath(candidate_1);
29907                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
29908                 if (resolvedFileName_1) {
29909                     return resolvedFileName_1;
29910                 }
29911             }
29912             if (state.traceEnabled) {
29913                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
29914             }
29915         }
29916         return undefined;
29917     }
29918     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
29919         var baseUrl = state.compilerOptions.baseUrl;
29920         if (!baseUrl) {
29921             return undefined;
29922         }
29923         if (state.traceEnabled) {
29924             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
29925         }
29926         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
29927         if (state.traceEnabled) {
29928             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
29929         }
29930         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
29931     }
29932     /**
29933      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
29934      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
29935      * Throws an error if the module can't be resolved.
29936      */
29937     /* @internal */
29938     function resolveJSModule(moduleName, initialDir, host) {
29939         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
29940         if (!resolvedModule) {
29941             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
29942         }
29943         return resolvedModule.resolvedFileName;
29944     }
29945     ts.resolveJSModule = resolveJSModule;
29946     /* @internal */
29947     function tryResolveJSModule(moduleName, initialDir, host) {
29948         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
29949         return resolvedModule && resolvedModule.resolvedFileName;
29950     }
29951     ts.tryResolveJSModule = tryResolveJSModule;
29952     var jsOnlyExtensions = [Extensions.JavaScript];
29953     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
29954     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
29955     var tsconfigExtensions = [Extensions.TSConfig];
29956     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
29957         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
29958     }
29959     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
29960         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
29961     }
29962     ts.nodeModuleNameResolver = nodeModuleNameResolver;
29963     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
29964         var _a, _b;
29965         var traceEnabled = isTraceEnabled(compilerOptions, host);
29966         var failedLookupLocations = [];
29967         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
29968         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
29969         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);
29970         function tryResolve(extensions) {
29971             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
29972             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
29973             if (resolved) {
29974                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
29975             }
29976             if (!ts.isExternalModuleNameRelative(moduleName)) {
29977                 if (traceEnabled) {
29978                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
29979                 }
29980                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
29981                 if (!resolved_1)
29982                     return undefined;
29983                 var resolvedValue = resolved_1.value;
29984                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
29985                     var path = realPath(resolvedValue.path, host, traceEnabled);
29986                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
29987                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
29988                 }
29989                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
29990                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
29991             }
29992             else {
29993                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
29994                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
29995                 // Treat explicit "node_modules" import as an external library import.
29996                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
29997             }
29998         }
29999     }
30000     function realPath(path, host, traceEnabled) {
30001         if (!host.realpath) {
30002             return path;
30003         }
30004         var real = ts.normalizePath(host.realpath(path));
30005         if (traceEnabled) {
30006             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
30007         }
30008         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
30009         return real;
30010     }
30011     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30012         if (state.traceEnabled) {
30013             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
30014         }
30015         if (!ts.hasTrailingDirectorySeparator(candidate)) {
30016             if (!onlyRecordFailures) {
30017                 var parentOfCandidate = ts.getDirectoryPath(candidate);
30018                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
30019                     if (state.traceEnabled) {
30020                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
30021                     }
30022                     onlyRecordFailures = true;
30023                 }
30024             }
30025             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
30026             if (resolvedFromFile) {
30027                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
30028                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
30029                 return withPackageId(packageInfo, resolvedFromFile);
30030             }
30031         }
30032         if (!onlyRecordFailures) {
30033             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
30034             if (!candidateExists) {
30035                 if (state.traceEnabled) {
30036                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
30037                 }
30038                 onlyRecordFailures = true;
30039             }
30040         }
30041         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
30042     }
30043     /*@internal*/
30044     ts.nodeModulesPathPart = "/node_modules/";
30045     /*@internal*/
30046     function pathContainsNodeModules(path) {
30047         return ts.stringContains(path, ts.nodeModulesPathPart);
30048     }
30049     ts.pathContainsNodeModules = pathContainsNodeModules;
30050     /**
30051      * This will be called on the successfully resolved path from `loadModuleFromFile`.
30052      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
30053      *
30054      * packageDirectory is the directory of the package itself.
30055      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
30056      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
30057      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
30058      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
30059      */
30060     function parseNodeModuleFromPath(resolved) {
30061         var path = ts.normalizePath(resolved.path);
30062         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
30063         if (idx === -1) {
30064             return undefined;
30065         }
30066         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
30067         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
30068         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
30069             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
30070         }
30071         return path.slice(0, indexAfterPackageName);
30072     }
30073     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
30074         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
30075         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
30076     }
30077     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
30078         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
30079     }
30080     /**
30081      * @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
30082      * 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.
30083      */
30084     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
30085         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
30086             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
30087             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
30088         }
30089         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
30090         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
30091         if (resolvedByAddingExtension) {
30092             return resolvedByAddingExtension;
30093         }
30094         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
30095         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
30096         if (ts.hasJSFileExtension(candidate)) {
30097             var extensionless = ts.removeFileExtension(candidate);
30098             if (state.traceEnabled) {
30099                 var extension = candidate.substring(extensionless.length);
30100                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
30101             }
30102             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
30103         }
30104     }
30105     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
30106     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
30107         if (!onlyRecordFailures) {
30108             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
30109             var directory = ts.getDirectoryPath(candidate);
30110             if (directory) {
30111                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
30112             }
30113         }
30114         switch (extensions) {
30115             case Extensions.DtsOnly:
30116                 return tryExtension(".d.ts" /* Dts */);
30117             case Extensions.TypeScript:
30118                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
30119             case Extensions.JavaScript:
30120                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
30121             case Extensions.TSConfig:
30122             case Extensions.Json:
30123                 return tryExtension(".json" /* Json */);
30124         }
30125         function tryExtension(ext) {
30126             var path = tryFile(candidate + ext, onlyRecordFailures, state);
30127             return path === undefined ? undefined : { path: path, ext: ext };
30128         }
30129     }
30130     /** Return the file if it exists. */
30131     function tryFile(fileName, onlyRecordFailures, state) {
30132         if (!onlyRecordFailures) {
30133             if (state.host.fileExists(fileName)) {
30134                 if (state.traceEnabled) {
30135                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
30136                 }
30137                 return fileName;
30138             }
30139             else {
30140                 if (state.traceEnabled) {
30141                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
30142                 }
30143             }
30144         }
30145         state.failedLookupLocations.push(fileName);
30146         return undefined;
30147     }
30148     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
30149         if (considerPackageJson === void 0) { considerPackageJson = true; }
30150         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
30151         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
30152         var versionPaths = packageInfo && packageInfo.versionPaths;
30153         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
30154     }
30155     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
30156         var host = state.host, traceEnabled = state.traceEnabled;
30157         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
30158         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
30159         if (directoryExists && host.fileExists(packageJsonPath)) {
30160             var packageJsonContent = ts.readJson(packageJsonPath, host);
30161             if (traceEnabled) {
30162                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
30163             }
30164             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
30165             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
30166         }
30167         else {
30168             if (directoryExists && traceEnabled) {
30169                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
30170             }
30171             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
30172             state.failedLookupLocations.push(packageJsonPath);
30173         }
30174     }
30175     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
30176         var packageFile;
30177         if (jsonContent) {
30178             switch (extensions) {
30179                 case Extensions.JavaScript:
30180                 case Extensions.Json:
30181                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
30182                     break;
30183                 case Extensions.TypeScript:
30184                     // When resolving typescript modules, try resolving using main field as well
30185                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
30186                     break;
30187                 case Extensions.DtsOnly:
30188                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
30189                     break;
30190                 case Extensions.TSConfig:
30191                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
30192                     break;
30193                 default:
30194                     return ts.Debug.assertNever(extensions);
30195             }
30196         }
30197         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30198             var fromFile = tryFile(candidate, onlyRecordFailures, state);
30199             if (fromFile) {
30200                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
30201                 if (resolved) {
30202                     return noPackageId(resolved);
30203                 }
30204                 if (state.traceEnabled) {
30205                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
30206                 }
30207             }
30208             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
30209             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
30210             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
30211             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
30212         };
30213         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
30214         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
30215         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
30216         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
30217             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
30218             if (state.traceEnabled) {
30219                 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);
30220             }
30221             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
30222             if (result) {
30223                 return removeIgnoredPackageId(result.value);
30224             }
30225         }
30226         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
30227         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
30228         if (packageFileResult)
30229             return packageFileResult;
30230         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
30231     }
30232     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
30233     function resolvedIfExtensionMatches(extensions, path) {
30234         var ext = ts.tryGetExtensionFromPath(path);
30235         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
30236     }
30237     /** True if `extension` is one of the supported `extensions`. */
30238     function extensionIsOk(extensions, extension) {
30239         switch (extensions) {
30240             case Extensions.JavaScript:
30241                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
30242             case Extensions.TSConfig:
30243             case Extensions.Json:
30244                 return extension === ".json" /* Json */;
30245             case Extensions.TypeScript:
30246                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
30247             case Extensions.DtsOnly:
30248                 return extension === ".d.ts" /* Dts */;
30249         }
30250     }
30251     /* @internal */
30252     function parsePackageName(moduleName) {
30253         var idx = moduleName.indexOf(ts.directorySeparator);
30254         if (moduleName[0] === "@") {
30255             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
30256         }
30257         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
30258     }
30259     ts.parsePackageName = parsePackageName;
30260     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
30261         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
30262     }
30263     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
30264         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
30265         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
30266     }
30267     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
30268         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30269         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
30270             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
30271                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
30272                 if (resolutionFromCache) {
30273                     return resolutionFromCache;
30274                 }
30275                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
30276             }
30277         });
30278     }
30279     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
30280         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
30281         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
30282         if (!nodeModulesFolderExists && state.traceEnabled) {
30283             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
30284         }
30285         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
30286         if (packageResult) {
30287             return packageResult;
30288         }
30289         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
30290             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
30291             var nodeModulesAtTypesExists = nodeModulesFolderExists;
30292             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
30293                 if (state.traceEnabled) {
30294                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
30295                 }
30296                 nodeModulesAtTypesExists = false;
30297             }
30298             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
30299         }
30300     }
30301     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
30302         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
30303         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
30304         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
30305         if (packageInfo) {
30306             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
30307             if (fromFile) {
30308                 return noPackageId(fromFile);
30309             }
30310             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
30311             return withPackageId(packageInfo, fromDirectory);
30312         }
30313         var loader = function (extensions, candidate, onlyRecordFailures, state) {
30314             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
30315                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
30316             return withPackageId(packageInfo, pathAndExtension);
30317         };
30318         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
30319         if (rest !== "") { // If "rest" is empty, we just did this search above.
30320             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
30321             // 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.
30322             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
30323             if (packageInfo && packageInfo.versionPaths) {
30324                 if (state.traceEnabled) {
30325                     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);
30326                 }
30327                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
30328                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
30329                 if (fromPaths) {
30330                     return fromPaths.value;
30331                 }
30332             }
30333         }
30334         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
30335     }
30336     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
30337         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
30338         if (matchedPattern) {
30339             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
30340             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
30341             if (state.traceEnabled) {
30342                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
30343             }
30344             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
30345                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
30346                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
30347                 if (state.traceEnabled) {
30348                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
30349                 }
30350                 // A path mapping may have an extension, in contrast to an import, which should omit it.
30351                 var extension = ts.tryGetExtensionFromPath(candidate);
30352                 if (extension !== undefined) {
30353                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
30354                     if (path_1 !== undefined) {
30355                         return noPackageId({ path: path_1, ext: extension });
30356                     }
30357                 }
30358                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
30359             });
30360             return { value: resolved };
30361         }
30362     }
30363     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
30364     var mangledScopedPackageSeparator = "__";
30365     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
30366     function mangleScopedPackageNameWithTrace(packageName, state) {
30367         var mangled = mangleScopedPackageName(packageName);
30368         if (state.traceEnabled && mangled !== packageName) {
30369             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
30370         }
30371         return mangled;
30372     }
30373     /* @internal */
30374     function getTypesPackageName(packageName) {
30375         return "@types/" + mangleScopedPackageName(packageName);
30376     }
30377     ts.getTypesPackageName = getTypesPackageName;
30378     /* @internal */
30379     function mangleScopedPackageName(packageName) {
30380         if (ts.startsWith(packageName, "@")) {
30381             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
30382             if (replaceSlash !== packageName) {
30383                 return replaceSlash.slice(1); // Take off the "@"
30384             }
30385         }
30386         return packageName;
30387     }
30388     ts.mangleScopedPackageName = mangleScopedPackageName;
30389     /* @internal */
30390     function getPackageNameFromTypesPackageName(mangledName) {
30391         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
30392         if (withoutAtTypePrefix !== mangledName) {
30393             return unmangleScopedPackageName(withoutAtTypePrefix);
30394         }
30395         return mangledName;
30396     }
30397     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
30398     /* @internal */
30399     function unmangleScopedPackageName(typesPackageName) {
30400         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
30401             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
30402             typesPackageName;
30403     }
30404     ts.unmangleScopedPackageName = unmangleScopedPackageName;
30405     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
30406         var result = cache && cache.get(containingDirectory);
30407         if (result) {
30408             if (state.traceEnabled) {
30409                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
30410             }
30411             state.resultFromCache = result;
30412             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
30413         }
30414     }
30415     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
30416         var traceEnabled = isTraceEnabled(compilerOptions, host);
30417         var failedLookupLocations = [];
30418         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30419         var containingDirectory = ts.getDirectoryPath(containingFile);
30420         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
30421         // No originalPath because classic resolution doesn't resolve realPath
30422         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
30423         function tryResolve(extensions) {
30424             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
30425             if (resolvedUsingSettings) {
30426                 return { value: resolvedUsingSettings };
30427             }
30428             if (!ts.isExternalModuleNameRelative(moduleName)) {
30429                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
30430                 // Climb up parent directories looking for a module.
30431                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
30432                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
30433                     if (resolutionFromCache) {
30434                         return resolutionFromCache;
30435                     }
30436                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
30437                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
30438                 });
30439                 if (resolved_3) {
30440                     return resolved_3;
30441                 }
30442                 if (extensions === Extensions.TypeScript) {
30443                     // If we didn't find the file normally, look it up in @types.
30444                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
30445                 }
30446             }
30447             else {
30448                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
30449                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
30450             }
30451         }
30452     }
30453     ts.classicNameResolver = classicNameResolver;
30454     /**
30455      * A host may load a module from a global cache of typings.
30456      * This is the minumum code needed to expose that functionality; the rest is in the host.
30457      */
30458     /* @internal */
30459     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
30460         var traceEnabled = isTraceEnabled(compilerOptions, host);
30461         if (traceEnabled) {
30462             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);
30463         }
30464         var failedLookupLocations = [];
30465         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
30466         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
30467         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
30468     }
30469     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
30470     /**
30471      * Wraps value to SearchResult.
30472      * @returns undefined if value is undefined or { value } otherwise
30473      */
30474     function toSearchResult(value) {
30475         return value !== undefined ? { value: value } : undefined;
30476     }
30477 })(ts || (ts = {}));
30478 /* @internal */
30479 var ts;
30480 (function (ts) {
30481     var ModuleInstanceState;
30482     (function (ModuleInstanceState) {
30483         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
30484         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
30485         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
30486     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
30487     function getModuleInstanceState(node, visited) {
30488         if (node.body && !node.body.parent) {
30489             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
30490             setParentPointers(node, node.body);
30491         }
30492         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
30493     }
30494     ts.getModuleInstanceState = getModuleInstanceState;
30495     function getModuleInstanceStateCached(node, visited) {
30496         if (visited === void 0) { visited = ts.createMap(); }
30497         var nodeId = "" + ts.getNodeId(node);
30498         if (visited.has(nodeId)) {
30499             return visited.get(nodeId) || 0 /* NonInstantiated */;
30500         }
30501         visited.set(nodeId, undefined);
30502         var result = getModuleInstanceStateWorker(node, visited);
30503         visited.set(nodeId, result);
30504         return result;
30505     }
30506     function getModuleInstanceStateWorker(node, visited) {
30507         // A module is uninstantiated if it contains only
30508         switch (node.kind) {
30509             // 1. interface declarations, type alias declarations
30510             case 246 /* InterfaceDeclaration */:
30511             case 247 /* TypeAliasDeclaration */:
30512                 return 0 /* NonInstantiated */;
30513             // 2. const enum declarations
30514             case 248 /* EnumDeclaration */:
30515                 if (ts.isEnumConst(node)) {
30516                     return 2 /* ConstEnumOnly */;
30517                 }
30518                 break;
30519             // 3. non-exported import declarations
30520             case 254 /* ImportDeclaration */:
30521             case 253 /* ImportEqualsDeclaration */:
30522                 if (!(ts.hasModifier(node, 1 /* Export */))) {
30523                     return 0 /* NonInstantiated */;
30524                 }
30525                 break;
30526             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
30527             case 260 /* ExportDeclaration */:
30528                 var exportDeclaration = node;
30529                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 261 /* NamedExports */) {
30530                     var state = 0 /* NonInstantiated */;
30531                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
30532                         var specifier = _a[_i];
30533                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
30534                         if (specifierState > state) {
30535                             state = specifierState;
30536                         }
30537                         if (state === 1 /* Instantiated */) {
30538                             return state;
30539                         }
30540                     }
30541                     return state;
30542                 }
30543                 break;
30544             // 5. other uninstantiated module declarations.
30545             case 250 /* ModuleBlock */: {
30546                 var state_1 = 0 /* NonInstantiated */;
30547                 ts.forEachChild(node, function (n) {
30548                     var childState = getModuleInstanceStateCached(n, visited);
30549                     switch (childState) {
30550                         case 0 /* NonInstantiated */:
30551                             // child is non-instantiated - continue searching
30552                             return;
30553                         case 2 /* ConstEnumOnly */:
30554                             // child is const enum only - record state and continue searching
30555                             state_1 = 2 /* ConstEnumOnly */;
30556                             return;
30557                         case 1 /* Instantiated */:
30558                             // child is instantiated - record state and stop
30559                             state_1 = 1 /* Instantiated */;
30560                             return true;
30561                         default:
30562                             ts.Debug.assertNever(childState);
30563                     }
30564                 });
30565                 return state_1;
30566             }
30567             case 249 /* ModuleDeclaration */:
30568                 return getModuleInstanceState(node, visited);
30569             case 75 /* Identifier */:
30570                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
30571                 // be considered the same as type alias
30572                 if (node.isInJSDocNamespace) {
30573                     return 0 /* NonInstantiated */;
30574                 }
30575         }
30576         return 1 /* Instantiated */;
30577     }
30578     function getModuleInstanceStateForAliasTarget(specifier, visited) {
30579         var name = specifier.propertyName || specifier.name;
30580         var p = specifier.parent;
30581         while (p) {
30582             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
30583                 var statements = p.statements;
30584                 var found = void 0;
30585                 for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
30586                     var statement = statements_1[_i];
30587                     if (ts.nodeHasName(statement, name)) {
30588                         if (!statement.parent) {
30589                             setParentPointers(p, statement);
30590                         }
30591                         var state = getModuleInstanceStateCached(statement, visited);
30592                         if (found === undefined || state > found) {
30593                             found = state;
30594                         }
30595                         if (found === 1 /* Instantiated */) {
30596                             return found;
30597                         }
30598                     }
30599                 }
30600                 if (found !== undefined) {
30601                     return found;
30602                 }
30603             }
30604             p = p.parent;
30605         }
30606         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
30607     }
30608     var ContainerFlags;
30609     (function (ContainerFlags) {
30610         // The current node is not a container, and no container manipulation should happen before
30611         // recursing into it.
30612         ContainerFlags[ContainerFlags["None"] = 0] = "None";
30613         // The current node is a container.  It should be set as the current container (and block-
30614         // container) before recursing into it.  The current node does not have locals.  Examples:
30615         //
30616         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
30617         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
30618         // The current node is a block-scoped-container.  It should be set as the current block-
30619         // container before recursing into it.  Examples:
30620         //
30621         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
30622         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
30623         // The current node is the container of a control flow path. The current control flow should
30624         // be saved and restored, and a new control flow initialized within the container.
30625         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
30626         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
30627         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
30628         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
30629         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
30630         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
30631     })(ContainerFlags || (ContainerFlags = {}));
30632     function initFlowNode(node) {
30633         ts.Debug.attachFlowNodeDebugInfo(node);
30634         return node;
30635     }
30636     var binder = createBinder();
30637     function bindSourceFile(file, options) {
30638         ts.performance.mark("beforeBind");
30639         ts.perfLogger.logStartBindFile("" + file.fileName);
30640         binder(file, options);
30641         ts.perfLogger.logStopBindFile();
30642         ts.performance.mark("afterBind");
30643         ts.performance.measure("Bind", "beforeBind", "afterBind");
30644     }
30645     ts.bindSourceFile = bindSourceFile;
30646     function createBinder() {
30647         var file;
30648         var options;
30649         var languageVersion;
30650         var parent;
30651         var container;
30652         var thisParentContainer; // Container one level up
30653         var blockScopeContainer;
30654         var lastContainer;
30655         var delayedTypeAliases;
30656         var seenThisKeyword;
30657         // state used by control flow analysis
30658         var currentFlow;
30659         var currentBreakTarget;
30660         var currentContinueTarget;
30661         var currentReturnTarget;
30662         var currentTrueTarget;
30663         var currentFalseTarget;
30664         var currentExceptionTarget;
30665         var preSwitchCaseFlow;
30666         var activeLabelList;
30667         var hasExplicitReturn;
30668         // state used for emit helpers
30669         var emitFlags;
30670         // If this file is an external module, then it is automatically in strict-mode according to
30671         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
30672         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
30673         // or if compiler options contain alwaysStrict.
30674         var inStrictMode;
30675         var symbolCount = 0;
30676         var Symbol;
30677         var classifiableNames;
30678         var unreachableFlow = { flags: 1 /* Unreachable */ };
30679         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
30680         // state used to aggregate transform flags during bind.
30681         var subtreeTransformFlags = 0 /* None */;
30682         var skipTransformFlagAggregation;
30683         /**
30684          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
30685          * 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)
30686          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
30687          */
30688         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
30689             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
30690         }
30691         function bindSourceFile(f, opts) {
30692             file = f;
30693             options = opts;
30694             languageVersion = ts.getEmitScriptTarget(options);
30695             inStrictMode = bindInStrictMode(file, opts);
30696             classifiableNames = ts.createUnderscoreEscapedMap();
30697             symbolCount = 0;
30698             skipTransformFlagAggregation = file.isDeclarationFile;
30699             Symbol = ts.objectAllocator.getSymbolConstructor();
30700             // Attach debugging information if necessary
30701             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
30702             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
30703             if (!file.locals) {
30704                 bind(file);
30705                 file.symbolCount = symbolCount;
30706                 file.classifiableNames = classifiableNames;
30707                 delayedBindJSDocTypedefTag();
30708             }
30709             file = undefined;
30710             options = undefined;
30711             languageVersion = undefined;
30712             parent = undefined;
30713             container = undefined;
30714             thisParentContainer = undefined;
30715             blockScopeContainer = undefined;
30716             lastContainer = undefined;
30717             delayedTypeAliases = undefined;
30718             seenThisKeyword = false;
30719             currentFlow = undefined;
30720             currentBreakTarget = undefined;
30721             currentContinueTarget = undefined;
30722             currentReturnTarget = undefined;
30723             currentTrueTarget = undefined;
30724             currentFalseTarget = undefined;
30725             currentExceptionTarget = undefined;
30726             activeLabelList = undefined;
30727             hasExplicitReturn = false;
30728             emitFlags = 0 /* None */;
30729             subtreeTransformFlags = 0 /* None */;
30730         }
30731         return bindSourceFile;
30732         function bindInStrictMode(file, opts) {
30733             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
30734                 // bind in strict mode source files with alwaysStrict option
30735                 return true;
30736             }
30737             else {
30738                 return !!file.externalModuleIndicator;
30739             }
30740         }
30741         function createSymbol(flags, name) {
30742             symbolCount++;
30743             return new Symbol(flags, name);
30744         }
30745         function addDeclarationToSymbol(symbol, node, symbolFlags) {
30746             symbol.flags |= symbolFlags;
30747             node.symbol = symbol;
30748             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
30749             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
30750                 symbol.exports = ts.createSymbolTable();
30751             }
30752             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
30753                 symbol.members = ts.createSymbolTable();
30754             }
30755             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
30756             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
30757                 symbol.constEnumOnlyModule = false;
30758             }
30759             if (symbolFlags & 111551 /* Value */) {
30760                 ts.setValueDeclaration(symbol, node);
30761             }
30762         }
30763         // Should not be called on a declaration with a computed property name,
30764         // unless it is a well known Symbol.
30765         function getDeclarationName(node) {
30766             if (node.kind === 259 /* ExportAssignment */) {
30767                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
30768             }
30769             var name = ts.getNameOfDeclaration(node);
30770             if (name) {
30771                 if (ts.isAmbientModule(node)) {
30772                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
30773                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
30774                 }
30775                 if (name.kind === 154 /* ComputedPropertyName */) {
30776                     var nameExpression = name.expression;
30777                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
30778                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
30779                         return ts.escapeLeadingUnderscores(nameExpression.text);
30780                     }
30781                     if (ts.isSignedNumericLiteral(nameExpression)) {
30782                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
30783                     }
30784                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
30785                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
30786                 }
30787                 if (ts.isWellKnownSymbolSyntactically(name)) {
30788                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
30789                 }
30790                 if (ts.isPrivateIdentifier(name)) {
30791                     // containingClass exists because private names only allowed inside classes
30792                     var containingClass = ts.getContainingClass(node);
30793                     if (!containingClass) {
30794                         // we can get here in cases where there is already a parse error.
30795                         return undefined;
30796                     }
30797                     var containingClassSymbol = containingClass.symbol;
30798                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
30799                 }
30800                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
30801             }
30802             switch (node.kind) {
30803                 case 162 /* Constructor */:
30804                     return "__constructor" /* Constructor */;
30805                 case 170 /* FunctionType */:
30806                 case 165 /* CallSignature */:
30807                 case 305 /* JSDocSignature */:
30808                     return "__call" /* Call */;
30809                 case 171 /* ConstructorType */:
30810                 case 166 /* ConstructSignature */:
30811                     return "__new" /* New */;
30812                 case 167 /* IndexSignature */:
30813                     return "__index" /* Index */;
30814                 case 260 /* ExportDeclaration */:
30815                     return "__export" /* ExportStar */;
30816                 case 290 /* SourceFile */:
30817                     // json file should behave as
30818                     // module.exports = ...
30819                     return "export=" /* ExportEquals */;
30820                 case 209 /* BinaryExpression */:
30821                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
30822                         // module.exports = ...
30823                         return "export=" /* ExportEquals */;
30824                     }
30825                     ts.Debug.fail("Unknown binary declaration kind");
30826                     break;
30827                 case 300 /* JSDocFunctionType */:
30828                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
30829                 case 156 /* Parameter */:
30830                     // Parameters with names are handled at the top of this function.  Parameters
30831                     // without names can only come from JSDocFunctionTypes.
30832                     ts.Debug.assert(node.parent.kind === 300 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
30833                     var functionType = node.parent;
30834                     var index = functionType.parameters.indexOf(node);
30835                     return "arg" + index;
30836             }
30837         }
30838         function getDisplayName(node) {
30839             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
30840         }
30841         /**
30842          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
30843          * @param symbolTable - The symbol table which node will be added to.
30844          * @param parent - node's parent declaration.
30845          * @param node - The declaration to be added to the symbol table
30846          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
30847          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
30848          */
30849         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
30850             ts.Debug.assert(!ts.hasDynamicName(node));
30851             var isDefaultExport = ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
30852             // The exported symbol for an export default function/class node is always named "default"
30853             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
30854             var symbol;
30855             if (name === undefined) {
30856                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
30857             }
30858             else {
30859                 // Check and see if the symbol table already has a symbol with this name.  If not,
30860                 // create a new symbol with this name and add it to the table.  Note that we don't
30861                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
30862                 // with the 'excludes' flags we pass in.
30863                 //
30864                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
30865                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
30866                 // the same symbol table.  If we have a conflict, report the issue on each
30867                 // declaration we have for this symbol, and then create a new symbol for this
30868                 // declaration.
30869                 //
30870                 // Note that when properties declared in Javascript constructors
30871                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
30872                 // Always. This allows the common Javascript pattern of overwriting a prototype method
30873                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
30874                 //
30875                 // If we created a new symbol, either because we didn't have a symbol with this name
30876                 // in the symbol table, or we conflicted with an existing symbol, then just add this
30877                 // node as the sole declaration of the new symbol.
30878                 //
30879                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
30880                 // you have multiple 'vars' with the same name in the same container).  In this case
30881                 // just add this node into the declarations list of the symbol.
30882                 symbol = symbolTable.get(name);
30883                 if (includes & 2885600 /* Classifiable */) {
30884                     classifiableNames.set(name, true);
30885                 }
30886                 if (!symbol) {
30887                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30888                     if (isReplaceableByMethod)
30889                         symbol.isReplaceableByMethod = true;
30890                 }
30891                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
30892                     // A symbol already exists, so don't add this as a declaration.
30893                     return symbol;
30894                 }
30895                 else if (symbol.flags & excludes) {
30896                     if (symbol.isReplaceableByMethod) {
30897                         // Javascript constructor-declared symbols can be discarded in favor of
30898                         // prototype symbols like methods.
30899                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
30900                     }
30901                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
30902                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
30903                         if (ts.isNamedDeclaration(node)) {
30904                             node.name.parent = node;
30905                         }
30906                         // Report errors every position with duplicate declaration
30907                         // Report errors on previous encountered declarations
30908                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
30909                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
30910                             : ts.Diagnostics.Duplicate_identifier_0;
30911                         var messageNeedsName_1 = true;
30912                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
30913                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
30914                             messageNeedsName_1 = false;
30915                         }
30916                         var multipleDefaultExports_1 = false;
30917                         if (ts.length(symbol.declarations)) {
30918                             // If the current node is a default export of some sort, then check if
30919                             // there are any other default exports that we need to error on.
30920                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
30921                             if (isDefaultExport) {
30922                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30923                                 messageNeedsName_1 = false;
30924                                 multipleDefaultExports_1 = true;
30925                             }
30926                             else {
30927                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
30928                                 // Error on multiple export default in the following case:
30929                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
30930                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
30931                                 if (symbol.declarations && symbol.declarations.length &&
30932                                     (node.kind === 259 /* ExportAssignment */ && !node.isExportEquals)) {
30933                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
30934                                     messageNeedsName_1 = false;
30935                                     multipleDefaultExports_1 = true;
30936                                 }
30937                             }
30938                         }
30939                         var relatedInformation_1 = [];
30940                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
30941                             // export type T; - may have meant export type { T }?
30942                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
30943                         }
30944                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
30945                         ts.forEach(symbol.declarations, function (declaration, index) {
30946                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
30947                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
30948                             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);
30949                             if (multipleDefaultExports_1) {
30950                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
30951                             }
30952                         });
30953                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
30954                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
30955                         symbol = createSymbol(0 /* None */, name);
30956                     }
30957                 }
30958             }
30959             addDeclarationToSymbol(symbol, node, includes);
30960             if (symbol.parent) {
30961                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
30962             }
30963             else {
30964                 symbol.parent = parent;
30965             }
30966             return symbol;
30967         }
30968         function declareModuleMember(node, symbolFlags, symbolExcludes) {
30969             var hasExportModifier = ts.getCombinedModifierFlags(node) & 1 /* Export */;
30970             if (symbolFlags & 2097152 /* Alias */) {
30971                 if (node.kind === 263 /* ExportSpecifier */ || (node.kind === 253 /* ImportEqualsDeclaration */ && hasExportModifier)) {
30972                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
30973                 }
30974                 else {
30975                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
30976                 }
30977             }
30978             else {
30979                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
30980                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
30981                 //
30982                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
30983                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
30984                 //      with the same name in the same container.
30985                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
30986                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
30987                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
30988                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
30989                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
30990                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
30991                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
30992                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
30993                 if (ts.isJSDocTypeAlias(node))
30994                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
30995                 if ((!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) || ts.isJSDocTypeAlias(node)) {
30996                     if (!container.locals || (ts.hasModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
30997                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
30998                     }
30999                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
31000                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
31001                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
31002                     node.localSymbol = local;
31003                     return local;
31004                 }
31005                 else {
31006                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
31007                 }
31008             }
31009         }
31010         // All container nodes are kept on a linked list in declaration order. This list is used by
31011         // the getLocalNameOfContainer function in the type checker to validate that the local name
31012         // used for a container is unique.
31013         function bindContainer(node, containerFlags) {
31014             // Before we recurse into a node's children, we first save the existing parent, container
31015             // and block-container.  Then after we pop out of processing the children, we restore
31016             // these saved values.
31017             var saveContainer = container;
31018             var saveThisParentContainer = thisParentContainer;
31019             var savedBlockScopeContainer = blockScopeContainer;
31020             // Depending on what kind of node this is, we may have to adjust the current container
31021             // and block-container.   If the current node is a container, then it is automatically
31022             // considered the current block-container as well.  Also, for containers that we know
31023             // may contain locals, we eagerly initialize the .locals field. We do this because
31024             // it's highly likely that the .locals will be needed to place some child in (for example,
31025             // a parameter, or variable declaration).
31026             //
31027             // However, we do not proactively create the .locals for block-containers because it's
31028             // totally normal and common for block-containers to never actually have a block-scoped
31029             // variable in them.  We don't want to end up allocating an object for every 'block' we
31030             // run into when most of them won't be necessary.
31031             //
31032             // Finally, if this is a block-container, then we clear out any existing .locals object
31033             // it may contain within it.  This happens in incremental scenarios.  Because we can be
31034             // reusing a node from a previous compilation, that node may have had 'locals' created
31035             // for it.  We must clear this so we don't accidentally move any stale data forward from
31036             // a previous compilation.
31037             if (containerFlags & 1 /* IsContainer */) {
31038                 if (node.kind !== 202 /* ArrowFunction */) {
31039                     thisParentContainer = container;
31040                 }
31041                 container = blockScopeContainer = node;
31042                 if (containerFlags & 32 /* HasLocals */) {
31043                     container.locals = ts.createSymbolTable();
31044                 }
31045                 addToContainerChain(container);
31046             }
31047             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
31048                 blockScopeContainer = node;
31049                 blockScopeContainer.locals = undefined;
31050             }
31051             if (containerFlags & 4 /* IsControlFlowContainer */) {
31052                 var saveCurrentFlow = currentFlow;
31053                 var saveBreakTarget = currentBreakTarget;
31054                 var saveContinueTarget = currentContinueTarget;
31055                 var saveReturnTarget = currentReturnTarget;
31056                 var saveExceptionTarget = currentExceptionTarget;
31057                 var saveActiveLabelList = activeLabelList;
31058                 var saveHasExplicitReturn = hasExplicitReturn;
31059                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasModifier(node, 256 /* Async */) &&
31060                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
31061                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
31062                 // similarly to break statements that exit to a label just past the statement body.
31063                 if (!isIIFE) {
31064                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
31065                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
31066                         currentFlow.node = node;
31067                     }
31068                 }
31069                 // We create a return control flow graph for IIFEs and constructors. For constructors
31070                 // we use the return control flow graph in strict property initialization checks.
31071                 currentReturnTarget = isIIFE || node.kind === 162 /* Constructor */ ? createBranchLabel() : undefined;
31072                 currentExceptionTarget = undefined;
31073                 currentBreakTarget = undefined;
31074                 currentContinueTarget = undefined;
31075                 activeLabelList = undefined;
31076                 hasExplicitReturn = false;
31077                 bindChildren(node);
31078                 // Reset all reachability check related flags on node (for incremental scenarios)
31079                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
31080                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
31081                     node.flags |= 256 /* HasImplicitReturn */;
31082                     if (hasExplicitReturn)
31083                         node.flags |= 512 /* HasExplicitReturn */;
31084                     node.endFlowNode = currentFlow;
31085                 }
31086                 if (node.kind === 290 /* SourceFile */) {
31087                     node.flags |= emitFlags;
31088                 }
31089                 if (currentReturnTarget) {
31090                     addAntecedent(currentReturnTarget, currentFlow);
31091                     currentFlow = finishFlowLabel(currentReturnTarget);
31092                     if (node.kind === 162 /* Constructor */) {
31093                         node.returnFlowNode = currentFlow;
31094                     }
31095                 }
31096                 if (!isIIFE) {
31097                     currentFlow = saveCurrentFlow;
31098                 }
31099                 currentBreakTarget = saveBreakTarget;
31100                 currentContinueTarget = saveContinueTarget;
31101                 currentReturnTarget = saveReturnTarget;
31102                 currentExceptionTarget = saveExceptionTarget;
31103                 activeLabelList = saveActiveLabelList;
31104                 hasExplicitReturn = saveHasExplicitReturn;
31105             }
31106             else if (containerFlags & 64 /* IsInterface */) {
31107                 seenThisKeyword = false;
31108                 bindChildren(node);
31109                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
31110             }
31111             else {
31112                 bindChildren(node);
31113             }
31114             container = saveContainer;
31115             thisParentContainer = saveThisParentContainer;
31116             blockScopeContainer = savedBlockScopeContainer;
31117         }
31118         function bindChildren(node) {
31119             if (skipTransformFlagAggregation) {
31120                 bindChildrenWorker(node);
31121             }
31122             else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31123                 skipTransformFlagAggregation = true;
31124                 bindChildrenWorker(node);
31125                 skipTransformFlagAggregation = false;
31126                 subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31127             }
31128             else {
31129                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31130                 subtreeTransformFlags = 0;
31131                 bindChildrenWorker(node);
31132                 subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags);
31133             }
31134         }
31135         function bindEachFunctionsFirst(nodes) {
31136             bindEach(nodes, function (n) { return n.kind === 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31137             bindEach(nodes, function (n) { return n.kind !== 244 /* FunctionDeclaration */ ? bind(n) : undefined; });
31138         }
31139         function bindEach(nodes, bindFunction) {
31140             if (bindFunction === void 0) { bindFunction = bind; }
31141             if (nodes === undefined) {
31142                 return;
31143             }
31144             if (skipTransformFlagAggregation) {
31145                 ts.forEach(nodes, bindFunction);
31146             }
31147             else {
31148                 var savedSubtreeTransformFlags = subtreeTransformFlags;
31149                 subtreeTransformFlags = 0 /* None */;
31150                 var nodeArrayFlags = 0 /* None */;
31151                 for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
31152                     var node = nodes_2[_i];
31153                     bindFunction(node);
31154                     nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
31155                 }
31156                 nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
31157                 subtreeTransformFlags |= savedSubtreeTransformFlags;
31158             }
31159         }
31160         function bindEachChild(node) {
31161             ts.forEachChild(node, bind, bindEach);
31162         }
31163         function bindChildrenWorker(node) {
31164             if (checkUnreachable(node)) {
31165                 bindEachChild(node);
31166                 bindJSDoc(node);
31167                 return;
31168             }
31169             if (node.kind >= 225 /* FirstStatement */ && node.kind <= 241 /* LastStatement */ && !options.allowUnreachableCode) {
31170                 node.flowNode = currentFlow;
31171             }
31172             switch (node.kind) {
31173                 case 229 /* WhileStatement */:
31174                     bindWhileStatement(node);
31175                     break;
31176                 case 228 /* DoStatement */:
31177                     bindDoStatement(node);
31178                     break;
31179                 case 230 /* ForStatement */:
31180                     bindForStatement(node);
31181                     break;
31182                 case 231 /* ForInStatement */:
31183                 case 232 /* ForOfStatement */:
31184                     bindForInOrForOfStatement(node);
31185                     break;
31186                 case 227 /* IfStatement */:
31187                     bindIfStatement(node);
31188                     break;
31189                 case 235 /* ReturnStatement */:
31190                 case 239 /* ThrowStatement */:
31191                     bindReturnOrThrow(node);
31192                     break;
31193                 case 234 /* BreakStatement */:
31194                 case 233 /* ContinueStatement */:
31195                     bindBreakOrContinueStatement(node);
31196                     break;
31197                 case 240 /* TryStatement */:
31198                     bindTryStatement(node);
31199                     break;
31200                 case 237 /* SwitchStatement */:
31201                     bindSwitchStatement(node);
31202                     break;
31203                 case 251 /* CaseBlock */:
31204                     bindCaseBlock(node);
31205                     break;
31206                 case 277 /* CaseClause */:
31207                     bindCaseClause(node);
31208                     break;
31209                 case 226 /* ExpressionStatement */:
31210                     bindExpressionStatement(node);
31211                     break;
31212                 case 238 /* LabeledStatement */:
31213                     bindLabeledStatement(node);
31214                     break;
31215                 case 207 /* PrefixUnaryExpression */:
31216                     bindPrefixUnaryExpressionFlow(node);
31217                     break;
31218                 case 208 /* PostfixUnaryExpression */:
31219                     bindPostfixUnaryExpressionFlow(node);
31220                     break;
31221                 case 209 /* BinaryExpression */:
31222                     bindBinaryExpressionFlow(node);
31223                     break;
31224                 case 203 /* DeleteExpression */:
31225                     bindDeleteExpressionFlow(node);
31226                     break;
31227                 case 210 /* ConditionalExpression */:
31228                     bindConditionalExpressionFlow(node);
31229                     break;
31230                 case 242 /* VariableDeclaration */:
31231                     bindVariableDeclarationFlow(node);
31232                     break;
31233                 case 194 /* PropertyAccessExpression */:
31234                 case 195 /* ElementAccessExpression */:
31235                     bindAccessExpressionFlow(node);
31236                     break;
31237                 case 196 /* CallExpression */:
31238                     bindCallExpressionFlow(node);
31239                     break;
31240                 case 218 /* NonNullExpression */:
31241                     bindNonNullExpressionFlow(node);
31242                     break;
31243                 case 322 /* JSDocTypedefTag */:
31244                 case 315 /* JSDocCallbackTag */:
31245                 case 316 /* JSDocEnumTag */:
31246                     bindJSDocTypeAlias(node);
31247                     break;
31248                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
31249                 case 290 /* SourceFile */: {
31250                     bindEachFunctionsFirst(node.statements);
31251                     bind(node.endOfFileToken);
31252                     break;
31253                 }
31254                 case 223 /* Block */:
31255                 case 250 /* ModuleBlock */:
31256                     bindEachFunctionsFirst(node.statements);
31257                     break;
31258                 default:
31259                     bindEachChild(node);
31260                     break;
31261             }
31262             bindJSDoc(node);
31263         }
31264         function isNarrowingExpression(expr) {
31265             switch (expr.kind) {
31266                 case 75 /* Identifier */:
31267                 case 104 /* ThisKeyword */:
31268                 case 194 /* PropertyAccessExpression */:
31269                 case 195 /* ElementAccessExpression */:
31270                     return containsNarrowableReference(expr);
31271                 case 196 /* CallExpression */:
31272                     return hasNarrowableArgument(expr);
31273                 case 200 /* ParenthesizedExpression */:
31274                     return isNarrowingExpression(expr.expression);
31275                 case 209 /* BinaryExpression */:
31276                     return isNarrowingBinaryExpression(expr);
31277                 case 207 /* PrefixUnaryExpression */:
31278                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
31279                 case 204 /* TypeOfExpression */:
31280                     return isNarrowingExpression(expr.expression);
31281             }
31282             return false;
31283         }
31284         function isNarrowableReference(expr) {
31285             return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ ||
31286                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
31287                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression);
31288         }
31289         function containsNarrowableReference(expr) {
31290             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
31291         }
31292         function hasNarrowableArgument(expr) {
31293             if (expr.arguments) {
31294                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
31295                     var argument = _a[_i];
31296                     if (containsNarrowableReference(argument)) {
31297                         return true;
31298                     }
31299                 }
31300             }
31301             if (expr.expression.kind === 194 /* PropertyAccessExpression */ &&
31302                 containsNarrowableReference(expr.expression.expression)) {
31303                 return true;
31304             }
31305             return false;
31306         }
31307         function isNarrowingTypeofOperands(expr1, expr2) {
31308             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
31309         }
31310         function isNarrowableInOperands(left, right) {
31311             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
31312         }
31313         function isNarrowingBinaryExpression(expr) {
31314             switch (expr.operatorToken.kind) {
31315                 case 62 /* EqualsToken */:
31316                     return containsNarrowableReference(expr.left);
31317                 case 34 /* EqualsEqualsToken */:
31318                 case 35 /* ExclamationEqualsToken */:
31319                 case 36 /* EqualsEqualsEqualsToken */:
31320                 case 37 /* ExclamationEqualsEqualsToken */:
31321                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
31322                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
31323                 case 98 /* InstanceOfKeyword */:
31324                     return isNarrowableOperand(expr.left);
31325                 case 97 /* InKeyword */:
31326                     return isNarrowableInOperands(expr.left, expr.right);
31327                 case 27 /* CommaToken */:
31328                     return isNarrowingExpression(expr.right);
31329             }
31330             return false;
31331         }
31332         function isNarrowableOperand(expr) {
31333             switch (expr.kind) {
31334                 case 200 /* ParenthesizedExpression */:
31335                     return isNarrowableOperand(expr.expression);
31336                 case 209 /* BinaryExpression */:
31337                     switch (expr.operatorToken.kind) {
31338                         case 62 /* EqualsToken */:
31339                             return isNarrowableOperand(expr.left);
31340                         case 27 /* CommaToken */:
31341                             return isNarrowableOperand(expr.right);
31342                     }
31343             }
31344             return containsNarrowableReference(expr);
31345         }
31346         function createBranchLabel() {
31347             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
31348         }
31349         function createLoopLabel() {
31350             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
31351         }
31352         function createReduceLabel(target, antecedents, antecedent) {
31353             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
31354         }
31355         function setFlowNodeReferenced(flow) {
31356             // On first reference we set the Referenced flag, thereafter we set the Shared flag
31357             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
31358         }
31359         function addAntecedent(label, antecedent) {
31360             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
31361                 (label.antecedents || (label.antecedents = [])).push(antecedent);
31362                 setFlowNodeReferenced(antecedent);
31363             }
31364         }
31365         function createFlowCondition(flags, antecedent, expression) {
31366             if (antecedent.flags & 1 /* Unreachable */) {
31367                 return antecedent;
31368             }
31369             if (!expression) {
31370                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
31371             }
31372             if ((expression.kind === 106 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
31373                 expression.kind === 91 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
31374                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
31375                 return unreachableFlow;
31376             }
31377             if (!isNarrowingExpression(expression)) {
31378                 return antecedent;
31379             }
31380             setFlowNodeReferenced(antecedent);
31381             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
31382         }
31383         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
31384             setFlowNodeReferenced(antecedent);
31385             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
31386         }
31387         function createFlowMutation(flags, antecedent, node) {
31388             setFlowNodeReferenced(antecedent);
31389             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
31390             if (currentExceptionTarget) {
31391                 addAntecedent(currentExceptionTarget, result);
31392             }
31393             return result;
31394         }
31395         function createFlowCall(antecedent, node) {
31396             setFlowNodeReferenced(antecedent);
31397             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
31398         }
31399         function finishFlowLabel(flow) {
31400             var antecedents = flow.antecedents;
31401             if (!antecedents) {
31402                 return unreachableFlow;
31403             }
31404             if (antecedents.length === 1) {
31405                 return antecedents[0];
31406             }
31407             return flow;
31408         }
31409         function isStatementCondition(node) {
31410             var parent = node.parent;
31411             switch (parent.kind) {
31412                 case 227 /* IfStatement */:
31413                 case 229 /* WhileStatement */:
31414                 case 228 /* DoStatement */:
31415                     return parent.expression === node;
31416                 case 230 /* ForStatement */:
31417                 case 210 /* ConditionalExpression */:
31418                     return parent.condition === node;
31419             }
31420             return false;
31421         }
31422         function isLogicalExpression(node) {
31423             while (true) {
31424                 if (node.kind === 200 /* ParenthesizedExpression */) {
31425                     node = node.expression;
31426                 }
31427                 else if (node.kind === 207 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
31428                     node = node.operand;
31429                 }
31430                 else {
31431                     return node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
31432                         node.operatorToken.kind === 56 /* BarBarToken */ ||
31433                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
31434                 }
31435             }
31436         }
31437         function isTopLevelLogicalExpression(node) {
31438             while (ts.isParenthesizedExpression(node.parent) ||
31439                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
31440                 node = node.parent;
31441             }
31442             return !isStatementCondition(node) &&
31443                 !isLogicalExpression(node.parent) &&
31444                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
31445         }
31446         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
31447             var savedTrueTarget = currentTrueTarget;
31448             var savedFalseTarget = currentFalseTarget;
31449             currentTrueTarget = trueTarget;
31450             currentFalseTarget = falseTarget;
31451             action(value);
31452             currentTrueTarget = savedTrueTarget;
31453             currentFalseTarget = savedFalseTarget;
31454         }
31455         function bindCondition(node, trueTarget, falseTarget) {
31456             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
31457             if (!node || !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
31458                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
31459                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
31460             }
31461         }
31462         function bindIterativeStatement(node, breakTarget, continueTarget) {
31463             var saveBreakTarget = currentBreakTarget;
31464             var saveContinueTarget = currentContinueTarget;
31465             currentBreakTarget = breakTarget;
31466             currentContinueTarget = continueTarget;
31467             bind(node);
31468             currentBreakTarget = saveBreakTarget;
31469             currentContinueTarget = saveContinueTarget;
31470         }
31471         function setContinueTarget(node, target) {
31472             var label = activeLabelList;
31473             while (label && node.parent.kind === 238 /* LabeledStatement */) {
31474                 label.continueTarget = target;
31475                 label = label.next;
31476                 node = node.parent;
31477             }
31478             return target;
31479         }
31480         function bindWhileStatement(node) {
31481             var preWhileLabel = setContinueTarget(node, createLoopLabel());
31482             var preBodyLabel = createBranchLabel();
31483             var postWhileLabel = createBranchLabel();
31484             addAntecedent(preWhileLabel, currentFlow);
31485             currentFlow = preWhileLabel;
31486             bindCondition(node.expression, preBodyLabel, postWhileLabel);
31487             currentFlow = finishFlowLabel(preBodyLabel);
31488             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
31489             addAntecedent(preWhileLabel, currentFlow);
31490             currentFlow = finishFlowLabel(postWhileLabel);
31491         }
31492         function bindDoStatement(node) {
31493             var preDoLabel = createLoopLabel();
31494             var preConditionLabel = setContinueTarget(node, createBranchLabel());
31495             var postDoLabel = createBranchLabel();
31496             addAntecedent(preDoLabel, currentFlow);
31497             currentFlow = preDoLabel;
31498             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
31499             addAntecedent(preConditionLabel, currentFlow);
31500             currentFlow = finishFlowLabel(preConditionLabel);
31501             bindCondition(node.expression, preDoLabel, postDoLabel);
31502             currentFlow = finishFlowLabel(postDoLabel);
31503         }
31504         function bindForStatement(node) {
31505             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31506             var preBodyLabel = createBranchLabel();
31507             var postLoopLabel = createBranchLabel();
31508             bind(node.initializer);
31509             addAntecedent(preLoopLabel, currentFlow);
31510             currentFlow = preLoopLabel;
31511             bindCondition(node.condition, preBodyLabel, postLoopLabel);
31512             currentFlow = finishFlowLabel(preBodyLabel);
31513             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31514             bind(node.incrementor);
31515             addAntecedent(preLoopLabel, currentFlow);
31516             currentFlow = finishFlowLabel(postLoopLabel);
31517         }
31518         function bindForInOrForOfStatement(node) {
31519             var preLoopLabel = setContinueTarget(node, createLoopLabel());
31520             var postLoopLabel = createBranchLabel();
31521             bind(node.expression);
31522             addAntecedent(preLoopLabel, currentFlow);
31523             currentFlow = preLoopLabel;
31524             if (node.kind === 232 /* ForOfStatement */) {
31525                 bind(node.awaitModifier);
31526             }
31527             addAntecedent(postLoopLabel, currentFlow);
31528             bind(node.initializer);
31529             if (node.initializer.kind !== 243 /* VariableDeclarationList */) {
31530                 bindAssignmentTargetFlow(node.initializer);
31531             }
31532             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
31533             addAntecedent(preLoopLabel, currentFlow);
31534             currentFlow = finishFlowLabel(postLoopLabel);
31535         }
31536         function bindIfStatement(node) {
31537             var thenLabel = createBranchLabel();
31538             var elseLabel = createBranchLabel();
31539             var postIfLabel = createBranchLabel();
31540             bindCondition(node.expression, thenLabel, elseLabel);
31541             currentFlow = finishFlowLabel(thenLabel);
31542             bind(node.thenStatement);
31543             addAntecedent(postIfLabel, currentFlow);
31544             currentFlow = finishFlowLabel(elseLabel);
31545             bind(node.elseStatement);
31546             addAntecedent(postIfLabel, currentFlow);
31547             currentFlow = finishFlowLabel(postIfLabel);
31548         }
31549         function bindReturnOrThrow(node) {
31550             bind(node.expression);
31551             if (node.kind === 235 /* ReturnStatement */) {
31552                 hasExplicitReturn = true;
31553                 if (currentReturnTarget) {
31554                     addAntecedent(currentReturnTarget, currentFlow);
31555                 }
31556             }
31557             currentFlow = unreachableFlow;
31558         }
31559         function findActiveLabel(name) {
31560             for (var label = activeLabelList; label; label = label.next) {
31561                 if (label.name === name) {
31562                     return label;
31563                 }
31564             }
31565             return undefined;
31566         }
31567         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
31568             var flowLabel = node.kind === 234 /* BreakStatement */ ? breakTarget : continueTarget;
31569             if (flowLabel) {
31570                 addAntecedent(flowLabel, currentFlow);
31571                 currentFlow = unreachableFlow;
31572             }
31573         }
31574         function bindBreakOrContinueStatement(node) {
31575             bind(node.label);
31576             if (node.label) {
31577                 var activeLabel = findActiveLabel(node.label.escapedText);
31578                 if (activeLabel) {
31579                     activeLabel.referenced = true;
31580                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
31581                 }
31582             }
31583             else {
31584                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
31585             }
31586         }
31587         function bindTryStatement(node) {
31588             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
31589             // to track code that causes mutations (because only mutations widen the possible control flow type of
31590             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
31591             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
31592             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
31593             // represent exceptions that occur before any mutations.
31594             var saveReturnTarget = currentReturnTarget;
31595             var saveExceptionTarget = currentExceptionTarget;
31596             var normalExitLabel = createBranchLabel();
31597             var returnLabel = createBranchLabel();
31598             var exceptionLabel = createBranchLabel();
31599             if (node.finallyBlock) {
31600                 currentReturnTarget = returnLabel;
31601             }
31602             addAntecedent(exceptionLabel, currentFlow);
31603             currentExceptionTarget = exceptionLabel;
31604             bind(node.tryBlock);
31605             addAntecedent(normalExitLabel, currentFlow);
31606             if (node.catchClause) {
31607                 // Start of catch clause is the target of exceptions from try block.
31608                 currentFlow = finishFlowLabel(exceptionLabel);
31609                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
31610                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
31611                 // acts like a second try block.
31612                 exceptionLabel = createBranchLabel();
31613                 addAntecedent(exceptionLabel, currentFlow);
31614                 currentExceptionTarget = exceptionLabel;
31615                 bind(node.catchClause);
31616                 addAntecedent(normalExitLabel, currentFlow);
31617             }
31618             currentReturnTarget = saveReturnTarget;
31619             currentExceptionTarget = saveExceptionTarget;
31620             if (node.finallyBlock) {
31621                 // Possible ways control can reach the finally block:
31622                 // 1) Normal completion of try block of a try-finally or try-catch-finally
31623                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
31624                 // 3) Return in try or catch block of a try-finally or try-catch-finally
31625                 // 4) Exception in try block of a try-finally
31626                 // 5) Exception in catch block of a try-catch-finally
31627                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
31628                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
31629                 // the finally block, we only want to consider the first two (if we're past a finally block then it
31630                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
31631                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
31632                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
31633                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
31634                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
31635                 var finallyLabel = createBranchLabel();
31636                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
31637                 currentFlow = finallyLabel;
31638                 bind(node.finallyBlock);
31639                 if (currentFlow.flags & 1 /* Unreachable */) {
31640                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
31641                     currentFlow = unreachableFlow;
31642                 }
31643                 else {
31644                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
31645                     // flow that goes back through the finally block and back through only the return statements.
31646                     if (currentReturnTarget && returnLabel.antecedents) {
31647                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
31648                     }
31649                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
31650                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
31651                     // result in an unreachable current control flow.
31652                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
31653                 }
31654             }
31655             else {
31656                 currentFlow = finishFlowLabel(normalExitLabel);
31657             }
31658         }
31659         function bindSwitchStatement(node) {
31660             var postSwitchLabel = createBranchLabel();
31661             bind(node.expression);
31662             var saveBreakTarget = currentBreakTarget;
31663             var savePreSwitchCaseFlow = preSwitchCaseFlow;
31664             currentBreakTarget = postSwitchLabel;
31665             preSwitchCaseFlow = currentFlow;
31666             bind(node.caseBlock);
31667             addAntecedent(postSwitchLabel, currentFlow);
31668             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 278 /* DefaultClause */; });
31669             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
31670             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
31671             // this property in control flow analysis, it's there only for backwards compatibility.
31672             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
31673             if (!hasDefault) {
31674                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
31675             }
31676             currentBreakTarget = saveBreakTarget;
31677             preSwitchCaseFlow = savePreSwitchCaseFlow;
31678             currentFlow = finishFlowLabel(postSwitchLabel);
31679         }
31680         function bindCaseBlock(node) {
31681             var savedSubtreeTransformFlags = subtreeTransformFlags;
31682             subtreeTransformFlags = 0;
31683             var clauses = node.clauses;
31684             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
31685             var fallthroughFlow = unreachableFlow;
31686             for (var i = 0; i < clauses.length; i++) {
31687                 var clauseStart = i;
31688                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
31689                     bind(clauses[i]);
31690                     i++;
31691                 }
31692                 var preCaseLabel = createBranchLabel();
31693                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
31694                 addAntecedent(preCaseLabel, fallthroughFlow);
31695                 currentFlow = finishFlowLabel(preCaseLabel);
31696                 var clause = clauses[i];
31697                 bind(clause);
31698                 fallthroughFlow = currentFlow;
31699                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
31700                     clause.fallthroughFlowNode = currentFlow;
31701                 }
31702             }
31703             clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */;
31704             subtreeTransformFlags |= savedSubtreeTransformFlags;
31705         }
31706         function bindCaseClause(node) {
31707             var saveCurrentFlow = currentFlow;
31708             currentFlow = preSwitchCaseFlow;
31709             bind(node.expression);
31710             currentFlow = saveCurrentFlow;
31711             bindEach(node.statements);
31712         }
31713         function bindExpressionStatement(node) {
31714             bind(node.expression);
31715             // A top level call expression with a dotted function name and at least one argument
31716             // is potentially an assertion and is therefore included in the control flow.
31717             if (node.expression.kind === 196 /* CallExpression */) {
31718                 var call = node.expression;
31719                 if (ts.isDottedName(call.expression)) {
31720                     currentFlow = createFlowCall(currentFlow, call);
31721                 }
31722             }
31723         }
31724         function bindLabeledStatement(node) {
31725             var postStatementLabel = createBranchLabel();
31726             activeLabelList = {
31727                 next: activeLabelList,
31728                 name: node.label.escapedText,
31729                 breakTarget: postStatementLabel,
31730                 continueTarget: undefined,
31731                 referenced: false
31732             };
31733             bind(node.label);
31734             bind(node.statement);
31735             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
31736                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
31737             }
31738             activeLabelList = activeLabelList.next;
31739             addAntecedent(postStatementLabel, currentFlow);
31740             currentFlow = finishFlowLabel(postStatementLabel);
31741         }
31742         function bindDestructuringTargetFlow(node) {
31743             if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
31744                 bindAssignmentTargetFlow(node.left);
31745             }
31746             else {
31747                 bindAssignmentTargetFlow(node);
31748             }
31749         }
31750         function bindAssignmentTargetFlow(node) {
31751             if (isNarrowableReference(node)) {
31752                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31753             }
31754             else if (node.kind === 192 /* ArrayLiteralExpression */) {
31755                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
31756                     var e = _a[_i];
31757                     if (e.kind === 213 /* SpreadElement */) {
31758                         bindAssignmentTargetFlow(e.expression);
31759                     }
31760                     else {
31761                         bindDestructuringTargetFlow(e);
31762                     }
31763                 }
31764             }
31765             else if (node.kind === 193 /* ObjectLiteralExpression */) {
31766                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
31767                     var p = _c[_b];
31768                     if (p.kind === 281 /* PropertyAssignment */) {
31769                         bindDestructuringTargetFlow(p.initializer);
31770                     }
31771                     else if (p.kind === 282 /* ShorthandPropertyAssignment */) {
31772                         bindAssignmentTargetFlow(p.name);
31773                     }
31774                     else if (p.kind === 283 /* SpreadAssignment */) {
31775                         bindAssignmentTargetFlow(p.expression);
31776                     }
31777                 }
31778             }
31779         }
31780         function bindLogicalExpression(node, trueTarget, falseTarget) {
31781             var preRightLabel = createBranchLabel();
31782             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
31783                 bindCondition(node.left, preRightLabel, falseTarget);
31784             }
31785             else {
31786                 bindCondition(node.left, trueTarget, preRightLabel);
31787             }
31788             currentFlow = finishFlowLabel(preRightLabel);
31789             bind(node.operatorToken);
31790             bindCondition(node.right, trueTarget, falseTarget);
31791         }
31792         function bindPrefixUnaryExpressionFlow(node) {
31793             if (node.operator === 53 /* ExclamationToken */) {
31794                 var saveTrueTarget = currentTrueTarget;
31795                 currentTrueTarget = currentFalseTarget;
31796                 currentFalseTarget = saveTrueTarget;
31797                 bindEachChild(node);
31798                 currentFalseTarget = currentTrueTarget;
31799                 currentTrueTarget = saveTrueTarget;
31800             }
31801             else {
31802                 bindEachChild(node);
31803                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31804                     bindAssignmentTargetFlow(node.operand);
31805                 }
31806             }
31807         }
31808         function bindPostfixUnaryExpressionFlow(node) {
31809             bindEachChild(node);
31810             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
31811                 bindAssignmentTargetFlow(node.operand);
31812             }
31813         }
31814         var BindBinaryExpressionFlowState;
31815         (function (BindBinaryExpressionFlowState) {
31816             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
31817             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
31818             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
31819             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
31820             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
31821         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
31822         function bindBinaryExpressionFlow(node) {
31823             var workStacks = {
31824                 expr: [node],
31825                 state: [1 /* MaybeBindLeft */],
31826                 inStrictMode: [undefined],
31827                 parent: [undefined],
31828                 subtreeFlags: [undefined]
31829             };
31830             var stackIndex = 0;
31831             while (stackIndex >= 0) {
31832                 node = workStacks.expr[stackIndex];
31833                 switch (workStacks.state[stackIndex]) {
31834                     case 0 /* BindThenBindChildren */: {
31835                         // This state is used only when recuring, to emulate the work that `bind` does before
31836                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
31837                         node.parent = parent;
31838                         var saveInStrictMode = inStrictMode;
31839                         bindWorker(node);
31840                         var saveParent = parent;
31841                         parent = node;
31842                         var subtreeFlagsState = void 0;
31843                         // While this next part does the work of `bindChildren` before it descends into `bindChildrenWorker`
31844                         // and uses `subtreeFlagsState` to queue up the work that needs to be done once the node is bound.
31845                         if (skipTransformFlagAggregation) {
31846                             // do nothing extra
31847                         }
31848                         else if (node.transformFlags & 536870912 /* HasComputedFlags */) {
31849                             skipTransformFlagAggregation = true;
31850                             subtreeFlagsState = -1;
31851                         }
31852                         else {
31853                             var savedSubtreeTransformFlags = subtreeTransformFlags;
31854                             subtreeTransformFlags = 0;
31855                             subtreeFlagsState = savedSubtreeTransformFlags;
31856                         }
31857                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent, subtreeFlagsState);
31858                         break;
31859                     }
31860                     case 1 /* MaybeBindLeft */: {
31861                         var operator = node.operatorToken.kind;
31862                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
31863                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
31864                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
31865                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
31866                             if (isTopLevelLogicalExpression(node)) {
31867                                 var postExpressionLabel = createBranchLabel();
31868                                 bindLogicalExpression(node, postExpressionLabel, postExpressionLabel);
31869                                 currentFlow = finishFlowLabel(postExpressionLabel);
31870                             }
31871                             else {
31872                                 bindLogicalExpression(node, currentTrueTarget, currentFalseTarget);
31873                             }
31874                             completeNode();
31875                         }
31876                         else {
31877                             advanceState(2 /* BindToken */);
31878                             maybeBind(node.left);
31879                         }
31880                         break;
31881                     }
31882                     case 2 /* BindToken */: {
31883                         advanceState(3 /* BindRight */);
31884                         maybeBind(node.operatorToken);
31885                         break;
31886                     }
31887                     case 3 /* BindRight */: {
31888                         advanceState(4 /* FinishBind */);
31889                         maybeBind(node.right);
31890                         break;
31891                     }
31892                     case 4 /* FinishBind */: {
31893                         var operator = node.operatorToken.kind;
31894                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
31895                             bindAssignmentTargetFlow(node.left);
31896                             if (operator === 62 /* EqualsToken */ && node.left.kind === 195 /* ElementAccessExpression */) {
31897                                 var elementAccess = node.left;
31898                                 if (isNarrowableOperand(elementAccess.expression)) {
31899                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
31900                                 }
31901                             }
31902                         }
31903                         completeNode();
31904                         break;
31905                     }
31906                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
31907                 }
31908             }
31909             /**
31910              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
31911              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
31912              */
31913             function advanceState(state, isInStrictMode, parent, subtreeFlags) {
31914                 workStacks.state[stackIndex] = state;
31915                 if (isInStrictMode !== undefined) {
31916                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
31917                 }
31918                 if (parent !== undefined) {
31919                     workStacks.parent[stackIndex] = parent;
31920                 }
31921                 if (subtreeFlags !== undefined) {
31922                     workStacks.subtreeFlags[stackIndex] = subtreeFlags;
31923                 }
31924             }
31925             function completeNode() {
31926                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
31927                     if (workStacks.subtreeFlags[stackIndex] === -1) {
31928                         skipTransformFlagAggregation = false;
31929                         subtreeTransformFlags |= node.transformFlags & ~getTransformFlagsSubtreeExclusions(node.kind);
31930                     }
31931                     else if (workStacks.subtreeFlags[stackIndex] !== undefined) {
31932                         subtreeTransformFlags = workStacks.subtreeFlags[stackIndex] | computeTransformFlagsForNode(node, subtreeTransformFlags);
31933                     }
31934                     inStrictMode = workStacks.inStrictMode[stackIndex];
31935                     parent = workStacks.parent[stackIndex];
31936                 }
31937                 stackIndex--;
31938             }
31939             /**
31940              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
31941              */
31942             function maybeBind(node) {
31943                 if (node && ts.isBinaryExpression(node)) {
31944                     stackIndex++;
31945                     workStacks.expr[stackIndex] = node;
31946                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
31947                     workStacks.inStrictMode[stackIndex] = undefined;
31948                     workStacks.parent[stackIndex] = undefined;
31949                     workStacks.subtreeFlags[stackIndex] = undefined;
31950                 }
31951                 else {
31952                     bind(node);
31953                 }
31954             }
31955         }
31956         function bindDeleteExpressionFlow(node) {
31957             bindEachChild(node);
31958             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
31959                 bindAssignmentTargetFlow(node.expression);
31960             }
31961         }
31962         function bindConditionalExpressionFlow(node) {
31963             var trueLabel = createBranchLabel();
31964             var falseLabel = createBranchLabel();
31965             var postExpressionLabel = createBranchLabel();
31966             bindCondition(node.condition, trueLabel, falseLabel);
31967             currentFlow = finishFlowLabel(trueLabel);
31968             bind(node.questionToken);
31969             bind(node.whenTrue);
31970             addAntecedent(postExpressionLabel, currentFlow);
31971             currentFlow = finishFlowLabel(falseLabel);
31972             bind(node.colonToken);
31973             bind(node.whenFalse);
31974             addAntecedent(postExpressionLabel, currentFlow);
31975             currentFlow = finishFlowLabel(postExpressionLabel);
31976         }
31977         function bindInitializedVariableFlow(node) {
31978             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
31979             if (ts.isBindingPattern(name)) {
31980                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
31981                     var child = _a[_i];
31982                     bindInitializedVariableFlow(child);
31983                 }
31984             }
31985             else {
31986                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
31987             }
31988         }
31989         function bindVariableDeclarationFlow(node) {
31990             bindEachChild(node);
31991             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
31992                 bindInitializedVariableFlow(node);
31993             }
31994         }
31995         function bindJSDocTypeAlias(node) {
31996             node.tagName.parent = node;
31997             if (node.kind !== 316 /* JSDocEnumTag */ && node.fullName) {
31998                 setParentPointers(node, node.fullName);
31999             }
32000         }
32001         function bindJSDocClassTag(node) {
32002             bindEachChild(node);
32003             var host = ts.getHostSignatureFromJSDoc(node);
32004             if (host && host.kind !== 161 /* MethodDeclaration */) {
32005                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
32006             }
32007         }
32008         function bindOptionalExpression(node, trueTarget, falseTarget) {
32009             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
32010             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
32011                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32012                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32013             }
32014         }
32015         function bindOptionalChainRest(node) {
32016             switch (node.kind) {
32017                 case 194 /* PropertyAccessExpression */:
32018                     bind(node.questionDotToken);
32019                     bind(node.name);
32020                     break;
32021                 case 195 /* ElementAccessExpression */:
32022                     bind(node.questionDotToken);
32023                     bind(node.argumentExpression);
32024                     break;
32025                 case 196 /* CallExpression */:
32026                     bind(node.questionDotToken);
32027                     bindEach(node.typeArguments);
32028                     bindEach(node.arguments);
32029                     break;
32030             }
32031         }
32032         function bindOptionalChain(node, trueTarget, falseTarget) {
32033             // For an optional chain, we emulate the behavior of a logical expression:
32034             //
32035             // a?.b         -> a && a.b
32036             // a?.b.c       -> a && a.b.c
32037             // a?.b?.c      -> a && a.b && a.b.c
32038             // a?.[x = 1]   -> a && a[x = 1]
32039             //
32040             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
32041             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
32042             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
32043             // chain node. We then treat the entire node as the right side of the expression.
32044             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
32045             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
32046             if (preChainLabel) {
32047                 currentFlow = finishFlowLabel(preChainLabel);
32048             }
32049             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
32050             if (ts.isOutermostOptionalChain(node)) {
32051                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
32052                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
32053             }
32054         }
32055         function bindOptionalChainFlow(node) {
32056             if (isTopLevelLogicalExpression(node)) {
32057                 var postExpressionLabel = createBranchLabel();
32058                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
32059                 currentFlow = finishFlowLabel(postExpressionLabel);
32060             }
32061             else {
32062                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
32063             }
32064         }
32065         function bindNonNullExpressionFlow(node) {
32066             if (ts.isOptionalChain(node)) {
32067                 bindOptionalChainFlow(node);
32068             }
32069             else {
32070                 bindEachChild(node);
32071             }
32072         }
32073         function bindAccessExpressionFlow(node) {
32074             if (ts.isOptionalChain(node)) {
32075                 bindOptionalChainFlow(node);
32076             }
32077             else {
32078                 bindEachChild(node);
32079             }
32080         }
32081         function bindCallExpressionFlow(node) {
32082             if (ts.isOptionalChain(node)) {
32083                 bindOptionalChainFlow(node);
32084             }
32085             else {
32086                 // If the target of the call expression is a function expression or arrow function we have
32087                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
32088                 // the current control flow (which includes evaluation of the IIFE arguments).
32089                 var expr = ts.skipParentheses(node.expression);
32090                 if (expr.kind === 201 /* FunctionExpression */ || expr.kind === 202 /* ArrowFunction */) {
32091                     bindEach(node.typeArguments);
32092                     bindEach(node.arguments);
32093                     bind(node.expression);
32094                 }
32095                 else {
32096                     bindEachChild(node);
32097                 }
32098             }
32099             if (node.expression.kind === 194 /* PropertyAccessExpression */) {
32100                 var propertyAccess = node.expression;
32101                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
32102                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
32103                 }
32104             }
32105         }
32106         function getContainerFlags(node) {
32107             switch (node.kind) {
32108                 case 214 /* ClassExpression */:
32109                 case 245 /* ClassDeclaration */:
32110                 case 248 /* EnumDeclaration */:
32111                 case 193 /* ObjectLiteralExpression */:
32112                 case 173 /* TypeLiteral */:
32113                 case 304 /* JSDocTypeLiteral */:
32114                 case 274 /* JsxAttributes */:
32115                     return 1 /* IsContainer */;
32116                 case 246 /* InterfaceDeclaration */:
32117                     return 1 /* IsContainer */ | 64 /* IsInterface */;
32118                 case 249 /* ModuleDeclaration */:
32119                 case 247 /* TypeAliasDeclaration */:
32120                 case 186 /* MappedType */:
32121                     return 1 /* IsContainer */ | 32 /* HasLocals */;
32122                 case 290 /* SourceFile */:
32123                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
32124                 case 161 /* MethodDeclaration */:
32125                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
32126                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
32127                     }
32128                 // falls through
32129                 case 162 /* Constructor */:
32130                 case 244 /* FunctionDeclaration */:
32131                 case 160 /* MethodSignature */:
32132                 case 163 /* GetAccessor */:
32133                 case 164 /* SetAccessor */:
32134                 case 165 /* CallSignature */:
32135                 case 305 /* JSDocSignature */:
32136                 case 300 /* JSDocFunctionType */:
32137                 case 170 /* FunctionType */:
32138                 case 166 /* ConstructSignature */:
32139                 case 167 /* IndexSignature */:
32140                 case 171 /* ConstructorType */:
32141                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
32142                 case 201 /* FunctionExpression */:
32143                 case 202 /* ArrowFunction */:
32144                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
32145                 case 250 /* ModuleBlock */:
32146                     return 4 /* IsControlFlowContainer */;
32147                 case 159 /* PropertyDeclaration */:
32148                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
32149                 case 280 /* CatchClause */:
32150                 case 230 /* ForStatement */:
32151                 case 231 /* ForInStatement */:
32152                 case 232 /* ForOfStatement */:
32153                 case 251 /* CaseBlock */:
32154                     return 2 /* IsBlockScopedContainer */;
32155                 case 223 /* Block */:
32156                     // do not treat blocks directly inside a function as a block-scoped-container.
32157                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
32158                     // would not appear to be a redeclaration of a block scoped local in the following
32159                     // example:
32160                     //
32161                     //      function foo() {
32162                     //          var x;
32163                     //          let x;
32164                     //      }
32165                     //
32166                     // If we placed 'var x' into the function locals and 'let x' into the locals of
32167                     // the block, then there would be no collision.
32168                     //
32169                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
32170                     // and 'let x' go into the Function-container's locals, and we do get a collision
32171                     // conflict.
32172                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
32173             }
32174             return 0 /* None */;
32175         }
32176         function addToContainerChain(next) {
32177             if (lastContainer) {
32178                 lastContainer.nextContainer = next;
32179             }
32180             lastContainer = next;
32181         }
32182         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
32183             switch (container.kind) {
32184                 // Modules, source files, and classes need specialized handling for how their
32185                 // members are declared (for example, a member of a class will go into a specific
32186                 // symbol table depending on if it is static or not). We defer to specialized
32187                 // handlers to take care of declaring these child members.
32188                 case 249 /* ModuleDeclaration */:
32189                     return declareModuleMember(node, symbolFlags, symbolExcludes);
32190                 case 290 /* SourceFile */:
32191                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
32192                 case 214 /* ClassExpression */:
32193                 case 245 /* ClassDeclaration */:
32194                     return declareClassMember(node, symbolFlags, symbolExcludes);
32195                 case 248 /* EnumDeclaration */:
32196                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
32197                 case 173 /* TypeLiteral */:
32198                 case 304 /* JSDocTypeLiteral */:
32199                 case 193 /* ObjectLiteralExpression */:
32200                 case 246 /* InterfaceDeclaration */:
32201                 case 274 /* JsxAttributes */:
32202                     // Interface/Object-types always have their children added to the 'members' of
32203                     // their container. They are only accessible through an instance of their
32204                     // container, and are never in scope otherwise (even inside the body of the
32205                     // object / type / interface declaring them). An exception is type parameters,
32206                     // which are in scope without qualification (similar to 'locals').
32207                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32208                 case 170 /* FunctionType */:
32209                 case 171 /* ConstructorType */:
32210                 case 165 /* CallSignature */:
32211                 case 166 /* ConstructSignature */:
32212                 case 305 /* JSDocSignature */:
32213                 case 167 /* IndexSignature */:
32214                 case 161 /* MethodDeclaration */:
32215                 case 160 /* MethodSignature */:
32216                 case 162 /* Constructor */:
32217                 case 163 /* GetAccessor */:
32218                 case 164 /* SetAccessor */:
32219                 case 244 /* FunctionDeclaration */:
32220                 case 201 /* FunctionExpression */:
32221                 case 202 /* ArrowFunction */:
32222                 case 300 /* JSDocFunctionType */:
32223                 case 322 /* JSDocTypedefTag */:
32224                 case 315 /* JSDocCallbackTag */:
32225                 case 247 /* TypeAliasDeclaration */:
32226                 case 186 /* MappedType */:
32227                     // All the children of these container types are never visible through another
32228                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
32229                     // they're only accessed 'lexically' (i.e. from code that exists underneath
32230                     // their container in the tree). To accomplish this, we simply add their declared
32231                     // symbol to the 'locals' of the container.  These symbols can then be found as
32232                     // the type checker walks up the containers, checking them for matching names.
32233                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32234             }
32235         }
32236         function declareClassMember(node, symbolFlags, symbolExcludes) {
32237             return ts.hasModifier(node, 32 /* Static */)
32238                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
32239                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
32240         }
32241         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
32242             return ts.isExternalModule(file)
32243                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
32244                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32245         }
32246         function hasExportDeclarations(node) {
32247             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
32248             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
32249         }
32250         function setExportContextFlag(node) {
32251             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
32252             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
32253             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
32254                 node.flags |= 64 /* ExportContext */;
32255             }
32256             else {
32257                 node.flags &= ~64 /* ExportContext */;
32258             }
32259         }
32260         function bindModuleDeclaration(node) {
32261             setExportContextFlag(node);
32262             if (ts.isAmbientModule(node)) {
32263                 if (ts.hasModifier(node, 1 /* Export */)) {
32264                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
32265                 }
32266                 if (ts.isModuleAugmentationExternal(node)) {
32267                     declareModuleSymbol(node);
32268                 }
32269                 else {
32270                     var pattern = void 0;
32271                     if (node.name.kind === 10 /* StringLiteral */) {
32272                         var text = node.name.text;
32273                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
32274                             pattern = ts.tryParsePattern(text);
32275                         }
32276                         else {
32277                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
32278                         }
32279                     }
32280                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
32281                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
32282                 }
32283             }
32284             else {
32285                 var state = declareModuleSymbol(node);
32286                 if (state !== 0 /* NonInstantiated */) {
32287                     var symbol = node.symbol;
32288                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
32289                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
32290                         // Current must be `const enum` only
32291                         && state === 2 /* ConstEnumOnly */
32292                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
32293                         && symbol.constEnumOnlyModule !== false;
32294                 }
32295             }
32296         }
32297         function declareModuleSymbol(node) {
32298             var state = getModuleInstanceState(node);
32299             var instantiated = state !== 0 /* NonInstantiated */;
32300             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
32301             return state;
32302         }
32303         function bindFunctionOrConstructorType(node) {
32304             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
32305             // to the one we would get for: { <...>(...): T }
32306             //
32307             // We do that by making an anonymous type literal symbol, and then setting the function
32308             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
32309             // from an actual type literal symbol you would have gotten had you used the long form.
32310             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
32311             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
32312             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
32313             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
32314             typeLiteralSymbol.members = ts.createSymbolTable();
32315             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
32316         }
32317         function bindObjectLiteralExpression(node) {
32318             var ElementKind;
32319             (function (ElementKind) {
32320                 ElementKind[ElementKind["Property"] = 1] = "Property";
32321                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
32322             })(ElementKind || (ElementKind = {}));
32323             if (inStrictMode && !ts.isAssignmentTarget(node)) {
32324                 var seen = ts.createUnderscoreEscapedMap();
32325                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
32326                     var prop = _a[_i];
32327                     if (prop.kind === 283 /* SpreadAssignment */ || prop.name.kind !== 75 /* Identifier */) {
32328                         continue;
32329                     }
32330                     var identifier = prop.name;
32331                     // ECMA-262 11.1.5 Object Initializer
32332                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
32333                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
32334                     // IsDataDescriptor(propId.descriptor) is true.
32335                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
32336                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
32337                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
32338                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
32339                     var currentKind = prop.kind === 281 /* PropertyAssignment */ || prop.kind === 282 /* ShorthandPropertyAssignment */ || prop.kind === 161 /* MethodDeclaration */
32340                         ? 1 /* Property */
32341                         : 2 /* Accessor */;
32342                     var existingKind = seen.get(identifier.escapedText);
32343                     if (!existingKind) {
32344                         seen.set(identifier.escapedText, currentKind);
32345                         continue;
32346                     }
32347                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
32348                         var span = ts.getErrorSpanForNode(file, identifier);
32349                         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));
32350                     }
32351                 }
32352             }
32353             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
32354         }
32355         function bindJsxAttributes(node) {
32356             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
32357         }
32358         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
32359             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
32360         }
32361         function bindAnonymousDeclaration(node, symbolFlags, name) {
32362             var symbol = createSymbol(symbolFlags, name);
32363             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
32364                 symbol.parent = container.symbol;
32365             }
32366             addDeclarationToSymbol(symbol, node, symbolFlags);
32367             return symbol;
32368         }
32369         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
32370             switch (blockScopeContainer.kind) {
32371                 case 249 /* ModuleDeclaration */:
32372                     declareModuleMember(node, symbolFlags, symbolExcludes);
32373                     break;
32374                 case 290 /* SourceFile */:
32375                     if (ts.isExternalOrCommonJsModule(container)) {
32376                         declareModuleMember(node, symbolFlags, symbolExcludes);
32377                         break;
32378                     }
32379                 // falls through
32380                 default:
32381                     if (!blockScopeContainer.locals) {
32382                         blockScopeContainer.locals = ts.createSymbolTable();
32383                         addToContainerChain(blockScopeContainer);
32384                     }
32385                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
32386             }
32387         }
32388         function delayedBindJSDocTypedefTag() {
32389             if (!delayedTypeAliases) {
32390                 return;
32391             }
32392             var saveContainer = container;
32393             var saveLastContainer = lastContainer;
32394             var saveBlockScopeContainer = blockScopeContainer;
32395             var saveParent = parent;
32396             var saveCurrentFlow = currentFlow;
32397             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
32398                 var typeAlias = delayedTypeAliases_1[_i];
32399                 var host = ts.getJSDocHost(typeAlias);
32400                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
32401                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
32402                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
32403                 parent = typeAlias;
32404                 bind(typeAlias.typeExpression);
32405                 var declName = ts.getNameOfDeclaration(typeAlias);
32406                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
32407                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
32408                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
32409                     if (isTopLevel) {
32410                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
32411                         var oldContainer = container;
32412                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
32413                             case 1 /* ExportsProperty */:
32414                             case 2 /* ModuleExports */:
32415                                 if (!ts.isExternalOrCommonJsModule(file)) {
32416                                     container = undefined;
32417                                 }
32418                                 else {
32419                                     container = file;
32420                                 }
32421                                 break;
32422                             case 4 /* ThisProperty */:
32423                                 container = declName.parent.expression;
32424                                 break;
32425                             case 3 /* PrototypeProperty */:
32426                                 container = declName.parent.expression.name;
32427                                 break;
32428                             case 5 /* Property */:
32429                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
32430                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
32431                                         : declName.parent.expression;
32432                                 break;
32433                             case 0 /* None */:
32434                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
32435                         }
32436                         if (container) {
32437                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32438                         }
32439                         container = oldContainer;
32440                     }
32441                 }
32442                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 75 /* Identifier */) {
32443                     parent = typeAlias.parent;
32444                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32445                 }
32446                 else {
32447                     bind(typeAlias.fullName);
32448                 }
32449             }
32450             container = saveContainer;
32451             lastContainer = saveLastContainer;
32452             blockScopeContainer = saveBlockScopeContainer;
32453             parent = saveParent;
32454             currentFlow = saveCurrentFlow;
32455         }
32456         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
32457         // check for reserved words used as identifiers in strict mode code.
32458         function checkStrictModeIdentifier(node) {
32459             if (inStrictMode &&
32460                 node.originalKeywordKind >= 113 /* FirstFutureReservedWord */ &&
32461                 node.originalKeywordKind <= 121 /* LastFutureReservedWord */ &&
32462                 !ts.isIdentifierName(node) &&
32463                 !(node.flags & 8388608 /* Ambient */) &&
32464                 !(node.flags & 4194304 /* JSDoc */)) {
32465                 // Report error only if there are no parse errors in file
32466                 if (!file.parseDiagnostics.length) {
32467                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
32468                 }
32469             }
32470         }
32471         function getStrictModeIdentifierMessage(node) {
32472             // Provide specialized messages to help the user understand why we think they're in
32473             // strict mode.
32474             if (ts.getContainingClass(node)) {
32475                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
32476             }
32477             if (file.externalModuleIndicator) {
32478                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
32479             }
32480             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
32481         }
32482         // The binder visits every node, so this is a good place to check for
32483         // the reserved private name (there is only one)
32484         function checkPrivateIdentifier(node) {
32485             if (node.escapedText === "#constructor") {
32486                 // Report error only if there are no parse errors in file
32487                 if (!file.parseDiagnostics.length) {
32488                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
32489                 }
32490             }
32491         }
32492         function checkStrictModeBinaryExpression(node) {
32493             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
32494                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32495                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
32496                 checkStrictModeEvalOrArguments(node, node.left);
32497             }
32498         }
32499         function checkStrictModeCatchClause(node) {
32500             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
32501             // Catch production is eval or arguments
32502             if (inStrictMode && node.variableDeclaration) {
32503                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
32504             }
32505         }
32506         function checkStrictModeDeleteExpression(node) {
32507             // Grammar checking
32508             if (inStrictMode && node.expression.kind === 75 /* Identifier */) {
32509                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
32510                 // UnaryExpression is a direct reference to a variable, function argument, or function name
32511                 var span = ts.getErrorSpanForNode(file, node.expression);
32512                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
32513             }
32514         }
32515         function isEvalOrArgumentsIdentifier(node) {
32516             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
32517         }
32518         function checkStrictModeEvalOrArguments(contextNode, name) {
32519             if (name && name.kind === 75 /* Identifier */) {
32520                 var identifier = name;
32521                 if (isEvalOrArgumentsIdentifier(identifier)) {
32522                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32523                     // otherwise report generic error message.
32524                     var span = ts.getErrorSpanForNode(file, name);
32525                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
32526                 }
32527             }
32528         }
32529         function getStrictModeEvalOrArgumentsMessage(node) {
32530             // Provide specialized messages to help the user understand why we think they're in
32531             // strict mode.
32532             if (ts.getContainingClass(node)) {
32533                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
32534             }
32535             if (file.externalModuleIndicator) {
32536                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
32537             }
32538             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
32539         }
32540         function checkStrictModeFunctionName(node) {
32541             if (inStrictMode) {
32542                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
32543                 checkStrictModeEvalOrArguments(node, node.name);
32544             }
32545         }
32546         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
32547             // Provide specialized messages to help the user understand why we think they're in
32548             // strict mode.
32549             if (ts.getContainingClass(node)) {
32550                 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;
32551             }
32552             if (file.externalModuleIndicator) {
32553                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
32554             }
32555             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
32556         }
32557         function checkStrictModeFunctionDeclaration(node) {
32558             if (languageVersion < 2 /* ES2015 */) {
32559                 // Report error if function is not top level function declaration
32560                 if (blockScopeContainer.kind !== 290 /* SourceFile */ &&
32561                     blockScopeContainer.kind !== 249 /* ModuleDeclaration */ &&
32562                     !ts.isFunctionLike(blockScopeContainer)) {
32563                     // We check first if the name is inside class declaration or class expression; if so give explicit message
32564                     // otherwise report generic error message.
32565                     var errorSpan = ts.getErrorSpanForNode(file, node);
32566                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
32567                 }
32568             }
32569         }
32570         function checkStrictModeNumericLiteral(node) {
32571             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
32572                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
32573             }
32574         }
32575         function checkStrictModePostfixUnaryExpression(node) {
32576             // Grammar checking
32577             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
32578             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
32579             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
32580             if (inStrictMode) {
32581                 checkStrictModeEvalOrArguments(node, node.operand);
32582             }
32583         }
32584         function checkStrictModePrefixUnaryExpression(node) {
32585             // Grammar checking
32586             if (inStrictMode) {
32587                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
32588                     checkStrictModeEvalOrArguments(node, node.operand);
32589                 }
32590             }
32591         }
32592         function checkStrictModeWithStatement(node) {
32593             // Grammar checking for withStatement
32594             if (inStrictMode) {
32595                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
32596             }
32597         }
32598         function checkStrictModeLabeledStatement(node) {
32599             // Grammar checking for labeledStatement
32600             if (inStrictMode && options.target >= 2 /* ES2015 */) {
32601                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
32602                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
32603                 }
32604             }
32605         }
32606         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
32607             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
32608             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
32609         }
32610         function errorOrSuggestionOnNode(isError, node, message) {
32611             errorOrSuggestionOnRange(isError, node, node, message);
32612         }
32613         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
32614             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
32615         }
32616         function addErrorOrSuggestionDiagnostic(isError, range, message) {
32617             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
32618             if (isError) {
32619                 file.bindDiagnostics.push(diag);
32620             }
32621             else {
32622                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
32623             }
32624         }
32625         function bind(node) {
32626             if (!node) {
32627                 return;
32628             }
32629             node.parent = parent;
32630             var saveInStrictMode = inStrictMode;
32631             // Even though in the AST the jsdoc @typedef node belongs to the current node,
32632             // its symbol might be in the same scope with the current node's symbol. Consider:
32633             //
32634             //     /** @typedef {string | number} MyType */
32635             //     function foo();
32636             //
32637             // Here the current node is "foo", which is a container, but the scope of "MyType" should
32638             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
32639             // and skip binding this tag later when binding all the other jsdoc tags.
32640             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
32641             // and then potentially add the symbol to an appropriate symbol table. Possible
32642             // destination symbol tables are:
32643             //
32644             //  1) The 'exports' table of the current container's symbol.
32645             //  2) The 'members' table of the current container's symbol.
32646             //  3) The 'locals' table of the current container.
32647             //
32648             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
32649             // (like TypeLiterals for example) will not be put in any table.
32650             bindWorker(node);
32651             // Then we recurse into the children of the node to bind them as well. For certain
32652             // symbols we do specialized work when we recurse. For example, we'll keep track of
32653             // the current 'container' node when it changes. This helps us know which symbol table
32654             // a local should go into for example. Since terminal nodes are known not to have
32655             // children, as an optimization we don't process those.
32656             if (node.kind > 152 /* LastToken */) {
32657                 var saveParent = parent;
32658                 parent = node;
32659                 var containerFlags = getContainerFlags(node);
32660                 if (containerFlags === 0 /* None */) {
32661                     bindChildren(node);
32662                 }
32663                 else {
32664                     bindContainer(node, containerFlags);
32665                 }
32666                 parent = saveParent;
32667             }
32668             else if (!skipTransformFlagAggregation && (node.transformFlags & 536870912 /* HasComputedFlags */) === 0) {
32669                 subtreeTransformFlags |= computeTransformFlagsForNode(node, 0);
32670                 var saveParent = parent;
32671                 if (node.kind === 1 /* EndOfFileToken */)
32672                     parent = node;
32673                 bindJSDoc(node);
32674                 parent = saveParent;
32675             }
32676             inStrictMode = saveInStrictMode;
32677         }
32678         function bindJSDoc(node) {
32679             if (ts.hasJSDocNodes(node)) {
32680                 if (ts.isInJSFile(node)) {
32681                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
32682                         var j = _a[_i];
32683                         bind(j);
32684                     }
32685                 }
32686                 else {
32687                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
32688                         var j = _c[_b];
32689                         setParentPointers(node, j);
32690                     }
32691                 }
32692             }
32693         }
32694         function updateStrictModeStatementList(statements) {
32695             if (!inStrictMode) {
32696                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
32697                     var statement = statements_2[_i];
32698                     if (!ts.isPrologueDirective(statement)) {
32699                         return;
32700                     }
32701                     if (isUseStrictPrologueDirective(statement)) {
32702                         inStrictMode = true;
32703                         return;
32704                     }
32705                 }
32706             }
32707         }
32708         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
32709         function isUseStrictPrologueDirective(node) {
32710             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
32711             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
32712             // string to contain unicode escapes (as per ES5).
32713             return nodeText === '"use strict"' || nodeText === "'use strict'";
32714         }
32715         function bindWorker(node) {
32716             switch (node.kind) {
32717                 /* Strict mode checks */
32718                 case 75 /* Identifier */:
32719                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
32720                     // because it requires all containing namespaces to be in effect, namely the
32721                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
32722                     if (node.isInJSDocNamespace) {
32723                         var parentNode = node.parent;
32724                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
32725                             parentNode = parentNode.parent;
32726                         }
32727                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32728                         break;
32729                     }
32730                 // falls through
32731                 case 104 /* ThisKeyword */:
32732                     if (currentFlow && (ts.isExpression(node) || parent.kind === 282 /* ShorthandPropertyAssignment */)) {
32733                         node.flowNode = currentFlow;
32734                     }
32735                     return checkStrictModeIdentifier(node);
32736                 case 76 /* PrivateIdentifier */:
32737                     return checkPrivateIdentifier(node);
32738                 case 194 /* PropertyAccessExpression */:
32739                 case 195 /* ElementAccessExpression */:
32740                     var expr = node;
32741                     if (currentFlow && isNarrowableReference(expr)) {
32742                         expr.flowNode = currentFlow;
32743                     }
32744                     if (ts.isSpecialPropertyDeclaration(expr)) {
32745                         bindSpecialPropertyDeclaration(expr);
32746                     }
32747                     if (ts.isInJSFile(expr) &&
32748                         file.commonJsModuleIndicator &&
32749                         ts.isModuleExportsAccessExpression(expr) &&
32750                         !lookupSymbolForNameWorker(blockScopeContainer, "module")) {
32751                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
32752                     }
32753                     break;
32754                 case 209 /* BinaryExpression */:
32755                     var specialKind = ts.getAssignmentDeclarationKind(node);
32756                     switch (specialKind) {
32757                         case 1 /* ExportsProperty */:
32758                             bindExportsPropertyAssignment(node);
32759                             break;
32760                         case 2 /* ModuleExports */:
32761                             bindModuleExportsAssignment(node);
32762                             break;
32763                         case 3 /* PrototypeProperty */:
32764                             bindPrototypePropertyAssignment(node.left, node);
32765                             break;
32766                         case 6 /* Prototype */:
32767                             bindPrototypeAssignment(node);
32768                             break;
32769                         case 4 /* ThisProperty */:
32770                             bindThisPropertyAssignment(node);
32771                             break;
32772                         case 5 /* Property */:
32773                             bindSpecialPropertyAssignment(node);
32774                             break;
32775                         case 0 /* None */:
32776                             // Nothing to do
32777                             break;
32778                         default:
32779                             ts.Debug.fail("Unknown binary expression special property assignment kind");
32780                     }
32781                     return checkStrictModeBinaryExpression(node);
32782                 case 280 /* CatchClause */:
32783                     return checkStrictModeCatchClause(node);
32784                 case 203 /* DeleteExpression */:
32785                     return checkStrictModeDeleteExpression(node);
32786                 case 8 /* NumericLiteral */:
32787                     return checkStrictModeNumericLiteral(node);
32788                 case 208 /* PostfixUnaryExpression */:
32789                     return checkStrictModePostfixUnaryExpression(node);
32790                 case 207 /* PrefixUnaryExpression */:
32791                     return checkStrictModePrefixUnaryExpression(node);
32792                 case 236 /* WithStatement */:
32793                     return checkStrictModeWithStatement(node);
32794                 case 238 /* LabeledStatement */:
32795                     return checkStrictModeLabeledStatement(node);
32796                 case 183 /* ThisType */:
32797                     seenThisKeyword = true;
32798                     return;
32799                 case 168 /* TypePredicate */:
32800                     break; // Binding the children will handle everything
32801                 case 155 /* TypeParameter */:
32802                     return bindTypeParameter(node);
32803                 case 156 /* Parameter */:
32804                     return bindParameter(node);
32805                 case 242 /* VariableDeclaration */:
32806                     return bindVariableDeclarationOrBindingElement(node);
32807                 case 191 /* BindingElement */:
32808                     node.flowNode = currentFlow;
32809                     return bindVariableDeclarationOrBindingElement(node);
32810                 case 159 /* PropertyDeclaration */:
32811                 case 158 /* PropertySignature */:
32812                     return bindPropertyWorker(node);
32813                 case 281 /* PropertyAssignment */:
32814                 case 282 /* ShorthandPropertyAssignment */:
32815                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
32816                 case 284 /* EnumMember */:
32817                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
32818                 case 165 /* CallSignature */:
32819                 case 166 /* ConstructSignature */:
32820                 case 167 /* IndexSignature */:
32821                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
32822                 case 161 /* MethodDeclaration */:
32823                 case 160 /* MethodSignature */:
32824                     // If this is an ObjectLiteralExpression method, then it sits in the same space
32825                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
32826                     // so that it will conflict with any other object literal members with the same
32827                     // name.
32828                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
32829                 case 244 /* FunctionDeclaration */:
32830                     return bindFunctionDeclaration(node);
32831                 case 162 /* Constructor */:
32832                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
32833                 case 163 /* GetAccessor */:
32834                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
32835                 case 164 /* SetAccessor */:
32836                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
32837                 case 170 /* FunctionType */:
32838                 case 300 /* JSDocFunctionType */:
32839                 case 305 /* JSDocSignature */:
32840                 case 171 /* ConstructorType */:
32841                     return bindFunctionOrConstructorType(node);
32842                 case 173 /* TypeLiteral */:
32843                 case 304 /* JSDocTypeLiteral */:
32844                 case 186 /* MappedType */:
32845                     return bindAnonymousTypeWorker(node);
32846                 case 310 /* JSDocClassTag */:
32847                     return bindJSDocClassTag(node);
32848                 case 193 /* ObjectLiteralExpression */:
32849                     return bindObjectLiteralExpression(node);
32850                 case 201 /* FunctionExpression */:
32851                 case 202 /* ArrowFunction */:
32852                     return bindFunctionExpression(node);
32853                 case 196 /* CallExpression */:
32854                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
32855                     switch (assignmentKind) {
32856                         case 7 /* ObjectDefinePropertyValue */:
32857                             return bindObjectDefinePropertyAssignment(node);
32858                         case 8 /* ObjectDefinePropertyExports */:
32859                             return bindObjectDefinePropertyExport(node);
32860                         case 9 /* ObjectDefinePrototypeProperty */:
32861                             return bindObjectDefinePrototypeProperty(node);
32862                         case 0 /* None */:
32863                             break; // Nothing to do
32864                         default:
32865                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
32866                     }
32867                     if (ts.isInJSFile(node)) {
32868                         bindCallExpression(node);
32869                     }
32870                     break;
32871                 // Members of classes, interfaces, and modules
32872                 case 214 /* ClassExpression */:
32873                 case 245 /* ClassDeclaration */:
32874                     // All classes are automatically in strict mode in ES6.
32875                     inStrictMode = true;
32876                     return bindClassLikeDeclaration(node);
32877                 case 246 /* InterfaceDeclaration */:
32878                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
32879                 case 247 /* TypeAliasDeclaration */:
32880                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
32881                 case 248 /* EnumDeclaration */:
32882                     return bindEnumDeclaration(node);
32883                 case 249 /* ModuleDeclaration */:
32884                     return bindModuleDeclaration(node);
32885                 // Jsx-attributes
32886                 case 274 /* JsxAttributes */:
32887                     return bindJsxAttributes(node);
32888                 case 273 /* JsxAttribute */:
32889                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
32890                 // Imports and exports
32891                 case 253 /* ImportEqualsDeclaration */:
32892                 case 256 /* NamespaceImport */:
32893                 case 258 /* ImportSpecifier */:
32894                 case 263 /* ExportSpecifier */:
32895                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32896                 case 252 /* NamespaceExportDeclaration */:
32897                     return bindNamespaceExportDeclaration(node);
32898                 case 255 /* ImportClause */:
32899                     return bindImportClause(node);
32900                 case 260 /* ExportDeclaration */:
32901                     return bindExportDeclaration(node);
32902                 case 259 /* ExportAssignment */:
32903                     return bindExportAssignment(node);
32904                 case 290 /* SourceFile */:
32905                     updateStrictModeStatementList(node.statements);
32906                     return bindSourceFileIfExternalModule();
32907                 case 223 /* Block */:
32908                     if (!ts.isFunctionLike(node.parent)) {
32909                         return;
32910                     }
32911                 // falls through
32912                 case 250 /* ModuleBlock */:
32913                     return updateStrictModeStatementList(node.statements);
32914                 case 317 /* JSDocParameterTag */:
32915                     if (node.parent.kind === 305 /* JSDocSignature */) {
32916                         return bindParameter(node);
32917                     }
32918                     if (node.parent.kind !== 304 /* JSDocTypeLiteral */) {
32919                         break;
32920                     }
32921                 // falls through
32922                 case 323 /* JSDocPropertyTag */:
32923                     var propTag = node;
32924                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 299 /* JSDocOptionalType */ ?
32925                         4 /* Property */ | 16777216 /* Optional */ :
32926                         4 /* Property */;
32927                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
32928                 case 322 /* JSDocTypedefTag */:
32929                 case 315 /* JSDocCallbackTag */:
32930                 case 316 /* JSDocEnumTag */:
32931                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
32932             }
32933         }
32934         function bindPropertyWorker(node) {
32935             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
32936         }
32937         function bindAnonymousTypeWorker(node) {
32938             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
32939         }
32940         function bindSourceFileIfExternalModule() {
32941             setExportContextFlag(file);
32942             if (ts.isExternalModule(file)) {
32943                 bindSourceFileAsExternalModule();
32944             }
32945             else if (ts.isJsonSourceFile(file)) {
32946                 bindSourceFileAsExternalModule();
32947                 // Create symbol equivalent for the module.exports = {}
32948                 var originalSymbol = file.symbol;
32949                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
32950                 file.symbol = originalSymbol;
32951             }
32952         }
32953         function bindSourceFileAsExternalModule() {
32954             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
32955         }
32956         function bindExportAssignment(node) {
32957             if (!container.symbol || !container.symbol.exports) {
32958                 // Export assignment in some sort of block construct
32959                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
32960             }
32961             else {
32962                 var flags = ts.exportAssignmentIsAlias(node)
32963                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
32964                     ? 2097152 /* Alias */
32965                     // An export default clause with any other expression exports a value
32966                     : 4 /* Property */;
32967                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
32968                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
32969                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
32970                 if (node.isExportEquals) {
32971                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
32972                     ts.setValueDeclaration(symbol, node);
32973                 }
32974             }
32975         }
32976         function bindNamespaceExportDeclaration(node) {
32977             if (node.modifiers && node.modifiers.length) {
32978                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
32979             }
32980             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
32981                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
32982                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
32983                         : undefined;
32984             if (diag) {
32985                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
32986             }
32987             else {
32988                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
32989                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
32990             }
32991         }
32992         function bindExportDeclaration(node) {
32993             if (!container.symbol || !container.symbol.exports) {
32994                 // Export * in some sort of block construct
32995                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
32996             }
32997             else if (!node.exportClause) {
32998                 // All export * declarations are collected in an __export symbol
32999                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
33000             }
33001             else if (ts.isNamespaceExport(node.exportClause)) {
33002                 // declareSymbol walks up parents to find name text, parent _must_ be set
33003                 // but won't be set by the normal binder walk until `bindChildren` later on.
33004                 node.exportClause.parent = node;
33005                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33006             }
33007         }
33008         function bindImportClause(node) {
33009             if (node.name) {
33010                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
33011             }
33012         }
33013         function setCommonJsModuleIndicator(node) {
33014             if (file.externalModuleIndicator) {
33015                 return false;
33016             }
33017             if (!file.commonJsModuleIndicator) {
33018                 file.commonJsModuleIndicator = node;
33019                 bindSourceFileAsExternalModule();
33020             }
33021             return true;
33022         }
33023         function bindObjectDefinePropertyExport(node) {
33024             if (!setCommonJsModuleIndicator(node)) {
33025                 return;
33026             }
33027             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
33028                 if (symbol) {
33029                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33030                 }
33031                 return symbol;
33032             });
33033             if (symbol) {
33034                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
33035                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
33036             }
33037         }
33038         function bindExportsPropertyAssignment(node) {
33039             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
33040             // expression is the declaration
33041             if (!setCommonJsModuleIndicator(node)) {
33042                 return;
33043             }
33044             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
33045                 if (symbol) {
33046                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
33047                 }
33048                 return symbol;
33049             });
33050             if (symbol) {
33051                 var flags = ts.isClassExpression(node.right) ?
33052                     4 /* Property */ | 1048576 /* ExportValue */ | 32 /* Class */ :
33053                     4 /* Property */ | 1048576 /* ExportValue */;
33054                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
33055             }
33056         }
33057         function bindModuleExportsAssignment(node) {
33058             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
33059             // is still pointing to 'module.exports'.
33060             // We do not want to consider this as 'export=' since a module can have only one of these.
33061             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
33062             if (!setCommonJsModuleIndicator(node)) {
33063                 return;
33064             }
33065             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
33066             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
33067                 return;
33068             }
33069             // 'module.exports = expr' assignment
33070             var flags = ts.exportAssignmentIsAlias(node)
33071                 ? 2097152 /* Alias */
33072                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
33073             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
33074             ts.setValueDeclaration(symbol, node);
33075         }
33076         function bindThisPropertyAssignment(node) {
33077             ts.Debug.assert(ts.isInJSFile(node));
33078             // private identifiers *must* be declared (even in JS files)
33079             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
33080                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
33081             if (hasPrivateIdentifier) {
33082                 return;
33083             }
33084             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
33085             switch (thisContainer.kind) {
33086                 case 244 /* FunctionDeclaration */:
33087                 case 201 /* FunctionExpression */:
33088                     var constructorSymbol = thisContainer.symbol;
33089                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
33090                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
33091                         var l = thisContainer.parent.left;
33092                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
33093                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
33094                         }
33095                     }
33096                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
33097                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
33098                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
33099                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
33100                         if (ts.hasDynamicName(node)) {
33101                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
33102                         }
33103                         else {
33104                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
33105                         }
33106                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
33107                     }
33108                     break;
33109                 case 162 /* Constructor */:
33110                 case 159 /* PropertyDeclaration */:
33111                 case 161 /* MethodDeclaration */:
33112                 case 163 /* GetAccessor */:
33113                 case 164 /* SetAccessor */:
33114                     // this.foo assignment in a JavaScript class
33115                     // Bind this property to the containing class
33116                     var containingClass = thisContainer.parent;
33117                     var symbolTable = ts.hasModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
33118                     if (ts.hasDynamicName(node)) {
33119                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
33120                     }
33121                     else {
33122                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
33123                     }
33124                     break;
33125                 case 290 /* SourceFile */:
33126                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
33127                     if (ts.hasDynamicName(node)) {
33128                         break;
33129                     }
33130                     else if (thisContainer.commonJsModuleIndicator) {
33131                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
33132                     }
33133                     else {
33134                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33135                     }
33136                     break;
33137                 default:
33138                     ts.Debug.failBadSyntaxKind(thisContainer);
33139             }
33140         }
33141         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
33142             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
33143             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
33144         }
33145         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
33146             if (symbol) {
33147                 var members = symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = ts.createMap());
33148                 members.set("" + ts.getNodeId(node), node);
33149             }
33150         }
33151         function bindSpecialPropertyDeclaration(node) {
33152             if (node.expression.kind === 104 /* ThisKeyword */) {
33153                 bindThisPropertyAssignment(node);
33154             }
33155             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 290 /* SourceFile */) {
33156                 if (ts.isPrototypeAccess(node.expression)) {
33157                     bindPrototypePropertyAssignment(node, node.parent);
33158                 }
33159                 else {
33160                     bindStaticPropertyAssignment(node);
33161                 }
33162             }
33163         }
33164         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
33165         function bindPrototypeAssignment(node) {
33166             node.left.parent = node;
33167             node.right.parent = node;
33168             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
33169         }
33170         function bindObjectDefinePrototypeProperty(node) {
33171             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
33172             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
33173                 // Ensure the namespace symbol becomes class-like
33174                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33175             }
33176             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
33177         }
33178         /**
33179          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
33180          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
33181          */
33182         function bindPrototypePropertyAssignment(lhs, parent) {
33183             // Look up the function in the local scope, since prototype assignments should
33184             // follow the function declaration
33185             var classPrototype = lhs.expression;
33186             var constructorFunction = classPrototype.expression;
33187             // Fix up parent pointers since we're going to use these nodes before we bind into them
33188             lhs.parent = parent;
33189             constructorFunction.parent = classPrototype;
33190             classPrototype.parent = lhs;
33191             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
33192         }
33193         function bindObjectDefinePropertyAssignment(node) {
33194             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
33195             var isToplevel = node.parent.parent.kind === 290 /* SourceFile */;
33196             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33197             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
33198         }
33199         function bindSpecialPropertyAssignment(node) {
33200             // Class declarations in Typescript do not allow property declarations
33201             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression);
33202             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
33203                 return;
33204             }
33205             // Fix up parent pointers since we're going to use these nodes before we bind into them
33206             node.left.parent = node;
33207             node.right.parent = node;
33208             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
33209                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
33210                 //    var util = module.exports;
33211                 //    util.property = function ...
33212                 bindExportsPropertyAssignment(node);
33213             }
33214             else if (ts.hasDynamicName(node)) {
33215                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
33216                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
33217                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
33218             }
33219             else {
33220                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
33221             }
33222         }
33223         /**
33224          * 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.
33225          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
33226          */
33227         function bindStaticPropertyAssignment(node) {
33228             ts.Debug.assert(!ts.isIdentifier(node));
33229             node.expression.parent = node;
33230             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
33231         }
33232         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
33233             if (isToplevel && !isPrototypeProperty) {
33234                 // make symbols or add declarations for intermediate containers
33235                 var flags_1 = 1536 /* Module */ | 67108864 /* Assignment */;
33236                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
33237                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
33238                     if (symbol) {
33239                         addDeclarationToSymbol(symbol, id, flags_1);
33240                         return symbol;
33241                     }
33242                     else {
33243                         var table = parent ? parent.exports :
33244                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
33245                         return declareSymbol(table, parent, id, flags_1, excludeFlags_1);
33246                     }
33247                 });
33248             }
33249             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
33250                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
33251             }
33252             return namespaceSymbol;
33253         }
33254         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
33255             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
33256                 return;
33257             }
33258             // Set up the members collection if it doesn't exist already
33259             var symbolTable = isPrototypeProperty ?
33260                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
33261                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
33262             var includes = 0 /* None */;
33263             var excludes = 0 /* None */;
33264             // Method-like
33265             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
33266                 includes = 8192 /* Method */;
33267                 excludes = 103359 /* MethodExcludes */;
33268             }
33269             // Maybe accessor-like
33270             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
33271                 if (ts.some(declaration.arguments[2].properties, function (p) {
33272                     var id = ts.getNameOfDeclaration(p);
33273                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
33274                 })) {
33275                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
33276                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
33277                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
33278                     excludes |= 78783 /* SetAccessorExcludes */;
33279                 }
33280                 if (ts.some(declaration.arguments[2].properties, function (p) {
33281                     var id = ts.getNameOfDeclaration(p);
33282                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
33283                 })) {
33284                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
33285                     excludes |= 46015 /* GetAccessorExcludes */;
33286                 }
33287             }
33288             if (includes === 0 /* None */) {
33289                 includes = 4 /* Property */;
33290                 excludes = 0 /* PropertyExcludes */;
33291             }
33292             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
33293         }
33294         function isTopLevelNamespaceAssignment(propertyAccess) {
33295             return ts.isBinaryExpression(propertyAccess.parent)
33296                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 290 /* SourceFile */
33297                 : propertyAccess.parent.parent.kind === 290 /* SourceFile */;
33298         }
33299         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
33300             var namespaceSymbol = lookupSymbolForPropertyAccess(name);
33301             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
33302             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
33303             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
33304         }
33305         /**
33306          * Javascript expando values are:
33307          * - Functions
33308          * - classes
33309          * - namespaces
33310          * - variables initialized with function expressions
33311          * -                       with class expressions
33312          * -                       with empty object literals
33313          * -                       with non-empty object literals if assigned to the prototype property
33314          */
33315         function isExpandoSymbol(symbol) {
33316             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
33317                 return true;
33318             }
33319             var node = symbol.valueDeclaration;
33320             if (node && ts.isCallExpression(node)) {
33321                 return !!ts.getAssignedExpandoInitializer(node);
33322             }
33323             var init = !node ? undefined :
33324                 ts.isVariableDeclaration(node) ? node.initializer :
33325                     ts.isBinaryExpression(node) ? node.right :
33326                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
33327                             undefined;
33328             init = init && ts.getRightMostAssignedExpression(init);
33329             if (init) {
33330                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
33331                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
33332             }
33333             return false;
33334         }
33335         function getParentOfBinaryExpression(expr) {
33336             while (ts.isBinaryExpression(expr.parent)) {
33337                 expr = expr.parent;
33338             }
33339             return expr.parent;
33340         }
33341         function lookupSymbolForPropertyAccess(node, lookupContainer) {
33342             if (lookupContainer === void 0) { lookupContainer = container; }
33343             if (ts.isIdentifier(node)) {
33344                 return lookupSymbolForNameWorker(lookupContainer, node.escapedText);
33345             }
33346             else {
33347                 var symbol = lookupSymbolForPropertyAccess(node.expression);
33348                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
33349             }
33350         }
33351         function forEachIdentifierInEntityName(e, parent, action) {
33352             if (isExportsOrModuleExportsOrAlias(file, e)) {
33353                 return file.symbol;
33354             }
33355             else if (ts.isIdentifier(e)) {
33356                 return action(e, lookupSymbolForPropertyAccess(e), parent);
33357             }
33358             else {
33359                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
33360                 var name = ts.getNameOrArgument(e);
33361                 // unreachable
33362                 if (ts.isPrivateIdentifier(name)) {
33363                     ts.Debug.fail("unexpected PrivateIdentifier");
33364                 }
33365                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
33366             }
33367         }
33368         function bindCallExpression(node) {
33369             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
33370             // this check if we've already seen the module indicator
33371             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
33372                 setCommonJsModuleIndicator(node);
33373             }
33374         }
33375         function bindClassLikeDeclaration(node) {
33376             if (node.kind === 245 /* ClassDeclaration */) {
33377                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
33378             }
33379             else {
33380                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
33381                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
33382                 // Add name of class expression into the map for semantic classifier
33383                 if (node.name) {
33384                     classifiableNames.set(node.name.escapedText, true);
33385                 }
33386             }
33387             var symbol = node.symbol;
33388             // TypeScript 1.0 spec (April 2014): 8.4
33389             // Every class automatically contains a static property member named 'prototype', the
33390             // type of which is an instantiation of the class type with type Any supplied as a type
33391             // argument for each type parameter. It is an error to explicitly declare a static
33392             // property member with the name 'prototype'.
33393             //
33394             // Note: we check for this here because this class may be merging into a module.  The
33395             // module might have an exported variable called 'prototype'.  We can't allow that as
33396             // that would clash with the built-in 'prototype' for the class.
33397             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
33398             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
33399             if (symbolExport) {
33400                 if (node.name) {
33401                     node.name.parent = node;
33402                 }
33403                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
33404             }
33405             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
33406             prototypeSymbol.parent = symbol;
33407         }
33408         function bindEnumDeclaration(node) {
33409             return ts.isEnumConst(node)
33410                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
33411                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
33412         }
33413         function bindVariableDeclarationOrBindingElement(node) {
33414             if (inStrictMode) {
33415                 checkStrictModeEvalOrArguments(node, node.name);
33416             }
33417             if (!ts.isBindingPattern(node.name)) {
33418                 if (ts.isBlockOrCatchScoped(node)) {
33419                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
33420                 }
33421                 else if (ts.isParameterDeclaration(node)) {
33422                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
33423                     // because its parent chain has already been set up, since parents are set before descending into children.
33424                     //
33425                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
33426                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
33427                     // For example:
33428                     //      function foo([a,a]) {} // Duplicate Identifier error
33429                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
33430                     //                             // which correctly set excluded symbols
33431                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33432                 }
33433                 else {
33434                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
33435                 }
33436             }
33437         }
33438         function bindParameter(node) {
33439             if (node.kind === 317 /* JSDocParameterTag */ && container.kind !== 305 /* JSDocSignature */) {
33440                 return;
33441             }
33442             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
33443                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
33444                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
33445                 checkStrictModeEvalOrArguments(node, node.name);
33446             }
33447             if (ts.isBindingPattern(node.name)) {
33448                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
33449             }
33450             else {
33451                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
33452             }
33453             // If this is a property-parameter, then also declare the property symbol into the
33454             // containing class.
33455             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
33456                 var classDeclaration = node.parent.parent;
33457                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
33458             }
33459         }
33460         function bindFunctionDeclaration(node) {
33461             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33462                 if (ts.isAsyncFunction(node)) {
33463                     emitFlags |= 2048 /* HasAsyncFunctions */;
33464                 }
33465             }
33466             checkStrictModeFunctionName(node);
33467             if (inStrictMode) {
33468                 checkStrictModeFunctionDeclaration(node);
33469                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33470             }
33471             else {
33472                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
33473             }
33474         }
33475         function bindFunctionExpression(node) {
33476             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
33477                 if (ts.isAsyncFunction(node)) {
33478                     emitFlags |= 2048 /* HasAsyncFunctions */;
33479                 }
33480             }
33481             if (currentFlow) {
33482                 node.flowNode = currentFlow;
33483             }
33484             checkStrictModeFunctionName(node);
33485             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
33486             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
33487         }
33488         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
33489             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
33490                 emitFlags |= 2048 /* HasAsyncFunctions */;
33491             }
33492             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
33493                 node.flowNode = currentFlow;
33494             }
33495             return ts.hasDynamicName(node)
33496                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
33497                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
33498         }
33499         function getInferTypeContainer(node) {
33500             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
33501             return extendsType && extendsType.parent;
33502         }
33503         function bindTypeParameter(node) {
33504             if (ts.isJSDocTemplateTag(node.parent)) {
33505                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
33506                 if (container_1) {
33507                     if (!container_1.locals) {
33508                         container_1.locals = ts.createSymbolTable();
33509                     }
33510                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33511                 }
33512                 else {
33513                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33514                 }
33515             }
33516             else if (node.parent.kind === 181 /* InferType */) {
33517                 var container_2 = getInferTypeContainer(node.parent);
33518                 if (container_2) {
33519                     if (!container_2.locals) {
33520                         container_2.locals = ts.createSymbolTable();
33521                     }
33522                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33523                 }
33524                 else {
33525                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
33526                 }
33527             }
33528             else {
33529                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
33530             }
33531         }
33532         // reachability checks
33533         function shouldReportErrorOnModuleDeclaration(node) {
33534             var instanceState = getModuleInstanceState(node);
33535             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
33536         }
33537         function checkUnreachable(node) {
33538             if (!(currentFlow.flags & 1 /* Unreachable */)) {
33539                 return false;
33540             }
33541             if (currentFlow === unreachableFlow) {
33542                 var reportError = 
33543                 // report error on all statements except empty ones
33544                 (ts.isStatementButNotDeclaration(node) && node.kind !== 224 /* EmptyStatement */) ||
33545                     // report error on class declarations
33546                     node.kind === 245 /* ClassDeclaration */ ||
33547                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
33548                     (node.kind === 249 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
33549                 if (reportError) {
33550                     currentFlow = reportedUnreachableFlow;
33551                     if (!options.allowUnreachableCode) {
33552                         // unreachable code is reported if
33553                         // - user has explicitly asked about it AND
33554                         // - statement is in not ambient context (statements in ambient context is already an error
33555                         //   so we should not report extras) AND
33556                         //   - node is not variable statement OR
33557                         //   - node is block scoped variable statement OR
33558                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
33559                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
33560                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
33561                         var isError_1 = ts.unreachableCodeIsError(options) &&
33562                             !(node.flags & 8388608 /* Ambient */) &&
33563                             (!ts.isVariableStatement(node) ||
33564                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
33565                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
33566                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
33567                     }
33568                 }
33569             }
33570             return true;
33571         }
33572     }
33573     function eachUnreachableRange(node, cb) {
33574         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
33575             var statements = node.parent.statements;
33576             var slice_1 = ts.sliceAfter(statements, node);
33577             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
33578         }
33579         else {
33580             cb(node, node);
33581         }
33582     }
33583     // As opposed to a pure declaration like an `interface`
33584     function isExecutableStatement(s) {
33585         // Don't remove statements that can validly be used before they appear.
33586         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
33587             // `var x;` may declare a variable used above
33588             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
33589     }
33590     function isPurelyTypeDeclaration(s) {
33591         switch (s.kind) {
33592             case 246 /* InterfaceDeclaration */:
33593             case 247 /* TypeAliasDeclaration */:
33594                 return true;
33595             case 249 /* ModuleDeclaration */:
33596                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
33597             case 248 /* EnumDeclaration */:
33598                 return ts.hasModifier(s, 2048 /* Const */);
33599             default:
33600                 return false;
33601         }
33602     }
33603     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
33604         var i = 0;
33605         var q = [node];
33606         while (q.length && i < 100) {
33607             i++;
33608             node = q.shift();
33609             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
33610                 return true;
33611             }
33612             else if (ts.isIdentifier(node)) {
33613                 var symbol = lookupSymbolForNameWorker(sourceFile, node.escapedText);
33614                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
33615                     var init = symbol.valueDeclaration.initializer;
33616                     q.push(init);
33617                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
33618                         q.push(init.left);
33619                         q.push(init.right);
33620                     }
33621                 }
33622             }
33623         }
33624         return false;
33625     }
33626     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
33627     function lookupSymbolForNameWorker(container, name) {
33628         var local = container.locals && container.locals.get(name);
33629         if (local) {
33630             return local.exportSymbol || local;
33631         }
33632         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
33633             return container.jsGlobalAugmentations.get(name);
33634         }
33635         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
33636     }
33637     /**
33638      * Computes the transform flags for a node, given the transform flags of its subtree
33639      *
33640      * @param node The node to analyze
33641      * @param subtreeFlags Transform flags computed for this node's subtree
33642      */
33643     function computeTransformFlagsForNode(node, subtreeFlags) {
33644         var kind = node.kind;
33645         switch (kind) {
33646             case 196 /* CallExpression */:
33647                 return computeCallExpression(node, subtreeFlags);
33648             case 197 /* NewExpression */:
33649                 return computeNewExpression(node, subtreeFlags);
33650             case 249 /* ModuleDeclaration */:
33651                 return computeModuleDeclaration(node, subtreeFlags);
33652             case 200 /* ParenthesizedExpression */:
33653                 return computeParenthesizedExpression(node, subtreeFlags);
33654             case 209 /* BinaryExpression */:
33655                 return computeBinaryExpression(node, subtreeFlags);
33656             case 226 /* ExpressionStatement */:
33657                 return computeExpressionStatement(node, subtreeFlags);
33658             case 156 /* Parameter */:
33659                 return computeParameter(node, subtreeFlags);
33660             case 202 /* ArrowFunction */:
33661                 return computeArrowFunction(node, subtreeFlags);
33662             case 201 /* FunctionExpression */:
33663                 return computeFunctionExpression(node, subtreeFlags);
33664             case 244 /* FunctionDeclaration */:
33665                 return computeFunctionDeclaration(node, subtreeFlags);
33666             case 242 /* VariableDeclaration */:
33667                 return computeVariableDeclaration(node, subtreeFlags);
33668             case 243 /* VariableDeclarationList */:
33669                 return computeVariableDeclarationList(node, subtreeFlags);
33670             case 225 /* VariableStatement */:
33671                 return computeVariableStatement(node, subtreeFlags);
33672             case 238 /* LabeledStatement */:
33673                 return computeLabeledStatement(node, subtreeFlags);
33674             case 245 /* ClassDeclaration */:
33675                 return computeClassDeclaration(node, subtreeFlags);
33676             case 214 /* ClassExpression */:
33677                 return computeClassExpression(node, subtreeFlags);
33678             case 279 /* HeritageClause */:
33679                 return computeHeritageClause(node, subtreeFlags);
33680             case 280 /* CatchClause */:
33681                 return computeCatchClause(node, subtreeFlags);
33682             case 216 /* ExpressionWithTypeArguments */:
33683                 return computeExpressionWithTypeArguments(node, subtreeFlags);
33684             case 162 /* Constructor */:
33685                 return computeConstructor(node, subtreeFlags);
33686             case 159 /* PropertyDeclaration */:
33687                 return computePropertyDeclaration(node, subtreeFlags);
33688             case 161 /* MethodDeclaration */:
33689                 return computeMethod(node, subtreeFlags);
33690             case 163 /* GetAccessor */:
33691             case 164 /* SetAccessor */:
33692                 return computeAccessor(node, subtreeFlags);
33693             case 253 /* ImportEqualsDeclaration */:
33694                 return computeImportEquals(node, subtreeFlags);
33695             case 194 /* PropertyAccessExpression */:
33696                 return computePropertyAccess(node, subtreeFlags);
33697             case 195 /* ElementAccessExpression */:
33698                 return computeElementAccess(node, subtreeFlags);
33699             case 267 /* JsxSelfClosingElement */:
33700             case 268 /* JsxOpeningElement */:
33701                 return computeJsxOpeningLikeElement(node, subtreeFlags);
33702             default:
33703                 return computeOther(node, kind, subtreeFlags);
33704         }
33705     }
33706     ts.computeTransformFlagsForNode = computeTransformFlagsForNode;
33707     function computeCallExpression(node, subtreeFlags) {
33708         var transformFlags = subtreeFlags;
33709         var callee = ts.skipOuterExpressions(node.expression);
33710         var expression = node.expression;
33711         if (node.flags & 32 /* OptionalChain */) {
33712             transformFlags |= 8 /* ContainsES2020 */;
33713         }
33714         if (node.typeArguments) {
33715             transformFlags |= 1 /* AssertTypeScript */;
33716         }
33717         if (subtreeFlags & 8192 /* ContainsRestOrSpread */ || ts.isSuperOrSuperProperty(callee)) {
33718             // If the this node contains a SpreadExpression, or is a super call, then it is an ES6
33719             // node.
33720             transformFlags |= 256 /* AssertES2015 */;
33721             if (ts.isSuperProperty(callee)) {
33722                 transformFlags |= 4096 /* ContainsLexicalThis */;
33723             }
33724         }
33725         if (expression.kind === 96 /* ImportKeyword */) {
33726             transformFlags |= 2097152 /* ContainsDynamicImport */;
33727         }
33728         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33729         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33730     }
33731     function computeNewExpression(node, subtreeFlags) {
33732         var transformFlags = subtreeFlags;
33733         if (node.typeArguments) {
33734             transformFlags |= 1 /* AssertTypeScript */;
33735         }
33736         if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
33737             // If the this node contains a SpreadElementExpression then it is an ES6
33738             // node.
33739             transformFlags |= 256 /* AssertES2015 */;
33740         }
33741         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33742         return transformFlags & ~536879104 /* ArrayLiteralOrCallOrNewExcludes */;
33743     }
33744     function computeJsxOpeningLikeElement(node, subtreeFlags) {
33745         var transformFlags = subtreeFlags | 2 /* AssertJsx */;
33746         if (node.typeArguments) {
33747             transformFlags |= 1 /* AssertTypeScript */;
33748         }
33749         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33750         return transformFlags & ~536870912 /* NodeExcludes */;
33751     }
33752     function computeBinaryExpression(node, subtreeFlags) {
33753         var transformFlags = subtreeFlags;
33754         var operatorTokenKind = node.operatorToken.kind;
33755         var leftKind = node.left.kind;
33756         if (operatorTokenKind === 60 /* QuestionQuestionToken */) {
33757             transformFlags |= 8 /* AssertES2020 */;
33758         }
33759         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 193 /* ObjectLiteralExpression */) {
33760             // Destructuring object assignments with are ES2015 syntax
33761             // and possibly ES2018 if they contain rest
33762             transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33763         }
33764         else if (operatorTokenKind === 62 /* EqualsToken */ && leftKind === 192 /* ArrayLiteralExpression */) {
33765             // Destructuring assignments are ES2015 syntax.
33766             transformFlags |= 256 /* AssertES2015 */ | 1024 /* AssertDestructuringAssignment */;
33767         }
33768         else if (operatorTokenKind === 42 /* AsteriskAsteriskToken */
33769             || operatorTokenKind === 66 /* AsteriskAsteriskEqualsToken */) {
33770             // Exponentiation is ES2016 syntax.
33771             transformFlags |= 128 /* AssertES2016 */;
33772         }
33773         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33774         return transformFlags & ~536870912 /* NodeExcludes */;
33775     }
33776     function computeParameter(node, subtreeFlags) {
33777         var transformFlags = subtreeFlags;
33778         var name = node.name;
33779         var initializer = node.initializer;
33780         var dotDotDotToken = node.dotDotDotToken;
33781         // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript
33782         // syntax.
33783         if (node.questionToken
33784             || node.type
33785             || (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */ && ts.some(node.decorators))
33786             || ts.isThisIdentifier(name)) {
33787             transformFlags |= 1 /* AssertTypeScript */;
33788         }
33789         // If a parameter has an accessibility modifier, then it is TypeScript syntax.
33790         if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
33791             transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
33792         }
33793         // parameters with object rest destructuring are ES2018 syntax
33794         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33795             transformFlags |= 32 /* AssertES2018 */;
33796         }
33797         // If a parameter has an initializer, a binding pattern or a dotDotDot token, then
33798         // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel.
33799         if (subtreeFlags & 131072 /* ContainsBindingPattern */ || initializer || dotDotDotToken) {
33800             transformFlags |= 256 /* AssertES2015 */;
33801         }
33802         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33803         return transformFlags & ~536870912 /* ParameterExcludes */;
33804     }
33805     function computeParenthesizedExpression(node, subtreeFlags) {
33806         var transformFlags = subtreeFlags;
33807         var expression = node.expression;
33808         var expressionKind = expression.kind;
33809         // If the node is synthesized, it means the emitter put the parentheses there,
33810         // not the user. If we didn't want them, the emitter would not have put them
33811         // there.
33812         if (expressionKind === 217 /* AsExpression */
33813             || expressionKind === 199 /* TypeAssertionExpression */) {
33814             transformFlags |= 1 /* AssertTypeScript */;
33815         }
33816         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33817         return transformFlags & ~536870912 /* OuterExpressionExcludes */;
33818     }
33819     function computeClassDeclaration(node, subtreeFlags) {
33820         var transformFlags;
33821         if (ts.hasModifier(node, 2 /* Ambient */)) {
33822             // An ambient declaration is TypeScript syntax.
33823             transformFlags = 1 /* AssertTypeScript */;
33824         }
33825         else {
33826             // A ClassDeclaration is ES6 syntax.
33827             transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33828             // A class with a parameter property assignment or decorator is TypeScript syntax.
33829             // An exported declaration may be TypeScript syntax, but is handled by the visitor
33830             // for a namespace declaration.
33831             if ((subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */)
33832                 || node.typeParameters) {
33833                 transformFlags |= 1 /* AssertTypeScript */;
33834             }
33835         }
33836         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33837         return transformFlags & ~536905728 /* ClassExcludes */;
33838     }
33839     function computeClassExpression(node, subtreeFlags) {
33840         // A ClassExpression is ES6 syntax.
33841         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33842         // A class with a parameter property assignment or decorator is TypeScript syntax.
33843         if (subtreeFlags & 2048 /* ContainsTypeScriptClassSyntax */
33844             || node.typeParameters) {
33845             transformFlags |= 1 /* AssertTypeScript */;
33846         }
33847         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33848         return transformFlags & ~536905728 /* ClassExcludes */;
33849     }
33850     function computeHeritageClause(node, subtreeFlags) {
33851         var transformFlags = subtreeFlags;
33852         switch (node.token) {
33853             case 90 /* ExtendsKeyword */:
33854                 // An `extends` HeritageClause is ES6 syntax.
33855                 transformFlags |= 256 /* AssertES2015 */;
33856                 break;
33857             case 113 /* ImplementsKeyword */:
33858                 // An `implements` HeritageClause is TypeScript syntax.
33859                 transformFlags |= 1 /* AssertTypeScript */;
33860                 break;
33861             default:
33862                 ts.Debug.fail("Unexpected token for heritage clause");
33863                 break;
33864         }
33865         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33866         return transformFlags & ~536870912 /* NodeExcludes */;
33867     }
33868     function computeCatchClause(node, subtreeFlags) {
33869         var transformFlags = subtreeFlags;
33870         if (!node.variableDeclaration) {
33871             transformFlags |= 16 /* AssertES2019 */;
33872         }
33873         else if (ts.isBindingPattern(node.variableDeclaration.name)) {
33874             transformFlags |= 256 /* AssertES2015 */;
33875         }
33876         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33877         return transformFlags & ~536887296 /* CatchClauseExcludes */;
33878     }
33879     function computeExpressionWithTypeArguments(node, subtreeFlags) {
33880         // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
33881         // extends clause of a class.
33882         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33883         // If an ExpressionWithTypeArguments contains type arguments, then it
33884         // is TypeScript syntax.
33885         if (node.typeArguments) {
33886             transformFlags |= 1 /* AssertTypeScript */;
33887         }
33888         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33889         return transformFlags & ~536870912 /* NodeExcludes */;
33890     }
33891     function computeConstructor(node, subtreeFlags) {
33892         var transformFlags = subtreeFlags;
33893         // TypeScript-specific modifiers and overloads are TypeScript syntax
33894         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33895             || !node.body) {
33896             transformFlags |= 1 /* AssertTypeScript */;
33897         }
33898         // function declarations with object rest destructuring are ES2018 syntax
33899         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33900             transformFlags |= 32 /* AssertES2018 */;
33901         }
33902         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33903         return transformFlags & ~538923008 /* ConstructorExcludes */;
33904     }
33905     function computeMethod(node, subtreeFlags) {
33906         // A MethodDeclaration is ES6 syntax.
33907         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
33908         // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and
33909         // overloads are TypeScript syntax.
33910         if (node.decorators
33911             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33912             || node.typeParameters
33913             || node.type
33914             || !node.body
33915             || node.questionToken) {
33916             transformFlags |= 1 /* AssertTypeScript */;
33917         }
33918         // function declarations with object rest destructuring are ES2018 syntax
33919         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33920             transformFlags |= 32 /* AssertES2018 */;
33921         }
33922         // An async method declaration is ES2017 syntax.
33923         if (ts.hasModifier(node, 256 /* Async */)) {
33924             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33925         }
33926         if (node.asteriskToken) {
33927             transformFlags |= 512 /* AssertGenerator */;
33928         }
33929         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33930         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33931     }
33932     function computeAccessor(node, subtreeFlags) {
33933         var transformFlags = subtreeFlags;
33934         // Decorators, TypeScript-specific modifiers, type annotations, and overloads are
33935         // TypeScript syntax.
33936         if (node.decorators
33937             || ts.hasModifier(node, 2270 /* TypeScriptModifier */)
33938             || node.type
33939             || !node.body) {
33940             transformFlags |= 1 /* AssertTypeScript */;
33941         }
33942         // function declarations with object rest destructuring are ES2018 syntax
33943         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33944             transformFlags |= 32 /* AssertES2018 */;
33945         }
33946         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33947         return propagatePropertyNameFlags(node.name, transformFlags & ~538923008 /* MethodOrAccessorExcludes */);
33948     }
33949     function computePropertyDeclaration(node, subtreeFlags) {
33950         var transformFlags = subtreeFlags | 4194304 /* ContainsClassFields */;
33951         // Decorators, TypeScript-specific modifiers, and type annotations are TypeScript syntax.
33952         if (ts.some(node.decorators) || ts.hasModifier(node, 2270 /* TypeScriptModifier */) || node.type || node.questionToken || node.exclamationToken) {
33953             transformFlags |= 1 /* AssertTypeScript */;
33954         }
33955         // Hoisted variables related to class properties should live within the TypeScript class wrapper.
33956         if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
33957             transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
33958         }
33959         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33960         return propagatePropertyNameFlags(node.name, transformFlags & ~536875008 /* PropertyExcludes */);
33961     }
33962     function computeFunctionDeclaration(node, subtreeFlags) {
33963         var transformFlags;
33964         var modifierFlags = ts.getModifierFlags(node);
33965         var body = node.body;
33966         if (!body || (modifierFlags & 2 /* Ambient */)) {
33967             // An ambient declaration is TypeScript syntax.
33968             // A FunctionDeclaration without a body is an overload and is TypeScript syntax.
33969             transformFlags = 1 /* AssertTypeScript */;
33970         }
33971         else {
33972             transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
33973             // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
33974             // syntax.
33975             if (modifierFlags & 2270 /* TypeScriptModifier */
33976                 || node.typeParameters
33977                 || node.type) {
33978                 transformFlags |= 1 /* AssertTypeScript */;
33979             }
33980             // An async function declaration is ES2017 syntax.
33981             if (modifierFlags & 256 /* Async */) {
33982                 transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
33983             }
33984             // function declarations with object rest destructuring are ES2018 syntax
33985             if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
33986                 transformFlags |= 32 /* AssertES2018 */;
33987             }
33988             // If a FunctionDeclaration is generator function and is the body of a
33989             // transformed async function, then this node can be transformed to a
33990             // down-level generator.
33991             // Currently we do not support transforming any other generator functions
33992             // down level.
33993             if (node.asteriskToken) {
33994                 transformFlags |= 512 /* AssertGenerator */;
33995             }
33996         }
33997         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
33998         return transformFlags & ~538925056 /* FunctionExcludes */;
33999     }
34000     function computeFunctionExpression(node, subtreeFlags) {
34001         var transformFlags = subtreeFlags;
34002         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34003         // syntax.
34004         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34005             || node.typeParameters
34006             || node.type) {
34007             transformFlags |= 1 /* AssertTypeScript */;
34008         }
34009         // An async function expression is ES2017 syntax.
34010         if (ts.hasModifier(node, 256 /* Async */)) {
34011             transformFlags |= node.asteriskToken ? 32 /* AssertES2018 */ : 64 /* AssertES2017 */;
34012         }
34013         // function expressions with object rest destructuring are ES2018 syntax
34014         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34015             transformFlags |= 32 /* AssertES2018 */;
34016         }
34017         // If a FunctionExpression is generator function and is the body of a
34018         // transformed async function, then this node can be transformed to a
34019         // down-level generator.
34020         if (node.asteriskToken) {
34021             transformFlags |= 512 /* AssertGenerator */;
34022         }
34023         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34024         return transformFlags & ~538925056 /* FunctionExcludes */;
34025     }
34026     function computeArrowFunction(node, subtreeFlags) {
34027         // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction.
34028         var transformFlags = subtreeFlags | 256 /* AssertES2015 */;
34029         // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript
34030         // syntax.
34031         if (ts.hasModifier(node, 2270 /* TypeScriptModifier */)
34032             || node.typeParameters
34033             || node.type) {
34034             transformFlags |= 1 /* AssertTypeScript */;
34035         }
34036         // An async arrow function is ES2017 syntax.
34037         if (ts.hasModifier(node, 256 /* Async */)) {
34038             transformFlags |= 64 /* AssertES2017 */;
34039         }
34040         // arrow functions with object rest destructuring are ES2018 syntax
34041         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34042             transformFlags |= 32 /* AssertES2018 */;
34043         }
34044         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34045         return transformFlags & ~538920960 /* ArrowFunctionExcludes */;
34046     }
34047     function computePropertyAccess(node, subtreeFlags) {
34048         var transformFlags = subtreeFlags;
34049         if (node.flags & 32 /* OptionalChain */) {
34050             transformFlags |= 8 /* ContainsES2020 */;
34051         }
34052         // If a PropertyAccessExpression starts with a super keyword, then it is
34053         // ES6 syntax, and requires a lexical `this` binding.
34054         if (node.expression.kind === 102 /* SuperKeyword */) {
34055             // super inside of an async function requires hoisting the super access (ES2017).
34056             // same for super inside of an async generator, which is ES2018.
34057             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34058         }
34059         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34060         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34061     }
34062     function computeElementAccess(node, subtreeFlags) {
34063         var transformFlags = subtreeFlags;
34064         if (node.flags & 32 /* OptionalChain */) {
34065             transformFlags |= 8 /* ContainsES2020 */;
34066         }
34067         // If an ElementAccessExpression starts with a super keyword, then it is
34068         // ES6 syntax, and requires a lexical `this` binding.
34069         if (node.expression.kind === 102 /* SuperKeyword */) {
34070             // super inside of an async function requires hoisting the super access (ES2017).
34071             // same for super inside of an async generator, which is ES2018.
34072             transformFlags |= 64 /* ContainsES2017 */ | 32 /* ContainsES2018 */;
34073         }
34074         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34075         return transformFlags & ~536870912 /* PropertyAccessExcludes */;
34076     }
34077     function computeVariableDeclaration(node, subtreeFlags) {
34078         var transformFlags = subtreeFlags;
34079         transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */; // TODO(rbuckton): Why are these set unconditionally?
34080         // A VariableDeclaration containing ObjectRest is ES2018 syntax
34081         if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34082             transformFlags |= 32 /* AssertES2018 */;
34083         }
34084         // Type annotations are TypeScript syntax.
34085         if (node.type || node.exclamationToken) {
34086             transformFlags |= 1 /* AssertTypeScript */;
34087         }
34088         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34089         return transformFlags & ~536870912 /* NodeExcludes */;
34090     }
34091     function computeVariableStatement(node, subtreeFlags) {
34092         var transformFlags;
34093         var declarationListTransformFlags = node.declarationList.transformFlags;
34094         // An ambient declaration is TypeScript syntax.
34095         if (ts.hasModifier(node, 2 /* Ambient */)) {
34096             transformFlags = 1 /* AssertTypeScript */;
34097         }
34098         else {
34099             transformFlags = subtreeFlags;
34100             if (declarationListTransformFlags & 131072 /* ContainsBindingPattern */) {
34101                 transformFlags |= 256 /* AssertES2015 */;
34102             }
34103         }
34104         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34105         return transformFlags & ~536870912 /* NodeExcludes */;
34106     }
34107     function computeLabeledStatement(node, subtreeFlags) {
34108         var transformFlags = subtreeFlags;
34109         // A labeled statement containing a block scoped binding *may* need to be transformed from ES6.
34110         if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */
34111             && ts.isIterationStatement(node, /*lookInLabeledStatements*/ true)) {
34112             transformFlags |= 256 /* AssertES2015 */;
34113         }
34114         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34115         return transformFlags & ~536870912 /* NodeExcludes */;
34116     }
34117     function computeImportEquals(node, subtreeFlags) {
34118         var transformFlags = subtreeFlags;
34119         // An ImportEqualsDeclaration with a namespace reference is TypeScript.
34120         if (!ts.isExternalModuleImportEqualsDeclaration(node)) {
34121             transformFlags |= 1 /* AssertTypeScript */;
34122         }
34123         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34124         return transformFlags & ~536870912 /* NodeExcludes */;
34125     }
34126     function computeExpressionStatement(node, subtreeFlags) {
34127         var transformFlags = subtreeFlags;
34128         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34129         return transformFlags & ~536870912 /* NodeExcludes */;
34130     }
34131     function computeModuleDeclaration(node, subtreeFlags) {
34132         var transformFlags = 1 /* AssertTypeScript */;
34133         var modifierFlags = ts.getModifierFlags(node);
34134         if ((modifierFlags & 2 /* Ambient */) === 0) {
34135             transformFlags |= subtreeFlags;
34136         }
34137         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34138         return transformFlags & ~537991168 /* ModuleExcludes */;
34139     }
34140     function computeVariableDeclarationList(node, subtreeFlags) {
34141         var transformFlags = subtreeFlags | 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34142         if (subtreeFlags & 131072 /* ContainsBindingPattern */) {
34143             transformFlags |= 256 /* AssertES2015 */;
34144         }
34145         // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax.
34146         if (node.flags & 3 /* BlockScoped */) {
34147             transformFlags |= 256 /* AssertES2015 */ | 65536 /* ContainsBlockScopedBinding */;
34148         }
34149         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34150         return transformFlags & ~537018368 /* VariableDeclarationListExcludes */;
34151     }
34152     function computeOther(node, kind, subtreeFlags) {
34153         // Mark transformations needed for each node
34154         var transformFlags = subtreeFlags;
34155         var excludeFlags = 536870912 /* NodeExcludes */;
34156         switch (kind) {
34157             case 126 /* AsyncKeyword */:
34158                 // async is ES2017 syntax, but may be ES2018 syntax (for async generators)
34159                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */;
34160                 break;
34161             case 206 /* AwaitExpression */:
34162                 // await is ES2017 syntax, but may be ES2018 syntax (for async generators)
34163                 transformFlags |= 32 /* AssertES2018 */ | 64 /* AssertES2017 */ | 524288 /* ContainsAwait */;
34164                 break;
34165             case 199 /* TypeAssertionExpression */:
34166             case 217 /* AsExpression */:
34167             case 326 /* PartiallyEmittedExpression */:
34168                 // These nodes are TypeScript syntax.
34169                 transformFlags |= 1 /* AssertTypeScript */;
34170                 excludeFlags = 536870912 /* OuterExpressionExcludes */;
34171                 break;
34172             case 119 /* PublicKeyword */:
34173             case 117 /* PrivateKeyword */:
34174             case 118 /* ProtectedKeyword */:
34175             case 122 /* AbstractKeyword */:
34176             case 130 /* DeclareKeyword */:
34177             case 81 /* ConstKeyword */:
34178             case 248 /* EnumDeclaration */:
34179             case 284 /* EnumMember */:
34180             case 218 /* NonNullExpression */:
34181             case 138 /* ReadonlyKeyword */:
34182                 // These nodes are TypeScript syntax.
34183                 transformFlags |= 1 /* AssertTypeScript */;
34184                 break;
34185             case 266 /* JsxElement */:
34186             case 11 /* JsxText */:
34187             case 269 /* JsxClosingElement */:
34188             case 270 /* JsxFragment */:
34189             case 271 /* JsxOpeningFragment */:
34190             case 272 /* JsxClosingFragment */:
34191             case 273 /* JsxAttribute */:
34192             case 274 /* JsxAttributes */:
34193             case 275 /* JsxSpreadAttribute */:
34194             case 276 /* JsxExpression */:
34195                 // These nodes are Jsx syntax.
34196                 transformFlags |= 2 /* AssertJsx */;
34197                 break;
34198             case 14 /* NoSubstitutionTemplateLiteral */:
34199             case 15 /* TemplateHead */:
34200             case 16 /* TemplateMiddle */:
34201             case 17 /* TemplateTail */:
34202                 if (node.templateFlags) {
34203                     transformFlags |= 32 /* AssertES2018 */;
34204                     break;
34205                 }
34206             // falls through
34207             case 198 /* TaggedTemplateExpression */:
34208                 if (ts.hasInvalidEscape(node.template)) {
34209                     transformFlags |= 32 /* AssertES2018 */;
34210                     break;
34211                 }
34212             // falls through
34213             case 211 /* TemplateExpression */:
34214             case 282 /* ShorthandPropertyAssignment */:
34215             case 120 /* StaticKeyword */:
34216             case 219 /* MetaProperty */:
34217                 // These nodes are ES6 syntax.
34218                 transformFlags |= 256 /* AssertES2015 */;
34219                 break;
34220             case 10 /* StringLiteral */:
34221                 if (node.hasExtendedUnicodeEscape) {
34222                     transformFlags |= 256 /* AssertES2015 */;
34223                 }
34224                 break;
34225             case 8 /* NumericLiteral */:
34226                 if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
34227                     transformFlags |= 256 /* AssertES2015 */;
34228                 }
34229                 break;
34230             case 9 /* BigIntLiteral */:
34231                 transformFlags |= 4 /* AssertESNext */;
34232                 break;
34233             case 232 /* ForOfStatement */:
34234                 // This node is either ES2015 syntax or ES2017 syntax (if it is a for-await-of).
34235                 if (node.awaitModifier) {
34236                     transformFlags |= 32 /* AssertES2018 */;
34237                 }
34238                 transformFlags |= 256 /* AssertES2015 */;
34239                 break;
34240             case 212 /* YieldExpression */:
34241                 // This node is either ES2015 syntax (in a generator) or ES2017 syntax (in an async
34242                 // generator).
34243                 transformFlags |= 32 /* AssertES2018 */ | 256 /* AssertES2015 */ | 262144 /* ContainsYield */;
34244                 break;
34245             case 125 /* AnyKeyword */:
34246             case 140 /* NumberKeyword */:
34247             case 151 /* BigIntKeyword */:
34248             case 137 /* NeverKeyword */:
34249             case 141 /* ObjectKeyword */:
34250             case 143 /* StringKeyword */:
34251             case 128 /* BooleanKeyword */:
34252             case 144 /* SymbolKeyword */:
34253             case 110 /* VoidKeyword */:
34254             case 155 /* TypeParameter */:
34255             case 158 /* PropertySignature */:
34256             case 160 /* MethodSignature */:
34257             case 165 /* CallSignature */:
34258             case 166 /* ConstructSignature */:
34259             case 167 /* IndexSignature */:
34260             case 168 /* TypePredicate */:
34261             case 169 /* TypeReference */:
34262             case 170 /* FunctionType */:
34263             case 171 /* ConstructorType */:
34264             case 172 /* TypeQuery */:
34265             case 173 /* TypeLiteral */:
34266             case 174 /* ArrayType */:
34267             case 175 /* TupleType */:
34268             case 176 /* OptionalType */:
34269             case 177 /* RestType */:
34270             case 178 /* UnionType */:
34271             case 179 /* IntersectionType */:
34272             case 180 /* ConditionalType */:
34273             case 181 /* InferType */:
34274             case 182 /* ParenthesizedType */:
34275             case 246 /* InterfaceDeclaration */:
34276             case 247 /* TypeAliasDeclaration */:
34277             case 183 /* ThisType */:
34278             case 184 /* TypeOperator */:
34279             case 185 /* IndexedAccessType */:
34280             case 186 /* MappedType */:
34281             case 187 /* LiteralType */:
34282             case 252 /* NamespaceExportDeclaration */:
34283                 // Types and signatures are TypeScript syntax, and exclude all other facts.
34284                 transformFlags = 1 /* AssertTypeScript */;
34285                 excludeFlags = -2 /* TypeExcludes */;
34286                 break;
34287             case 154 /* ComputedPropertyName */:
34288                 // Even though computed property names are ES6, we don't treat them as such.
34289                 // This is so that they can flow through PropertyName transforms unaffected.
34290                 // Instead, we mark the container as ES6, so that it can properly handle the transform.
34291                 transformFlags |= 32768 /* ContainsComputedPropertyName */;
34292                 break;
34293             case 213 /* SpreadElement */:
34294                 transformFlags |= 256 /* AssertES2015 */ | 8192 /* ContainsRestOrSpread */;
34295                 break;
34296             case 283 /* SpreadAssignment */:
34297                 transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34298                 break;
34299             case 102 /* SuperKeyword */:
34300                 // This node is ES6 syntax.
34301                 transformFlags |= 256 /* AssertES2015 */;
34302                 excludeFlags = 536870912 /* OuterExpressionExcludes */; // must be set to persist `Super`
34303                 break;
34304             case 104 /* ThisKeyword */:
34305                 // Mark this node and its ancestors as containing a lexical `this` keyword.
34306                 transformFlags |= 4096 /* ContainsLexicalThis */;
34307                 break;
34308             case 189 /* ObjectBindingPattern */:
34309                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34310                 if (subtreeFlags & 8192 /* ContainsRestOrSpread */) {
34311                     transformFlags |= 32 /* AssertES2018 */ | 16384 /* ContainsObjectRestOrSpread */;
34312                 }
34313                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34314                 break;
34315             case 190 /* ArrayBindingPattern */:
34316                 transformFlags |= 256 /* AssertES2015 */ | 131072 /* ContainsBindingPattern */;
34317                 excludeFlags = 536879104 /* BindingPatternExcludes */;
34318                 break;
34319             case 191 /* BindingElement */:
34320                 transformFlags |= 256 /* AssertES2015 */;
34321                 if (node.dotDotDotToken) {
34322                     transformFlags |= 8192 /* ContainsRestOrSpread */;
34323                 }
34324                 break;
34325             case 157 /* Decorator */:
34326                 // This node is TypeScript syntax, and marks its container as also being TypeScript syntax.
34327                 transformFlags |= 1 /* AssertTypeScript */ | 2048 /* ContainsTypeScriptClassSyntax */;
34328                 break;
34329             case 193 /* ObjectLiteralExpression */:
34330                 excludeFlags = 536922112 /* ObjectLiteralExcludes */;
34331                 if (subtreeFlags & 32768 /* ContainsComputedPropertyName */) {
34332                     // If an ObjectLiteralExpression contains a ComputedPropertyName, then it
34333                     // is an ES6 node.
34334                     transformFlags |= 256 /* AssertES2015 */;
34335                 }
34336                 if (subtreeFlags & 16384 /* ContainsObjectRestOrSpread */) {
34337                     // If an ObjectLiteralExpression contains a spread element, then it
34338                     // is an ES2018 node.
34339                     transformFlags |= 32 /* AssertES2018 */;
34340                 }
34341                 break;
34342             case 192 /* ArrayLiteralExpression */:
34343                 excludeFlags = 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34344                 break;
34345             case 228 /* DoStatement */:
34346             case 229 /* WhileStatement */:
34347             case 230 /* ForStatement */:
34348             case 231 /* ForInStatement */:
34349                 // A loop containing a block scoped binding *may* need to be transformed from ES6.
34350                 if (subtreeFlags & 65536 /* ContainsBlockScopedBinding */) {
34351                     transformFlags |= 256 /* AssertES2015 */;
34352                 }
34353                 break;
34354             case 290 /* SourceFile */:
34355                 break;
34356             case 262 /* NamespaceExport */:
34357                 transformFlags |= 4 /* AssertESNext */;
34358                 break;
34359             case 235 /* ReturnStatement */:
34360                 // Return statements may require an `await` in ES2018.
34361                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */ | 32 /* AssertES2018 */;
34362                 break;
34363             case 233 /* ContinueStatement */:
34364             case 234 /* BreakStatement */:
34365                 transformFlags |= 1048576 /* ContainsHoistedDeclarationOrCompletion */;
34366                 break;
34367             case 76 /* PrivateIdentifier */:
34368                 transformFlags |= 4194304 /* ContainsClassFields */;
34369                 break;
34370         }
34371         node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */;
34372         return transformFlags & ~excludeFlags;
34373     }
34374     function propagatePropertyNameFlags(node, transformFlags) {
34375         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
34376     }
34377     /**
34378      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
34379      *
34380      * NOTE: This needs to be kept up-to-date with the exclusions used in `computeTransformFlagsForNode`.
34381      *       For performance reasons, `computeTransformFlagsForNode` uses local constant values rather
34382      *       than calling this function.
34383      */
34384     function getTransformFlagsSubtreeExclusions(kind) {
34385         if (kind >= 168 /* FirstTypeNode */ && kind <= 188 /* LastTypeNode */) {
34386             return -2 /* TypeExcludes */;
34387         }
34388         switch (kind) {
34389             case 196 /* CallExpression */:
34390             case 197 /* NewExpression */:
34391             case 192 /* ArrayLiteralExpression */:
34392                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
34393             case 249 /* ModuleDeclaration */:
34394                 return 537991168 /* ModuleExcludes */;
34395             case 156 /* Parameter */:
34396                 return 536870912 /* ParameterExcludes */;
34397             case 202 /* ArrowFunction */:
34398                 return 538920960 /* ArrowFunctionExcludes */;
34399             case 201 /* FunctionExpression */:
34400             case 244 /* FunctionDeclaration */:
34401                 return 538925056 /* FunctionExcludes */;
34402             case 243 /* VariableDeclarationList */:
34403                 return 537018368 /* VariableDeclarationListExcludes */;
34404             case 245 /* ClassDeclaration */:
34405             case 214 /* ClassExpression */:
34406                 return 536905728 /* ClassExcludes */;
34407             case 162 /* Constructor */:
34408                 return 538923008 /* ConstructorExcludes */;
34409             case 161 /* MethodDeclaration */:
34410             case 163 /* GetAccessor */:
34411             case 164 /* SetAccessor */:
34412                 return 538923008 /* MethodOrAccessorExcludes */;
34413             case 125 /* AnyKeyword */:
34414             case 140 /* NumberKeyword */:
34415             case 151 /* BigIntKeyword */:
34416             case 137 /* NeverKeyword */:
34417             case 143 /* StringKeyword */:
34418             case 141 /* ObjectKeyword */:
34419             case 128 /* BooleanKeyword */:
34420             case 144 /* SymbolKeyword */:
34421             case 110 /* VoidKeyword */:
34422             case 155 /* TypeParameter */:
34423             case 158 /* PropertySignature */:
34424             case 160 /* MethodSignature */:
34425             case 165 /* CallSignature */:
34426             case 166 /* ConstructSignature */:
34427             case 167 /* IndexSignature */:
34428             case 246 /* InterfaceDeclaration */:
34429             case 247 /* TypeAliasDeclaration */:
34430                 return -2 /* TypeExcludes */;
34431             case 193 /* ObjectLiteralExpression */:
34432                 return 536922112 /* ObjectLiteralExcludes */;
34433             case 280 /* CatchClause */:
34434                 return 536887296 /* CatchClauseExcludes */;
34435             case 189 /* ObjectBindingPattern */:
34436             case 190 /* ArrayBindingPattern */:
34437                 return 536879104 /* BindingPatternExcludes */;
34438             case 199 /* TypeAssertionExpression */:
34439             case 217 /* AsExpression */:
34440             case 326 /* PartiallyEmittedExpression */:
34441             case 200 /* ParenthesizedExpression */:
34442             case 102 /* SuperKeyword */:
34443                 return 536870912 /* OuterExpressionExcludes */;
34444             case 194 /* PropertyAccessExpression */:
34445             case 195 /* ElementAccessExpression */:
34446                 return 536870912 /* PropertyAccessExcludes */;
34447             default:
34448                 return 536870912 /* NodeExcludes */;
34449         }
34450     }
34451     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
34452     /**
34453      * "Binds" JSDoc nodes in TypeScript code.
34454      * Since we will never create symbols for JSDoc, we just set parent pointers instead.
34455      */
34456     function setParentPointers(parent, child) {
34457         child.parent = parent;
34458         ts.forEachChild(child, function (grandchild) { return setParentPointers(child, grandchild); });
34459     }
34460 })(ts || (ts = {}));
34461 /** @internal */
34462 var ts;
34463 (function (ts) {
34464     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
34465         return getSymbolWalker;
34466         function getSymbolWalker(accept) {
34467             if (accept === void 0) { accept = function () { return true; }; }
34468             var visitedTypes = []; // Sparse array from id to type
34469             var visitedSymbols = []; // Sparse array from id to symbol
34470             return {
34471                 walkType: function (type) {
34472                     try {
34473                         visitType(type);
34474                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34475                     }
34476                     finally {
34477                         ts.clear(visitedTypes);
34478                         ts.clear(visitedSymbols);
34479                     }
34480                 },
34481                 walkSymbol: function (symbol) {
34482                     try {
34483                         visitSymbol(symbol);
34484                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
34485                     }
34486                     finally {
34487                         ts.clear(visitedTypes);
34488                         ts.clear(visitedSymbols);
34489                     }
34490                 },
34491             };
34492             function visitType(type) {
34493                 if (!type) {
34494                     return;
34495                 }
34496                 if (visitedTypes[type.id]) {
34497                     return;
34498                 }
34499                 visitedTypes[type.id] = type;
34500                 // Reuse visitSymbol to visit the type's symbol,
34501                 //  but be sure to bail on recuring into the type if accept declines the symbol.
34502                 var shouldBail = visitSymbol(type.symbol);
34503                 if (shouldBail)
34504                     return;
34505                 // Visit the type's related types, if any
34506                 if (type.flags & 524288 /* Object */) {
34507                     var objectType = type;
34508                     var objectFlags = objectType.objectFlags;
34509                     if (objectFlags & 4 /* Reference */) {
34510                         visitTypeReference(type);
34511                     }
34512                     if (objectFlags & 32 /* Mapped */) {
34513                         visitMappedType(type);
34514                     }
34515                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
34516                         visitInterfaceType(type);
34517                     }
34518                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
34519                         visitObjectType(objectType);
34520                     }
34521                 }
34522                 if (type.flags & 262144 /* TypeParameter */) {
34523                     visitTypeParameter(type);
34524                 }
34525                 if (type.flags & 3145728 /* UnionOrIntersection */) {
34526                     visitUnionOrIntersectionType(type);
34527                 }
34528                 if (type.flags & 4194304 /* Index */) {
34529                     visitIndexType(type);
34530                 }
34531                 if (type.flags & 8388608 /* IndexedAccess */) {
34532                     visitIndexedAccessType(type);
34533                 }
34534             }
34535             function visitTypeReference(type) {
34536                 visitType(type.target);
34537                 ts.forEach(getTypeArguments(type), visitType);
34538             }
34539             function visitTypeParameter(type) {
34540                 visitType(getConstraintOfTypeParameter(type));
34541             }
34542             function visitUnionOrIntersectionType(type) {
34543                 ts.forEach(type.types, visitType);
34544             }
34545             function visitIndexType(type) {
34546                 visitType(type.type);
34547             }
34548             function visitIndexedAccessType(type) {
34549                 visitType(type.objectType);
34550                 visitType(type.indexType);
34551                 visitType(type.constraint);
34552             }
34553             function visitMappedType(type) {
34554                 visitType(type.typeParameter);
34555                 visitType(type.constraintType);
34556                 visitType(type.templateType);
34557                 visitType(type.modifiersType);
34558             }
34559             function visitSignature(signature) {
34560                 var typePredicate = getTypePredicateOfSignature(signature);
34561                 if (typePredicate) {
34562                     visitType(typePredicate.type);
34563                 }
34564                 ts.forEach(signature.typeParameters, visitType);
34565                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
34566                     var parameter = _a[_i];
34567                     visitSymbol(parameter);
34568                 }
34569                 visitType(getRestTypeOfSignature(signature));
34570                 visitType(getReturnTypeOfSignature(signature));
34571             }
34572             function visitInterfaceType(interfaceT) {
34573                 visitObjectType(interfaceT);
34574                 ts.forEach(interfaceT.typeParameters, visitType);
34575                 ts.forEach(getBaseTypes(interfaceT), visitType);
34576                 visitType(interfaceT.thisType);
34577             }
34578             function visitObjectType(type) {
34579                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
34580                 visitType(stringIndexType);
34581                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
34582                 visitType(numberIndexType);
34583                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
34584                 var resolved = resolveStructuredTypeMembers(type);
34585                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
34586                     var signature = _a[_i];
34587                     visitSignature(signature);
34588                 }
34589                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
34590                     var signature = _c[_b];
34591                     visitSignature(signature);
34592                 }
34593                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
34594                     var p = _e[_d];
34595                     visitSymbol(p);
34596                 }
34597             }
34598             function visitSymbol(symbol) {
34599                 if (!symbol) {
34600                     return false;
34601                 }
34602                 var symbolId = ts.getSymbolId(symbol);
34603                 if (visitedSymbols[symbolId]) {
34604                     return false;
34605                 }
34606                 visitedSymbols[symbolId] = symbol;
34607                 if (!accept(symbol)) {
34608                     return true;
34609                 }
34610                 var t = getTypeOfSymbol(symbol);
34611                 visitType(t); // Should handle members on classes and such
34612                 if (symbol.exports) {
34613                     symbol.exports.forEach(visitSymbol);
34614                 }
34615                 ts.forEach(symbol.declarations, function (d) {
34616                     // Type queries are too far resolved when we just visit the symbol's type
34617                     //  (their type resolved directly to the member deeply referenced)
34618                     // So to get the intervening symbols, we need to check if there's a type
34619                     // query node on any of the symbol's declarations and get symbols there
34620                     if (d.type && d.type.kind === 172 /* TypeQuery */) {
34621                         var query = d.type;
34622                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
34623                         visitSymbol(entity);
34624                     }
34625                 });
34626                 return false;
34627             }
34628         }
34629     }
34630     ts.createGetSymbolWalker = createGetSymbolWalker;
34631 })(ts || (ts = {}));
34632 /* @internal */
34633 var ts;
34634 (function (ts) {
34635     var ambientModuleSymbolRegex = /^".+"$/;
34636     var anon = "(anonymous)";
34637     var nextSymbolId = 1;
34638     var nextNodeId = 1;
34639     var nextMergeId = 1;
34640     var nextFlowId = 1;
34641     var IterationUse;
34642     (function (IterationUse) {
34643         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
34644         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
34645         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
34646         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
34647         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
34648         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
34649         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
34650         // Spread, Destructuring, Array element assignment
34651         IterationUse[IterationUse["Element"] = 1] = "Element";
34652         IterationUse[IterationUse["Spread"] = 33] = "Spread";
34653         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
34654         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
34655         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
34656         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
34657         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
34658         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
34659         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
34660     })(IterationUse || (IterationUse = {}));
34661     var IterationTypeKind;
34662     (function (IterationTypeKind) {
34663         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
34664         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
34665         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
34666     })(IterationTypeKind || (IterationTypeKind = {}));
34667     var WideningKind;
34668     (function (WideningKind) {
34669         WideningKind[WideningKind["Normal"] = 0] = "Normal";
34670         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
34671         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
34672         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
34673     })(WideningKind || (WideningKind = {}));
34674     var TypeFacts;
34675     (function (TypeFacts) {
34676         TypeFacts[TypeFacts["None"] = 0] = "None";
34677         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
34678         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
34679         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
34680         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
34681         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
34682         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
34683         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
34684         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
34685         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
34686         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
34687         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
34688         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
34689         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
34690         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
34691         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
34692         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
34693         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
34694         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
34695         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
34696         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
34697         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
34698         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
34699         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
34700         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
34701         TypeFacts[TypeFacts["All"] = 16777215] = "All";
34702         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
34703         // The presence of a particular fact means that the given test is true for some (and possibly all) values
34704         // of that kind of type.
34705         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
34706         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
34707         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
34708         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
34709         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
34710         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
34711         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
34712         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
34713         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
34714         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
34715         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
34716         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
34717         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
34718         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
34719         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
34720         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
34721         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
34722         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
34723         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
34724         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
34725         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
34726         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
34727         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
34728         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
34729         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
34730         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
34731         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
34732         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
34733         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
34734         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
34735         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
34736         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
34737         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
34738         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
34739         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
34740         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
34741         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
34742         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
34743         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
34744         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
34745         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
34746         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
34747     })(TypeFacts || (TypeFacts = {}));
34748     var typeofEQFacts = ts.createMapFromTemplate({
34749         string: 1 /* TypeofEQString */,
34750         number: 2 /* TypeofEQNumber */,
34751         bigint: 4 /* TypeofEQBigInt */,
34752         boolean: 8 /* TypeofEQBoolean */,
34753         symbol: 16 /* TypeofEQSymbol */,
34754         undefined: 65536 /* EQUndefined */,
34755         object: 32 /* TypeofEQObject */,
34756         function: 64 /* TypeofEQFunction */
34757     });
34758     var typeofNEFacts = ts.createMapFromTemplate({
34759         string: 256 /* TypeofNEString */,
34760         number: 512 /* TypeofNENumber */,
34761         bigint: 1024 /* TypeofNEBigInt */,
34762         boolean: 2048 /* TypeofNEBoolean */,
34763         symbol: 4096 /* TypeofNESymbol */,
34764         undefined: 524288 /* NEUndefined */,
34765         object: 8192 /* TypeofNEObject */,
34766         function: 16384 /* TypeofNEFunction */
34767     });
34768     var TypeSystemPropertyName;
34769     (function (TypeSystemPropertyName) {
34770         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
34771         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
34772         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
34773         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
34774         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
34775         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
34776         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
34777     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
34778     var CheckMode;
34779     (function (CheckMode) {
34780         CheckMode[CheckMode["Normal"] = 0] = "Normal";
34781         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
34782         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
34783         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
34784         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
34785         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
34786     })(CheckMode || (CheckMode = {}));
34787     var AccessFlags;
34788     (function (AccessFlags) {
34789         AccessFlags[AccessFlags["None"] = 0] = "None";
34790         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
34791         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
34792         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
34793         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
34794     })(AccessFlags || (AccessFlags = {}));
34795     var SignatureCheckMode;
34796     (function (SignatureCheckMode) {
34797         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
34798         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
34799         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
34800         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
34801         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
34802     })(SignatureCheckMode || (SignatureCheckMode = {}));
34803     var IntersectionState;
34804     (function (IntersectionState) {
34805         IntersectionState[IntersectionState["None"] = 0] = "None";
34806         IntersectionState[IntersectionState["Source"] = 1] = "Source";
34807         IntersectionState[IntersectionState["Target"] = 2] = "Target";
34808         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
34809         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
34810     })(IntersectionState || (IntersectionState = {}));
34811     var MappedTypeModifiers;
34812     (function (MappedTypeModifiers) {
34813         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
34814         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
34815         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
34816         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
34817     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
34818     var ExpandingFlags;
34819     (function (ExpandingFlags) {
34820         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
34821         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
34822         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
34823         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
34824     })(ExpandingFlags || (ExpandingFlags = {}));
34825     var MembersOrExportsResolutionKind;
34826     (function (MembersOrExportsResolutionKind) {
34827         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
34828         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
34829     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
34830     var UnusedKind;
34831     (function (UnusedKind) {
34832         UnusedKind[UnusedKind["Local"] = 0] = "Local";
34833         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
34834     })(UnusedKind || (UnusedKind = {}));
34835     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
34836     var DeclarationMeaning;
34837     (function (DeclarationMeaning) {
34838         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
34839         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
34840         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
34841         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
34842         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
34843         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
34844     })(DeclarationMeaning || (DeclarationMeaning = {}));
34845     var DeclarationSpaces;
34846     (function (DeclarationSpaces) {
34847         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
34848         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
34849         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
34850         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
34851     })(DeclarationSpaces || (DeclarationSpaces = {}));
34852     function SymbolLinks() {
34853     }
34854     function NodeLinks() {
34855         this.flags = 0;
34856     }
34857     function getNodeId(node) {
34858         if (!node.id) {
34859             node.id = nextNodeId;
34860             nextNodeId++;
34861         }
34862         return node.id;
34863     }
34864     ts.getNodeId = getNodeId;
34865     function getSymbolId(symbol) {
34866         if (!symbol.id) {
34867             symbol.id = nextSymbolId;
34868             nextSymbolId++;
34869         }
34870         return symbol.id;
34871     }
34872     ts.getSymbolId = getSymbolId;
34873     function isInstantiatedModule(node, preserveConstEnums) {
34874         var moduleState = ts.getModuleInstanceState(node);
34875         return moduleState === 1 /* Instantiated */ ||
34876             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
34877     }
34878     ts.isInstantiatedModule = isInstantiatedModule;
34879     function createTypeChecker(host, produceDiagnostics) {
34880         var getPackagesSet = ts.memoize(function () {
34881             var set = ts.createMap();
34882             host.getSourceFiles().forEach(function (sf) {
34883                 if (!sf.resolvedModules)
34884                     return;
34885                 ts.forEachEntry(sf.resolvedModules, function (r) {
34886                     if (r && r.packageId)
34887                         set.set(r.packageId.name, true);
34888                 });
34889             });
34890             return set;
34891         });
34892         // Cancellation that controls whether or not we can cancel in the middle of type checking.
34893         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
34894         // computing something, and we will leave our internals in an inconsistent state.  Callers
34895         // who set the cancellation token should catch if a cancellation exception occurs, and
34896         // should throw away and create a new TypeChecker.
34897         //
34898         // Currently we only support setting the cancellation token when getting diagnostics.  This
34899         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
34900         // they no longer need the information (for example, if the user started editing again).
34901         var cancellationToken;
34902         var requestedExternalEmitHelpers;
34903         var externalHelpersModule;
34904         var Symbol = ts.objectAllocator.getSymbolConstructor();
34905         var Type = ts.objectAllocator.getTypeConstructor();
34906         var Signature = ts.objectAllocator.getSignatureConstructor();
34907         var typeCount = 0;
34908         var symbolCount = 0;
34909         var enumCount = 0;
34910         var totalInstantiationCount = 0;
34911         var instantiationCount = 0;
34912         var instantiationDepth = 0;
34913         var constraintDepth = 0;
34914         var currentNode;
34915         var emptySymbols = ts.createSymbolTable();
34916         var arrayVariances = [1 /* Covariant */];
34917         var compilerOptions = host.getCompilerOptions();
34918         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
34919         var moduleKind = ts.getEmitModuleKind(compilerOptions);
34920         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
34921         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
34922         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
34923         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
34924         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
34925         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
34926         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
34927         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
34928         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
34929         var emitResolver = createResolver();
34930         var nodeBuilder = createNodeBuilder();
34931         var globals = ts.createSymbolTable();
34932         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
34933         undefinedSymbol.declarations = [];
34934         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
34935         globalThisSymbol.exports = globals;
34936         globalThisSymbol.declarations = [];
34937         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
34938         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
34939         var requireSymbol = createSymbol(4 /* Property */, "require");
34940         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
34941         var apparentArgumentCount;
34942         // for public members that accept a Node or one of its subtypes, we must guard against
34943         // synthetic nodes created during transformations by calling `getParseTreeNode`.
34944         // for most of these, we perform the guard only on `checker` to avoid any possible
34945         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
34946         // checker.
34947         var checker = {
34948             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
34949             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
34950             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
34951             getTypeCount: function () { return typeCount; },
34952             getInstantiationCount: function () { return totalInstantiationCount; },
34953             getRelationCacheSizes: function () { return ({
34954                 assignable: assignableRelation.size,
34955                 identity: identityRelation.size,
34956                 subtype: subtypeRelation.size,
34957                 strictSubtype: strictSubtypeRelation.size,
34958             }); },
34959             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
34960             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
34961             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
34962             getMergedSymbol: getMergedSymbol,
34963             getDiagnostics: getDiagnostics,
34964             getGlobalDiagnostics: getGlobalDiagnostics,
34965             getTypeOfSymbolAtLocation: function (symbol, location) {
34966                 location = ts.getParseTreeNode(location);
34967                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
34968             },
34969             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
34970                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
34971                 if (parameter === undefined)
34972                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
34973                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
34974             },
34975             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
34976             getPropertiesOfType: getPropertiesOfType,
34977             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34978             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
34979                 var node = ts.getParseTreeNode(location);
34980                 if (!node) {
34981                     return undefined;
34982                 }
34983                 var propName = ts.escapeLeadingUnderscores(name);
34984                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
34985                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
34986             },
34987             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
34988             getIndexInfoOfType: getIndexInfoOfType,
34989             getSignaturesOfType: getSignaturesOfType,
34990             getIndexTypeOfType: getIndexTypeOfType,
34991             getBaseTypes: getBaseTypes,
34992             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
34993             getWidenedType: getWidenedType,
34994             getTypeFromTypeNode: function (nodeIn) {
34995                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
34996                 return node ? getTypeFromTypeNode(node) : errorType;
34997             },
34998             getParameterType: getTypeAtPosition,
34999             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
35000             getReturnTypeOfSignature: getReturnTypeOfSignature,
35001             isNullableType: isNullableType,
35002             getNullableType: getNullableType,
35003             getNonNullableType: getNonNullableType,
35004             getNonOptionalType: removeOptionalTypeMarker,
35005             getTypeArguments: getTypeArguments,
35006             typeToTypeNode: nodeBuilder.typeToTypeNode,
35007             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
35008             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
35009             symbolToEntityName: nodeBuilder.symbolToEntityName,
35010             symbolToExpression: nodeBuilder.symbolToExpression,
35011             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
35012             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
35013             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
35014             getSymbolsInScope: function (location, meaning) {
35015                 location = ts.getParseTreeNode(location);
35016                 return location ? getSymbolsInScope(location, meaning) : [];
35017             },
35018             getSymbolAtLocation: function (node) {
35019                 node = ts.getParseTreeNode(node);
35020                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
35021                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
35022             },
35023             getShorthandAssignmentValueSymbol: function (node) {
35024                 node = ts.getParseTreeNode(node);
35025                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
35026             },
35027             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
35028                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
35029                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
35030             },
35031             getExportSymbolOfSymbol: function (symbol) {
35032                 return getMergedSymbol(symbol.exportSymbol || symbol);
35033             },
35034             getTypeAtLocation: function (node) {
35035                 node = ts.getParseTreeNode(node);
35036                 return node ? getTypeOfNode(node) : errorType;
35037             },
35038             getTypeOfAssignmentPattern: function (nodeIn) {
35039                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
35040                 return node && getTypeOfAssignmentPattern(node) || errorType;
35041             },
35042             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
35043                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
35044                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
35045             },
35046             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
35047                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
35048             },
35049             typeToString: function (type, enclosingDeclaration, flags) {
35050                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
35051             },
35052             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
35053                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
35054             },
35055             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
35056                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
35057             },
35058             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
35059                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
35060             },
35061             writeType: function (type, enclosingDeclaration, flags, writer) {
35062                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35063             },
35064             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
35065                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
35066             },
35067             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
35068                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
35069             },
35070             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
35071             getRootSymbols: getRootSymbols,
35072             getContextualType: function (nodeIn, contextFlags) {
35073                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
35074                 if (!node) {
35075                     return undefined;
35076                 }
35077                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
35078                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
35079                 if (contextFlags & 4 /* Completions */ && containingCall) {
35080                     var toMarkSkip = node;
35081                     do {
35082                         getNodeLinks(toMarkSkip).skipDirectInference = true;
35083                         toMarkSkip = toMarkSkip.parent;
35084                     } while (toMarkSkip && toMarkSkip !== containingCall);
35085                     getNodeLinks(containingCall).resolvedSignature = undefined;
35086                 }
35087                 var result = getContextualType(node, contextFlags);
35088                 if (contextFlags & 4 /* Completions */ && containingCall) {
35089                     var toMarkSkip = node;
35090                     do {
35091                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
35092                         toMarkSkip = toMarkSkip.parent;
35093                     } while (toMarkSkip && toMarkSkip !== containingCall);
35094                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
35095                 }
35096                 return result;
35097             },
35098             getContextualTypeForObjectLiteralElement: function (nodeIn) {
35099                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
35100                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
35101             },
35102             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
35103                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35104                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
35105             },
35106             getContextualTypeForJsxAttribute: function (nodeIn) {
35107                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
35108                 return node && getContextualTypeForJsxAttribute(node);
35109             },
35110             isContextSensitive: isContextSensitive,
35111             getFullyQualifiedName: getFullyQualifiedName,
35112             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
35113                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
35114             },
35115             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
35116                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
35117             },
35118             getExpandedParameters: getExpandedParameters,
35119             hasEffectiveRestParameter: hasEffectiveRestParameter,
35120             getConstantValue: function (nodeIn) {
35121                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
35122                 return node ? getConstantValue(node) : undefined;
35123             },
35124             isValidPropertyAccess: function (nodeIn, propertyName) {
35125                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
35126                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
35127             },
35128             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
35129                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
35130                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
35131             },
35132             getSignatureFromDeclaration: function (declarationIn) {
35133                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
35134                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
35135             },
35136             isImplementationOfOverload: function (node) {
35137                 var parsed = ts.getParseTreeNode(node, ts.isFunctionLike);
35138                 return parsed ? isImplementationOfOverload(parsed) : undefined;
35139             },
35140             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
35141             getAliasedSymbol: resolveAlias,
35142             getEmitResolver: getEmitResolver,
35143             getExportsOfModule: getExportsOfModuleAsArray,
35144             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
35145             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
35146             getAmbientModules: getAmbientModules,
35147             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
35148             isOptionalParameter: function (nodeIn) {
35149                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
35150                 return node ? isOptionalParameter(node) : false;
35151             },
35152             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
35153             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
35154             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
35155                 // we deliberately exclude augmentations
35156                 // since we are only interested in declarations of the module itself
35157                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
35158             },
35159             getApparentType: getApparentType,
35160             getUnionType: getUnionType,
35161             isTypeAssignableTo: isTypeAssignableTo,
35162             createAnonymousType: createAnonymousType,
35163             createSignature: createSignature,
35164             createSymbol: createSymbol,
35165             createIndexInfo: createIndexInfo,
35166             getAnyType: function () { return anyType; },
35167             getStringType: function () { return stringType; },
35168             getNumberType: function () { return numberType; },
35169             createPromiseType: createPromiseType,
35170             createArrayType: createArrayType,
35171             getElementTypeOfArrayType: getElementTypeOfArrayType,
35172             getBooleanType: function () { return booleanType; },
35173             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
35174             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
35175             getVoidType: function () { return voidType; },
35176             getUndefinedType: function () { return undefinedType; },
35177             getNullType: function () { return nullType; },
35178             getESSymbolType: function () { return esSymbolType; },
35179             getNeverType: function () { return neverType; },
35180             getOptionalType: function () { return optionalType; },
35181             isSymbolAccessible: isSymbolAccessible,
35182             isArrayType: isArrayType,
35183             isTupleType: isTupleType,
35184             isArrayLikeType: isArrayLikeType,
35185             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
35186             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
35187             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
35188             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
35189             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35190             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
35191             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
35192             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
35193             getBaseConstraintOfType: getBaseConstraintOfType,
35194             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
35195             resolveName: function (name, location, meaning, excludeGlobals) {
35196                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
35197             },
35198             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
35199             getAccessibleSymbolChain: getAccessibleSymbolChain,
35200             getTypePredicateOfSignature: getTypePredicateOfSignature,
35201             resolveExternalModuleName: function (moduleSpecifier) {
35202                 return resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
35203             },
35204             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
35205             tryGetThisTypeAt: function (node, includeGlobalThis) {
35206                 node = ts.getParseTreeNode(node);
35207                 return node && tryGetThisTypeAt(node, includeGlobalThis);
35208             },
35209             getTypeArgumentConstraint: function (nodeIn) {
35210                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
35211                 return node && getTypeArgumentConstraint(node);
35212             },
35213             getSuggestionDiagnostics: function (file, ct) {
35214                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
35215                     return ts.emptyArray;
35216                 }
35217                 var diagnostics;
35218                 try {
35219                     // Record the cancellation token so it can be checked later on during checkSourceElement.
35220                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
35221                     // this call is done.
35222                     cancellationToken = ct;
35223                     // Ensure file is type checked
35224                     checkSourceFile(file);
35225                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
35226                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
35227                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
35228                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
35229                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
35230                         }
35231                     });
35232                     return diagnostics || ts.emptyArray;
35233                 }
35234                 finally {
35235                     cancellationToken = undefined;
35236                 }
35237             },
35238             runWithCancellationToken: function (token, callback) {
35239                 try {
35240                     cancellationToken = token;
35241                     return callback(checker);
35242                 }
35243                 finally {
35244                     cancellationToken = undefined;
35245                 }
35246             },
35247             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
35248             isDeclarationVisible: isDeclarationVisible,
35249         };
35250         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
35251             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
35252             apparentArgumentCount = argumentCount;
35253             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
35254             apparentArgumentCount = undefined;
35255             return res;
35256         }
35257         var tupleTypes = ts.createMap();
35258         var unionTypes = ts.createMap();
35259         var intersectionTypes = ts.createMap();
35260         var literalTypes = ts.createMap();
35261         var indexedAccessTypes = ts.createMap();
35262         var substitutionTypes = ts.createMap();
35263         var evolvingArrayTypes = [];
35264         var undefinedProperties = ts.createMap();
35265         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
35266         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
35267         var anyType = createIntrinsicType(1 /* Any */, "any");
35268         var autoType = createIntrinsicType(1 /* Any */, "any");
35269         var wildcardType = createIntrinsicType(1 /* Any */, "any");
35270         var errorType = createIntrinsicType(1 /* Any */, "error");
35271         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
35272         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
35273         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
35274         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
35275         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
35276         var nullType = createIntrinsicType(65536 /* Null */, "null");
35277         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
35278         var stringType = createIntrinsicType(4 /* String */, "string");
35279         var numberType = createIntrinsicType(8 /* Number */, "number");
35280         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
35281         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35282         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
35283         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35284         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
35285         trueType.regularType = regularTrueType;
35286         trueType.freshType = trueType;
35287         regularTrueType.regularType = regularTrueType;
35288         regularTrueType.freshType = trueType;
35289         falseType.regularType = regularFalseType;
35290         falseType.freshType = falseType;
35291         regularFalseType.regularType = regularFalseType;
35292         regularFalseType.freshType = falseType;
35293         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
35294         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
35295         // (The union is cached, so simply doing the marking here is sufficient)
35296         createBooleanType([regularFalseType, trueType]);
35297         createBooleanType([falseType, regularTrueType]);
35298         createBooleanType([falseType, trueType]);
35299         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
35300         var voidType = createIntrinsicType(16384 /* Void */, "void");
35301         var neverType = createIntrinsicType(131072 /* Never */, "never");
35302         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
35303         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
35304         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
35305         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
35306         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
35307         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
35308         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
35309         var numberOrBigIntType = getUnionType([numberType, bigintType]);
35310         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
35311         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
35312         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35313         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35314         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
35315         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
35316         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
35317         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35318         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35319         emptyGenericType.instantiations = ts.createMap();
35320         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35321         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
35322         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
35323         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
35324         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35325         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35326         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
35327         var markerSuperType = createTypeParameter();
35328         var markerSubType = createTypeParameter();
35329         markerSubType.constraint = markerSuperType;
35330         var markerOtherType = createTypeParameter();
35331         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
35332         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35333         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35334         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35335         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
35336         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
35337         var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances
35338         var noIterationTypes = {
35339             get yieldType() { return ts.Debug.fail("Not supported"); },
35340             get returnType() { return ts.Debug.fail("Not supported"); },
35341             get nextType() { return ts.Debug.fail("Not supported"); },
35342         };
35343         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
35344         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
35345         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
35346         var asyncIterationTypesResolver = {
35347             iterableCacheKey: "iterationTypesOfAsyncIterable",
35348             iteratorCacheKey: "iterationTypesOfAsyncIterator",
35349             iteratorSymbolName: "asyncIterator",
35350             getGlobalIteratorType: getGlobalAsyncIteratorType,
35351             getGlobalIterableType: getGlobalAsyncIterableType,
35352             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
35353             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
35354             resolveIterationType: getAwaitedType,
35355             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
35356             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
35357             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,
35358         };
35359         var syncIterationTypesResolver = {
35360             iterableCacheKey: "iterationTypesOfIterable",
35361             iteratorCacheKey: "iterationTypesOfIterator",
35362             iteratorSymbolName: "iterator",
35363             getGlobalIteratorType: getGlobalIteratorType,
35364             getGlobalIterableType: getGlobalIterableType,
35365             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
35366             getGlobalGeneratorType: getGlobalGeneratorType,
35367             resolveIterationType: function (type, _errorNode) { return type; },
35368             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
35369             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
35370             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
35371         };
35372         /** Key is "/path/to/a.ts|/path/to/b.ts". */
35373         var amalgamatedDuplicates;
35374         var reverseMappedCache = ts.createMap();
35375         var ambientModulesCache;
35376         /**
35377          * List of every ambient module with a "*" wildcard.
35378          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
35379          * This is only used if there is no exact match.
35380          */
35381         var patternAmbientModules;
35382         var patternAmbientModuleAugmentations;
35383         var globalObjectType;
35384         var globalFunctionType;
35385         var globalCallableFunctionType;
35386         var globalNewableFunctionType;
35387         var globalArrayType;
35388         var globalReadonlyArrayType;
35389         var globalStringType;
35390         var globalNumberType;
35391         var globalBooleanType;
35392         var globalRegExpType;
35393         var globalThisType;
35394         var anyArrayType;
35395         var autoArrayType;
35396         var anyReadonlyArrayType;
35397         var deferredGlobalNonNullableTypeAlias;
35398         // The library files are only loaded when the feature is used.
35399         // This allows users to just specify library files they want to used through --lib
35400         // and they will not get an error from not having unrelated library files
35401         var deferredGlobalESSymbolConstructorSymbol;
35402         var deferredGlobalESSymbolType;
35403         var deferredGlobalTypedPropertyDescriptorType;
35404         var deferredGlobalPromiseType;
35405         var deferredGlobalPromiseLikeType;
35406         var deferredGlobalPromiseConstructorSymbol;
35407         var deferredGlobalPromiseConstructorLikeType;
35408         var deferredGlobalIterableType;
35409         var deferredGlobalIteratorType;
35410         var deferredGlobalIterableIteratorType;
35411         var deferredGlobalGeneratorType;
35412         var deferredGlobalIteratorYieldResultType;
35413         var deferredGlobalIteratorReturnResultType;
35414         var deferredGlobalAsyncIterableType;
35415         var deferredGlobalAsyncIteratorType;
35416         var deferredGlobalAsyncIterableIteratorType;
35417         var deferredGlobalAsyncGeneratorType;
35418         var deferredGlobalTemplateStringsArrayType;
35419         var deferredGlobalImportMetaType;
35420         var deferredGlobalExtractSymbol;
35421         var deferredGlobalOmitSymbol;
35422         var deferredGlobalBigIntType;
35423         var allPotentiallyUnusedIdentifiers = ts.createMap(); // key is file name
35424         var flowLoopStart = 0;
35425         var flowLoopCount = 0;
35426         var sharedFlowCount = 0;
35427         var flowAnalysisDisabled = false;
35428         var flowInvocationCount = 0;
35429         var lastFlowNode;
35430         var lastFlowNodeReachable;
35431         var flowTypeCache;
35432         var emptyStringType = getLiteralType("");
35433         var zeroType = getLiteralType(0);
35434         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
35435         var resolutionTargets = [];
35436         var resolutionResults = [];
35437         var resolutionPropertyNames = [];
35438         var suggestionCount = 0;
35439         var maximumSuggestionCount = 10;
35440         var mergedSymbols = [];
35441         var symbolLinks = [];
35442         var nodeLinks = [];
35443         var flowLoopCaches = [];
35444         var flowLoopNodes = [];
35445         var flowLoopKeys = [];
35446         var flowLoopTypes = [];
35447         var sharedFlowNodes = [];
35448         var sharedFlowTypes = [];
35449         var flowNodeReachable = [];
35450         var potentialThisCollisions = [];
35451         var potentialNewTargetCollisions = [];
35452         var potentialWeakMapCollisions = [];
35453         var awaitedTypeStack = [];
35454         var diagnostics = ts.createDiagnosticCollection();
35455         var suggestionDiagnostics = ts.createDiagnosticCollection();
35456         var typeofTypesByName = ts.createMapFromTemplate({
35457             string: stringType,
35458             number: numberType,
35459             bigint: bigintType,
35460             boolean: booleanType,
35461             symbol: esSymbolType,
35462             undefined: undefinedType
35463         });
35464         var typeofType = createTypeofType();
35465         var _jsxNamespace;
35466         var _jsxFactoryEntity;
35467         var outofbandVarianceMarkerHandler;
35468         var subtypeRelation = ts.createMap();
35469         var strictSubtypeRelation = ts.createMap();
35470         var assignableRelation = ts.createMap();
35471         var comparableRelation = ts.createMap();
35472         var identityRelation = ts.createMap();
35473         var enumRelation = ts.createMap();
35474         var builtinGlobals = ts.createSymbolTable();
35475         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
35476         initializeTypeChecker();
35477         return checker;
35478         function getJsxNamespace(location) {
35479             if (location) {
35480                 var file = ts.getSourceFileOfNode(location);
35481                 if (file) {
35482                     if (file.localJsxNamespace) {
35483                         return file.localJsxNamespace;
35484                     }
35485                     var jsxPragma = file.pragmas.get("jsx");
35486                     if (jsxPragma) {
35487                         var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
35488                         file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion);
35489                         ts.visitNode(file.localJsxFactory, markAsSynthetic);
35490                         if (file.localJsxFactory) {
35491                             return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
35492                         }
35493                     }
35494                 }
35495             }
35496             if (!_jsxNamespace) {
35497                 _jsxNamespace = "React";
35498                 if (compilerOptions.jsxFactory) {
35499                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
35500                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
35501                     if (_jsxFactoryEntity) {
35502                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
35503                     }
35504                 }
35505                 else if (compilerOptions.reactNamespace) {
35506                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
35507                 }
35508             }
35509             if (!_jsxFactoryEntity) {
35510                 _jsxFactoryEntity = ts.createQualifiedName(ts.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
35511             }
35512             return _jsxNamespace;
35513             function markAsSynthetic(node) {
35514                 node.pos = -1;
35515                 node.end = -1;
35516                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
35517             }
35518         }
35519         function getEmitResolver(sourceFile, cancellationToken) {
35520             // Ensure we have all the type information in place for this file so that all the
35521             // emitter questions of this resolver will return the right information.
35522             getDiagnostics(sourceFile, cancellationToken);
35523             return emitResolver;
35524         }
35525         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
35526             var diagnostic = location
35527                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35528                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35529             var existing = diagnostics.lookup(diagnostic);
35530             if (existing) {
35531                 return existing;
35532             }
35533             else {
35534                 diagnostics.add(diagnostic);
35535                 return diagnostic;
35536             }
35537         }
35538         function error(location, message, arg0, arg1, arg2, arg3) {
35539             var diagnostic = location
35540                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
35541                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
35542             diagnostics.add(diagnostic);
35543             return diagnostic;
35544         }
35545         function addErrorOrSuggestion(isError, diagnostic) {
35546             if (isError) {
35547                 diagnostics.add(diagnostic);
35548             }
35549             else {
35550                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
35551             }
35552         }
35553         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
35554             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
35555         }
35556         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
35557             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
35558             if (maybeMissingAwait) {
35559                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
35560                 ts.addRelatedInfo(diagnostic, related);
35561             }
35562             return diagnostic;
35563         }
35564         function createSymbol(flags, name, checkFlags) {
35565             symbolCount++;
35566             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
35567             symbol.checkFlags = checkFlags || 0;
35568             return symbol;
35569         }
35570         function getExcludedSymbolFlags(flags) {
35571             var result = 0;
35572             if (flags & 2 /* BlockScopedVariable */)
35573                 result |= 111551 /* BlockScopedVariableExcludes */;
35574             if (flags & 1 /* FunctionScopedVariable */)
35575                 result |= 111550 /* FunctionScopedVariableExcludes */;
35576             if (flags & 4 /* Property */)
35577                 result |= 0 /* PropertyExcludes */;
35578             if (flags & 8 /* EnumMember */)
35579                 result |= 900095 /* EnumMemberExcludes */;
35580             if (flags & 16 /* Function */)
35581                 result |= 110991 /* FunctionExcludes */;
35582             if (flags & 32 /* Class */)
35583                 result |= 899503 /* ClassExcludes */;
35584             if (flags & 64 /* Interface */)
35585                 result |= 788872 /* InterfaceExcludes */;
35586             if (flags & 256 /* RegularEnum */)
35587                 result |= 899327 /* RegularEnumExcludes */;
35588             if (flags & 128 /* ConstEnum */)
35589                 result |= 899967 /* ConstEnumExcludes */;
35590             if (flags & 512 /* ValueModule */)
35591                 result |= 110735 /* ValueModuleExcludes */;
35592             if (flags & 8192 /* Method */)
35593                 result |= 103359 /* MethodExcludes */;
35594             if (flags & 32768 /* GetAccessor */)
35595                 result |= 46015 /* GetAccessorExcludes */;
35596             if (flags & 65536 /* SetAccessor */)
35597                 result |= 78783 /* SetAccessorExcludes */;
35598             if (flags & 262144 /* TypeParameter */)
35599                 result |= 526824 /* TypeParameterExcludes */;
35600             if (flags & 524288 /* TypeAlias */)
35601                 result |= 788968 /* TypeAliasExcludes */;
35602             if (flags & 2097152 /* Alias */)
35603                 result |= 2097152 /* AliasExcludes */;
35604             return result;
35605         }
35606         function recordMergedSymbol(target, source) {
35607             if (!source.mergeId) {
35608                 source.mergeId = nextMergeId;
35609                 nextMergeId++;
35610             }
35611             mergedSymbols[source.mergeId] = target;
35612         }
35613         function cloneSymbol(symbol) {
35614             var result = createSymbol(symbol.flags, symbol.escapedName);
35615             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
35616             result.parent = symbol.parent;
35617             if (symbol.valueDeclaration)
35618                 result.valueDeclaration = symbol.valueDeclaration;
35619             if (symbol.constEnumOnlyModule)
35620                 result.constEnumOnlyModule = true;
35621             if (symbol.members)
35622                 result.members = ts.cloneMap(symbol.members);
35623             if (symbol.exports)
35624                 result.exports = ts.cloneMap(symbol.exports);
35625             recordMergedSymbol(result, symbol);
35626             return result;
35627         }
35628         /**
35629          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
35630          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
35631          */
35632         function mergeSymbol(target, source, unidirectional) {
35633             if (unidirectional === void 0) { unidirectional = false; }
35634             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
35635                 (source.flags | target.flags) & 67108864 /* Assignment */) {
35636                 if (source === target) {
35637                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
35638                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
35639                     return target;
35640                 }
35641                 if (!(target.flags & 33554432 /* Transient */)) {
35642                     var resolvedTarget = resolveSymbol(target);
35643                     if (resolvedTarget === unknownSymbol) {
35644                         return source;
35645                     }
35646                     target = cloneSymbol(resolvedTarget);
35647                 }
35648                 // Javascript static-property-assignment declarations always merge, even though they are also values
35649                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
35650                     // reset flag when merging instantiated module into value module that has only const enums
35651                     target.constEnumOnlyModule = false;
35652                 }
35653                 target.flags |= source.flags;
35654                 if (source.valueDeclaration) {
35655                     ts.setValueDeclaration(target, source.valueDeclaration);
35656                 }
35657                 ts.addRange(target.declarations, source.declarations);
35658                 if (source.members) {
35659                     if (!target.members)
35660                         target.members = ts.createSymbolTable();
35661                     mergeSymbolTable(target.members, source.members, unidirectional);
35662                 }
35663                 if (source.exports) {
35664                     if (!target.exports)
35665                         target.exports = ts.createSymbolTable();
35666                     mergeSymbolTable(target.exports, source.exports, unidirectional);
35667                 }
35668                 if (!unidirectional) {
35669                     recordMergedSymbol(target, source);
35670                 }
35671             }
35672             else if (target.flags & 1024 /* NamespaceModule */) {
35673                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
35674                 // as we will already report a "Declaration name conflicts..." error, and this error
35675                 // won't make much sense.
35676                 if (target !== globalThisSymbol) {
35677                     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));
35678                 }
35679             }
35680             else { // error
35681                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
35682                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
35683                 var message = isEitherEnum
35684                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
35685                     : isEitherBlockScoped_1
35686                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
35687                         : ts.Diagnostics.Duplicate_identifier_0;
35688                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
35689                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
35690                 var symbolName_1 = symbolToString(source);
35691                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
35692                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
35693                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
35694                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
35695                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
35696                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: ts.createMap() });
35697                     });
35698                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
35699                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
35700                     });
35701                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
35702                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
35703                 }
35704                 else {
35705                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
35706                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
35707                 }
35708             }
35709             return target;
35710             function addDuplicateLocations(locs, symbol) {
35711                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
35712                     var decl = _a[_i];
35713                     ts.pushIfUnique(locs, decl);
35714                 }
35715             }
35716         }
35717         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
35718             ts.forEach(target.declarations, function (node) {
35719                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
35720             });
35721         }
35722         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
35723             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
35724             var err = lookupOrIssueError(errorNode, message, symbolName);
35725             var _loop_6 = function (relatedNode) {
35726                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
35727                 if (adjustedNode === errorNode)
35728                     return "continue";
35729                 err.relatedInformation = err.relatedInformation || [];
35730                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
35731                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
35732                 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 */; }))
35733                     return "continue";
35734                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
35735             };
35736             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
35737                 var relatedNode = _a[_i];
35738                 _loop_6(relatedNode);
35739             }
35740         }
35741         function combineSymbolTables(first, second) {
35742             if (!ts.hasEntries(first))
35743                 return second;
35744             if (!ts.hasEntries(second))
35745                 return first;
35746             var combined = ts.createSymbolTable();
35747             mergeSymbolTable(combined, first);
35748             mergeSymbolTable(combined, second);
35749             return combined;
35750         }
35751         function mergeSymbolTable(target, source, unidirectional) {
35752             if (unidirectional === void 0) { unidirectional = false; }
35753             source.forEach(function (sourceSymbol, id) {
35754                 var targetSymbol = target.get(id);
35755                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
35756             });
35757         }
35758         function mergeModuleAugmentation(moduleName) {
35759             var _a, _b;
35760             var moduleAugmentation = moduleName.parent;
35761             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
35762                 // this is a combined symbol for multiple augmentations within the same file.
35763                 // its symbol already has accumulated information for all declarations
35764                 // so we need to add it just once - do the work only for first declaration
35765                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
35766                 return;
35767             }
35768             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
35769                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
35770             }
35771             else {
35772                 // find a module that about to be augmented
35773                 // do not validate names of augmentations that are defined in ambient context
35774                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
35775                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
35776                     : undefined;
35777                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
35778                 if (!mainModule_1) {
35779                     return;
35780                 }
35781                 // obtain item referenced by 'export='
35782                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
35783                 if (mainModule_1.flags & 1920 /* Namespace */) {
35784                     // If we're merging an augmentation to a pattern ambient module, we want to
35785                     // perform the merge unidirectionally from the augmentation ('a.foo') to
35786                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
35787                     // all the exports both from the pattern and from the augmentation, but
35788                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
35789                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
35790                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
35791                         if (!patternAmbientModuleAugmentations) {
35792                             patternAmbientModuleAugmentations = ts.createMap();
35793                         }
35794                         // moduleName will be a StringLiteral since this is not `declare global`.
35795                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
35796                     }
35797                     else {
35798                         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)) {
35799                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
35800                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
35801                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
35802                                 var _d = _c[_i], key = _d[0], value = _d[1];
35803                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
35804                                     mergeSymbol(resolvedExports.get(key), value);
35805                                 }
35806                             }
35807                         }
35808                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
35809                     }
35810                 }
35811                 else {
35812                     // moduleName will be a StringLiteral since this is not `declare global`.
35813                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
35814                 }
35815             }
35816         }
35817         function addToSymbolTable(target, source, message) {
35818             source.forEach(function (sourceSymbol, id) {
35819                 var targetSymbol = target.get(id);
35820                 if (targetSymbol) {
35821                     // Error on redeclarations
35822                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
35823                 }
35824                 else {
35825                     target.set(id, sourceSymbol);
35826                 }
35827             });
35828             function addDeclarationDiagnostic(id, message) {
35829                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
35830             }
35831         }
35832         function getSymbolLinks(symbol) {
35833             if (symbol.flags & 33554432 /* Transient */)
35834                 return symbol;
35835             var id = getSymbolId(symbol);
35836             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
35837         }
35838         function getNodeLinks(node) {
35839             var nodeId = getNodeId(node);
35840             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
35841         }
35842         function isGlobalSourceFile(node) {
35843             return node.kind === 290 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
35844         }
35845         function getSymbol(symbols, name, meaning) {
35846             if (meaning) {
35847                 var symbol = getMergedSymbol(symbols.get(name));
35848                 if (symbol) {
35849                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
35850                     if (symbol.flags & meaning) {
35851                         return symbol;
35852                     }
35853                     if (symbol.flags & 2097152 /* Alias */) {
35854                         var target = resolveAlias(symbol);
35855                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
35856                         if (target === unknownSymbol || target.flags & meaning) {
35857                             return symbol;
35858                         }
35859                     }
35860                 }
35861             }
35862             // return undefined if we can't find a symbol.
35863         }
35864         /**
35865          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
35866          * @param parameter a parameterDeclaration node
35867          * @param parameterName a name of the parameter to get the symbols for.
35868          * @return a tuple of two symbols
35869          */
35870         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
35871             var constructorDeclaration = parameter.parent;
35872             var classDeclaration = parameter.parent.parent;
35873             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
35874             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
35875             if (parameterSymbol && propertySymbol) {
35876                 return [parameterSymbol, propertySymbol];
35877             }
35878             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
35879         }
35880         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
35881             var declarationFile = ts.getSourceFileOfNode(declaration);
35882             var useFile = ts.getSourceFileOfNode(usage);
35883             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
35884             if (declarationFile !== useFile) {
35885                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
35886                     (!compilerOptions.outFile && !compilerOptions.out) ||
35887                     isInTypeQuery(usage) ||
35888                     declaration.flags & 8388608 /* Ambient */) {
35889                     // nodes are in different files and order cannot be determined
35890                     return true;
35891                 }
35892                 // declaration is after usage
35893                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
35894                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35895                     return true;
35896                 }
35897                 var sourceFiles = host.getSourceFiles();
35898                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
35899             }
35900             if (declaration.pos <= usage.pos) {
35901                 // declaration is before usage
35902                 if (declaration.kind === 191 /* BindingElement */) {
35903                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
35904                     var errorBindingElement = ts.getAncestor(usage, 191 /* BindingElement */);
35905                     if (errorBindingElement) {
35906                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
35907                             declaration.pos < errorBindingElement.pos;
35908                     }
35909                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
35910                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 242 /* VariableDeclaration */), usage);
35911                 }
35912                 else if (declaration.kind === 242 /* VariableDeclaration */) {
35913                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
35914                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
35915                 }
35916                 else if (ts.isClassDeclaration(declaration)) {
35917                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
35918                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
35919                 }
35920                 else if (ts.isPropertyDeclaration(declaration)) {
35921                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
35922                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
35923                 }
35924                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
35925                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
35926                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35927                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
35928                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
35929                 }
35930                 return true;
35931             }
35932             // declaration is after usage, but it can still be legal if usage is deferred:
35933             // 1. inside an export specifier
35934             // 2. inside a function
35935             // 3. inside an instance property initializer, a reference to a non-instance property
35936             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
35937             // 4. inside a static property initializer, a reference to a static method in the same class
35938             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
35939             // or if usage is in a type context:
35940             // 1. inside a type query (typeof in type position)
35941             // 2. inside a jsdoc comment
35942             if (usage.parent.kind === 263 /* ExportSpecifier */ || (usage.parent.kind === 259 /* ExportAssignment */ && usage.parent.isExportEquals)) {
35943                 // export specifiers do not use the variable, they only make it available for use
35944                 return true;
35945             }
35946             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
35947             if (usage.kind === 259 /* ExportAssignment */ && usage.isExportEquals) {
35948                 return true;
35949             }
35950             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
35951                 return true;
35952             }
35953             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
35954                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
35955                     && ts.getContainingClass(declaration)
35956                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
35957                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
35958                 }
35959                 else {
35960                     return true;
35961                 }
35962             }
35963             return false;
35964             function usageInTypeDeclaration() {
35965                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
35966             }
35967             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
35968                 switch (declaration.parent.parent.kind) {
35969                     case 225 /* VariableStatement */:
35970                     case 230 /* ForStatement */:
35971                     case 232 /* ForOfStatement */:
35972                         // variable statement/for/for-of statement case,
35973                         // use site should not be inside variable declaration (initializer of declaration or binding element)
35974                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
35975                             return true;
35976                         }
35977                         break;
35978                 }
35979                 // ForIn/ForOf case - use site should not be used in expression part
35980                 var grandparent = declaration.parent.parent;
35981                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
35982             }
35983             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
35984                 return !!ts.findAncestor(usage, function (current) {
35985                     if (current === declContainer) {
35986                         return "quit";
35987                     }
35988                     if (ts.isFunctionLike(current)) {
35989                         return true;
35990                     }
35991                     var initializerOfProperty = current.parent &&
35992                         current.parent.kind === 159 /* PropertyDeclaration */ &&
35993                         current.parent.initializer === current;
35994                     if (initializerOfProperty) {
35995                         if (ts.hasModifier(current.parent, 32 /* Static */)) {
35996                             if (declaration.kind === 161 /* MethodDeclaration */) {
35997                                 return true;
35998                             }
35999                         }
36000                         else {
36001                             var isDeclarationInstanceProperty = declaration.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(declaration, 32 /* Static */);
36002                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
36003                                 return true;
36004                             }
36005                         }
36006                     }
36007                     return false;
36008                 });
36009             }
36010             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
36011             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
36012                 // always legal if usage is after declaration
36013                 if (usage.end > declaration.end) {
36014                     return false;
36015                 }
36016                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
36017                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
36018                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
36019                     if (node === declaration) {
36020                         return "quit";
36021                     }
36022                     switch (node.kind) {
36023                         case 202 /* ArrowFunction */:
36024                             return true;
36025                         case 159 /* PropertyDeclaration */:
36026                             // even when stopping at any property declaration, they need to come from the same class
36027                             return stopAtAnyPropertyDeclaration &&
36028                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
36029                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
36030                                 ? "quit" : true;
36031                         case 223 /* Block */:
36032                             switch (node.parent.kind) {
36033                                 case 163 /* GetAccessor */:
36034                                 case 161 /* MethodDeclaration */:
36035                                 case 164 /* SetAccessor */:
36036                                     return true;
36037                                 default:
36038                                     return false;
36039                             }
36040                         default:
36041                             return false;
36042                     }
36043                 });
36044                 return ancestorChangingReferenceScope === undefined;
36045             }
36046         }
36047         function useOuterVariableScopeInParameter(result, location, lastLocation) {
36048             var target = ts.getEmitScriptTarget(compilerOptions);
36049             var functionLocation = location;
36050             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
36051                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
36052                 // - static field in a class expression
36053                 // - optional chaining pre-es2020
36054                 // - nullish coalesce pre-es2020
36055                 // - spread assignment in binding pattern pre-es2017
36056                 if (target >= 2 /* ES2015 */) {
36057                     var links = getNodeLinks(functionLocation);
36058                     if (links.declarationRequiresScopeChange === undefined) {
36059                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
36060                     }
36061                     return !links.declarationRequiresScopeChange;
36062                 }
36063             }
36064             return false;
36065             function requiresScopeChange(node) {
36066                 return requiresScopeChangeWorker(node.name)
36067                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
36068             }
36069             function requiresScopeChangeWorker(node) {
36070                 switch (node.kind) {
36071                     case 202 /* ArrowFunction */:
36072                     case 201 /* FunctionExpression */:
36073                     case 244 /* FunctionDeclaration */:
36074                     case 162 /* Constructor */:
36075                         // do not descend into these
36076                         return false;
36077                     case 161 /* MethodDeclaration */:
36078                     case 163 /* GetAccessor */:
36079                     case 164 /* SetAccessor */:
36080                     case 281 /* PropertyAssignment */:
36081                         return requiresScopeChangeWorker(node.name);
36082                     case 159 /* PropertyDeclaration */:
36083                         // static properties in classes introduce temporary variables
36084                         if (ts.hasStaticModifier(node)) {
36085                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
36086                         }
36087                         return requiresScopeChangeWorker(node.name);
36088                     default:
36089                         // null coalesce and optional chain pre-es2020 produce temporary variables
36090                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
36091                             return target < 7 /* ES2020 */;
36092                         }
36093                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
36094                             return target < 4 /* ES2017 */;
36095                         }
36096                         if (ts.isTypeNode(node))
36097                             return false;
36098                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
36099                 }
36100             }
36101         }
36102         /**
36103          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
36104          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
36105          * the given name can be found.
36106          *
36107          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
36108          */
36109         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
36110             if (excludeGlobals === void 0) { excludeGlobals = false; }
36111             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
36112         }
36113         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
36114             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
36115             var result;
36116             var lastLocation;
36117             var lastSelfReferenceLocation;
36118             var propertyWithInvalidInitializer;
36119             var associatedDeclarationForContainingInitializerOrBindingName;
36120             var withinDeferredContext = false;
36121             var errorLocation = location;
36122             var grandparent;
36123             var isInExternalModule = false;
36124             loop: while (location) {
36125                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
36126                 if (location.locals && !isGlobalSourceFile(location)) {
36127                     if (result = lookup(location.locals, name, meaning)) {
36128                         var useResult = true;
36129                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
36130                             // symbol lookup restrictions for function-like declarations
36131                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
36132                             //   list and return type. However, local types are only in scope in the function body.
36133                             // - parameters are only in the scope of function body
36134                             // This restriction does not apply to JSDoc comment types because they are parented
36135                             // at a higher level than type parameters would normally be
36136                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 303 /* JSDocComment */) {
36137                                 useResult = result.flags & 262144 /* TypeParameter */
36138                                     // type parameters are visible in parameter list, return type and type parameter list
36139                                     ? lastLocation === location.type ||
36140                                         lastLocation.kind === 156 /* Parameter */ ||
36141                                         lastLocation.kind === 155 /* TypeParameter */
36142                                     // local types not visible outside the function body
36143                                     : false;
36144                             }
36145                             if (meaning & result.flags & 3 /* Variable */) {
36146                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
36147                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
36148                                     useResult = false;
36149                                 }
36150                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
36151                                     // parameters are visible only inside function body, parameter list and return type
36152                                     // technically for parameter list case here we might mix parameters and variables declared in function,
36153                                     // however it is detected separately when checking initializers of parameters
36154                                     // to make sure that they reference no variables declared after them.
36155                                     useResult =
36156                                         lastLocation.kind === 156 /* Parameter */ ||
36157                                             (lastLocation === location.type &&
36158                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
36159                                 }
36160                             }
36161                         }
36162                         else if (location.kind === 180 /* ConditionalType */) {
36163                             // A type parameter declared using 'infer T' in a conditional type is visible only in
36164                             // the true branch of the conditional type.
36165                             useResult = lastLocation === location.trueType;
36166                         }
36167                         if (useResult) {
36168                             break loop;
36169                         }
36170                         else {
36171                             result = undefined;
36172                         }
36173                     }
36174                 }
36175                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
36176                 switch (location.kind) {
36177                     case 290 /* SourceFile */:
36178                         if (!ts.isExternalOrCommonJsModule(location))
36179                             break;
36180                         isInExternalModule = true;
36181                     // falls through
36182                     case 249 /* ModuleDeclaration */:
36183                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
36184                         if (location.kind === 290 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
36185                             // It's an external module. First see if the module has an export default and if the local
36186                             // name of that export default matches.
36187                             if (result = moduleExports.get("default" /* Default */)) {
36188                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
36189                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
36190                                     break loop;
36191                                 }
36192                                 result = undefined;
36193                             }
36194                             // Because of module/namespace merging, a module's exports are in scope,
36195                             // yet we never want to treat an export specifier as putting a member in scope.
36196                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
36197                             // Two things to note about this:
36198                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
36199                             //        on an export specifier is that it might find the export specifier itself, and try to
36200                             //        resolve it as an alias. This will cause the checker to consider the export specifier
36201                             //        a circular alias reference when it might not be.
36202                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
36203                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
36204                             //        which is not the desired behavior.
36205                             var moduleExport = moduleExports.get(name);
36206                             if (moduleExport &&
36207                                 moduleExport.flags === 2097152 /* Alias */ &&
36208                                 (ts.getDeclarationOfKind(moduleExport, 263 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 262 /* NamespaceExport */))) {
36209                                 break;
36210                             }
36211                         }
36212                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
36213                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
36214                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
36215                                 result = undefined;
36216                             }
36217                             else {
36218                                 break loop;
36219                             }
36220                         }
36221                         break;
36222                     case 248 /* EnumDeclaration */:
36223                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
36224                             break loop;
36225                         }
36226                         break;
36227                     case 159 /* PropertyDeclaration */:
36228                         // TypeScript 1.0 spec (April 2014): 8.4.1
36229                         // Initializer expressions for instance member variables are evaluated in the scope
36230                         // of the class constructor body but are not permitted to reference parameters or
36231                         // local variables of the constructor. This effectively means that entities from outer scopes
36232                         // by the same name as a constructor parameter or local variable are inaccessible
36233                         // in initializer expressions for instance member variables.
36234                         if (!ts.hasModifier(location, 32 /* Static */)) {
36235                             var ctor = findConstructorDeclaration(location.parent);
36236                             if (ctor && ctor.locals) {
36237                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
36238                                     // Remember the property node, it will be used later to report appropriate error
36239                                     propertyWithInvalidInitializer = location;
36240                                 }
36241                             }
36242                         }
36243                         break;
36244                     case 245 /* ClassDeclaration */:
36245                     case 214 /* ClassExpression */:
36246                     case 246 /* InterfaceDeclaration */:
36247                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
36248                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
36249                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
36250                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
36251                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
36252                                 // ignore type parameters not declared in this container
36253                                 result = undefined;
36254                                 break;
36255                             }
36256                             if (lastLocation && ts.hasModifier(lastLocation, 32 /* Static */)) {
36257                                 // TypeScript 1.0 spec (April 2014): 3.4.1
36258                                 // The scope of a type parameter extends over the entire declaration with which the type
36259                                 // parameter list is associated, with the exception of static member declarations in classes.
36260                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
36261                                 return undefined;
36262                             }
36263                             break loop;
36264                         }
36265                         if (location.kind === 214 /* ClassExpression */ && meaning & 32 /* Class */) {
36266                             var className = location.name;
36267                             if (className && name === className.escapedText) {
36268                                 result = location.symbol;
36269                                 break loop;
36270                             }
36271                         }
36272                         break;
36273                     case 216 /* ExpressionWithTypeArguments */:
36274                         // The type parameters of a class are not in scope in the base class expression.
36275                         if (lastLocation === location.expression && location.parent.token === 90 /* ExtendsKeyword */) {
36276                             var container = location.parent.parent;
36277                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
36278                                 if (nameNotFoundMessage) {
36279                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
36280                                 }
36281                                 return undefined;
36282                             }
36283                         }
36284                         break;
36285                     // It is not legal to reference a class's own type parameters from a computed property name that
36286                     // belongs to the class. For example:
36287                     //
36288                     //   function foo<T>() { return '' }
36289                     //   class C<T> { // <-- Class's own type parameter T
36290                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
36291                     //   }
36292                     //
36293                     case 154 /* ComputedPropertyName */:
36294                         grandparent = location.parent.parent;
36295                         if (ts.isClassLike(grandparent) || grandparent.kind === 246 /* InterfaceDeclaration */) {
36296                             // A reference to this grandparent's type parameters would be an error
36297                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
36298                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
36299                                 return undefined;
36300                             }
36301                         }
36302                         break;
36303                     case 202 /* ArrowFunction */:
36304                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
36305                         // for lower compile targets the resolved symbol is used to emit an error
36306                         if (compilerOptions.target >= 2 /* ES2015 */) {
36307                             break;
36308                         }
36309                     // falls through
36310                     case 161 /* MethodDeclaration */:
36311                     case 162 /* Constructor */:
36312                     case 163 /* GetAccessor */:
36313                     case 164 /* SetAccessor */:
36314                     case 244 /* FunctionDeclaration */:
36315                         if (meaning & 3 /* Variable */ && name === "arguments") {
36316                             result = argumentsSymbol;
36317                             break loop;
36318                         }
36319                         break;
36320                     case 201 /* FunctionExpression */:
36321                         if (meaning & 3 /* Variable */ && name === "arguments") {
36322                             result = argumentsSymbol;
36323                             break loop;
36324                         }
36325                         if (meaning & 16 /* Function */) {
36326                             var functionName = location.name;
36327                             if (functionName && name === functionName.escapedText) {
36328                                 result = location.symbol;
36329                                 break loop;
36330                             }
36331                         }
36332                         break;
36333                     case 157 /* Decorator */:
36334                         // Decorators are resolved at the class declaration. Resolving at the parameter
36335                         // or member would result in looking up locals in the method.
36336                         //
36337                         //   function y() {}
36338                         //   class C {
36339                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
36340                         //   }
36341                         //
36342                         if (location.parent && location.parent.kind === 156 /* Parameter */) {
36343                             location = location.parent;
36344                         }
36345                         //
36346                         //   function y() {}
36347                         //   class C {
36348                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
36349                         //   }
36350                         //
36351                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
36352                         //
36353                         //   type T = number;
36354                         //   declare function y(x: T): any;
36355                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
36356                         //   class C<T> {}
36357                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 245 /* ClassDeclaration */)) {
36358                             location = location.parent;
36359                         }
36360                         break;
36361                     case 322 /* JSDocTypedefTag */:
36362                     case 315 /* JSDocCallbackTag */:
36363                     case 316 /* JSDocEnumTag */:
36364                         // js type aliases do not resolve names from their host, so skip past it
36365                         location = ts.getJSDocHost(location);
36366                         break;
36367                     case 156 /* Parameter */:
36368                         if (lastLocation && (lastLocation === location.initializer ||
36369                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36370                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
36371                                 associatedDeclarationForContainingInitializerOrBindingName = location;
36372                             }
36373                         }
36374                         break;
36375                     case 191 /* BindingElement */:
36376                         if (lastLocation && (lastLocation === location.initializer ||
36377                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
36378                             var root = ts.getRootDeclaration(location);
36379                             if (root.kind === 156 /* Parameter */) {
36380                                 if (!associatedDeclarationForContainingInitializerOrBindingName) {
36381                                     associatedDeclarationForContainingInitializerOrBindingName = location;
36382                                 }
36383                             }
36384                         }
36385                         break;
36386                 }
36387                 if (isSelfReferenceLocation(location)) {
36388                     lastSelfReferenceLocation = location;
36389                 }
36390                 lastLocation = location;
36391                 location = location.parent;
36392             }
36393             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
36394             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
36395             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
36396             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
36397                 result.isReferenced |= meaning;
36398             }
36399             if (!result) {
36400                 if (lastLocation) {
36401                     ts.Debug.assert(lastLocation.kind === 290 /* SourceFile */);
36402                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
36403                         return lastLocation.symbol;
36404                     }
36405                 }
36406                 if (!excludeGlobals) {
36407                     result = lookup(globals, name, meaning);
36408                 }
36409             }
36410             if (!result) {
36411                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
36412                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
36413                         return requireSymbol;
36414                     }
36415                 }
36416             }
36417             if (!result) {
36418                 if (nameNotFoundMessage) {
36419                     if (!errorLocation ||
36420                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
36421                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
36422                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
36423                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
36424                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
36425                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
36426                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
36427                         var suggestion = void 0;
36428                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
36429                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
36430                             if (suggestion) {
36431                                 var suggestionName = symbolToString(suggestion);
36432                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
36433                                 if (suggestion.valueDeclaration) {
36434                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
36435                                 }
36436                             }
36437                         }
36438                         if (!suggestion) {
36439                             error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
36440                         }
36441                         suggestionCount++;
36442                     }
36443                 }
36444                 return undefined;
36445             }
36446             // Perform extra checks only if error reporting was requested
36447             if (nameNotFoundMessage) {
36448                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
36449                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
36450                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
36451                     // with ESNext+useDefineForClassFields because the scope semantics are different.
36452                     var propertyName = propertyWithInvalidInitializer.name;
36453                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
36454                     return undefined;
36455                 }
36456                 // Only check for block-scoped variable if we have an error location and are looking for the
36457                 // name with variable meaning
36458                 //      For example,
36459                 //          declare module foo {
36460                 //              interface bar {}
36461                 //          }
36462                 //      const foo/*1*/: foo/*2*/.bar;
36463                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
36464                 // block-scoped variable and namespace module. However, only when we
36465                 // try to resolve name in /*1*/ which is used in variable position,
36466                 // we want to check for block-scoped
36467                 if (errorLocation &&
36468                     (meaning & 2 /* BlockScopedVariable */ ||
36469                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
36470                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
36471                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
36472                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
36473                     }
36474                 }
36475                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
36476                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
36477                     var merged = getMergedSymbol(result);
36478                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
36479                         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));
36480                     }
36481                 }
36482                 // 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
36483                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
36484                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
36485                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
36486                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
36487                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
36488                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
36489                     }
36490                     // And it cannot refer to any declarations which come after it
36491                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
36492                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
36493                     }
36494                 }
36495                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
36496                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
36497                 }
36498             }
36499             return result;
36500         }
36501         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
36502             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
36503                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
36504                 if (typeOnlyDeclaration) {
36505                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36506                     var message = isExport
36507                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
36508                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
36509                     var relatedMessage = isExport
36510                         ? ts.Diagnostics._0_was_exported_here
36511                         : ts.Diagnostics._0_was_imported_here;
36512                     var unescapedName = ts.unescapeLeadingUnderscores(name);
36513                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
36514                 }
36515             }
36516         }
36517         function getIsDeferredContext(location, lastLocation) {
36518             if (location.kind !== 202 /* ArrowFunction */ && location.kind !== 201 /* FunctionExpression */) {
36519                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
36520                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
36521                     (location.kind === 159 /* PropertyDeclaration */ && !ts.hasModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
36522             }
36523             if (lastLocation && lastLocation === location.name) {
36524                 return false;
36525             }
36526             // generator functions and async functions are not inlined in control flow when immediately invoked
36527             if (location.asteriskToken || ts.hasModifier(location, 256 /* Async */)) {
36528                 return true;
36529             }
36530             return !ts.getImmediatelyInvokedFunctionExpression(location);
36531         }
36532         function isSelfReferenceLocation(node) {
36533             switch (node.kind) {
36534                 case 244 /* FunctionDeclaration */:
36535                 case 245 /* ClassDeclaration */:
36536                 case 246 /* InterfaceDeclaration */:
36537                 case 248 /* EnumDeclaration */:
36538                 case 247 /* TypeAliasDeclaration */:
36539                 case 249 /* ModuleDeclaration */: // For `namespace N { N; }`
36540                     return true;
36541                 default:
36542                     return false;
36543             }
36544         }
36545         function diagnosticName(nameArg) {
36546             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
36547         }
36548         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
36549             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
36550                 var decl = _a[_i];
36551                 if (decl.kind === 155 /* TypeParameter */) {
36552                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
36553                     if (parent === container) {
36554                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
36555                     }
36556                 }
36557             }
36558             return false;
36559         }
36560         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
36561             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
36562                 return false;
36563             }
36564             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
36565             var location = container;
36566             while (location) {
36567                 if (ts.isClassLike(location.parent)) {
36568                     var classSymbol = getSymbolOfNode(location.parent);
36569                     if (!classSymbol) {
36570                         break;
36571                     }
36572                     // Check to see if a static member exists.
36573                     var constructorType = getTypeOfSymbol(classSymbol);
36574                     if (getPropertyOfType(constructorType, name)) {
36575                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
36576                         return true;
36577                     }
36578                     // No static member is present.
36579                     // Check if we're in an instance method and look for a relevant instance member.
36580                     if (location === container && !ts.hasModifier(location, 32 /* Static */)) {
36581                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
36582                         if (getPropertyOfType(instanceType, name)) {
36583                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
36584                             return true;
36585                         }
36586                     }
36587                 }
36588                 location = location.parent;
36589             }
36590             return false;
36591         }
36592         function checkAndReportErrorForExtendingInterface(errorLocation) {
36593             var expression = getEntityNameForExtendingInterface(errorLocation);
36594             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
36595                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
36596                 return true;
36597             }
36598             return false;
36599         }
36600         /**
36601          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
36602          * but returns undefined if that expression is not an EntityNameExpression.
36603          */
36604         function getEntityNameForExtendingInterface(node) {
36605             switch (node.kind) {
36606                 case 75 /* Identifier */:
36607                 case 194 /* PropertyAccessExpression */:
36608                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
36609                 case 216 /* ExpressionWithTypeArguments */:
36610                     if (ts.isEntityNameExpression(node.expression)) {
36611                         return node.expression;
36612                     }
36613                 // falls through
36614                 default:
36615                     return undefined;
36616             }
36617         }
36618         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
36619             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
36620             if (meaning === namespaceMeaning) {
36621                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36622                 var parent = errorLocation.parent;
36623                 if (symbol) {
36624                     if (ts.isQualifiedName(parent)) {
36625                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
36626                         var propName = parent.right.escapedText;
36627                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
36628                         if (propType) {
36629                             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));
36630                             return true;
36631                         }
36632                     }
36633                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
36634                     return true;
36635                 }
36636             }
36637             return false;
36638         }
36639         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
36640             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
36641                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36642                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
36643                     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));
36644                     return true;
36645                 }
36646             }
36647             return false;
36648         }
36649         function isPrimitiveTypeName(name) {
36650             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
36651         }
36652         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
36653             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 263 /* ExportSpecifier */) {
36654                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
36655                 return true;
36656             }
36657             return false;
36658         }
36659         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
36660             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
36661                 if (isPrimitiveTypeName(name)) {
36662                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
36663                     return true;
36664                 }
36665                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36666                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
36667                     var message = isES2015OrLaterConstructorName(name)
36668                         ? 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
36669                         : ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here;
36670                     error(errorLocation, message, ts.unescapeLeadingUnderscores(name));
36671                     return true;
36672                 }
36673             }
36674             return false;
36675         }
36676         function isES2015OrLaterConstructorName(n) {
36677             switch (n) {
36678                 case "Promise":
36679                 case "Symbol":
36680                 case "Map":
36681                 case "WeakMap":
36682                 case "Set":
36683                 case "WeakSet":
36684                     return true;
36685             }
36686             return false;
36687         }
36688         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
36689             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
36690                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36691                 if (symbol) {
36692                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
36693                     return true;
36694                 }
36695             }
36696             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
36697                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
36698                 if (symbol) {
36699                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
36700                     return true;
36701                 }
36702             }
36703             return false;
36704         }
36705         function checkResolvedBlockScopedVariable(result, errorLocation) {
36706             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
36707             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
36708                 // constructor functions aren't block scoped
36709                 return;
36710             }
36711             // Block-scoped variables cannot be used before their definition
36712             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 248 /* EnumDeclaration */); });
36713             if (declaration === undefined)
36714                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
36715             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
36716                 var diagnosticMessage = void 0;
36717                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
36718                 if (result.flags & 2 /* BlockScopedVariable */) {
36719                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
36720                 }
36721                 else if (result.flags & 32 /* Class */) {
36722                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36723                 }
36724                 else if (result.flags & 256 /* RegularEnum */) {
36725                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
36726                 }
36727                 else {
36728                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
36729                     if (compilerOptions.preserveConstEnums) {
36730                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
36731                     }
36732                 }
36733                 if (diagnosticMessage) {
36734                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
36735                 }
36736             }
36737         }
36738         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
36739          * If at any point current node is equal to 'parent' node - return true.
36740          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
36741          */
36742         function isSameScopeDescendentOf(initial, parent, stopAt) {
36743             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
36744         }
36745         function getAnyImportSyntax(node) {
36746             switch (node.kind) {
36747                 case 253 /* ImportEqualsDeclaration */:
36748                     return node;
36749                 case 255 /* ImportClause */:
36750                     return node.parent;
36751                 case 256 /* NamespaceImport */:
36752                     return node.parent.parent;
36753                 case 258 /* ImportSpecifier */:
36754                     return node.parent.parent.parent;
36755                 default:
36756                     return undefined;
36757             }
36758         }
36759         function getDeclarationOfAliasSymbol(symbol) {
36760             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
36761         }
36762         /**
36763          * An alias symbol is created by one of the following declarations:
36764          * import <symbol> = ...
36765          * import <symbol> from ...
36766          * import * as <symbol> from ...
36767          * import { x as <symbol> } from ...
36768          * export { x as <symbol> } from ...
36769          * export * as ns <symbol> from ...
36770          * export = <EntityNameExpression>
36771          * export default <EntityNameExpression>
36772          * module.exports = <EntityNameExpression>
36773          * {<Identifier>}
36774          * {name: <EntityNameExpression>}
36775          */
36776         function isAliasSymbolDeclaration(node) {
36777             return node.kind === 253 /* ImportEqualsDeclaration */ ||
36778                 node.kind === 252 /* NamespaceExportDeclaration */ ||
36779                 node.kind === 255 /* ImportClause */ && !!node.name ||
36780                 node.kind === 256 /* NamespaceImport */ ||
36781                 node.kind === 262 /* NamespaceExport */ ||
36782                 node.kind === 258 /* ImportSpecifier */ ||
36783                 node.kind === 263 /* ExportSpecifier */ ||
36784                 node.kind === 259 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ||
36785                 ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node) ||
36786                 ts.isPropertyAccessExpression(node)
36787                     && ts.isBinaryExpression(node.parent)
36788                     && node.parent.left === node
36789                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
36790                     && isAliasableOrJsExpression(node.parent.right) ||
36791                 node.kind === 282 /* ShorthandPropertyAssignment */ ||
36792                 node.kind === 281 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer);
36793         }
36794         function isAliasableOrJsExpression(e) {
36795             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
36796         }
36797         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
36798             if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
36799                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleImportEqualsDeclarationExpression(node));
36800                 var resolved_4 = resolveExternalModuleSymbol(immediate);
36801                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
36802                 return resolved_4;
36803             }
36804             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
36805             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
36806             return resolved;
36807         }
36808         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
36809             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
36810                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
36811                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
36812                 var message = isExport
36813                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
36814                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
36815                 var relatedMessage = isExport
36816                     ? ts.Diagnostics._0_was_exported_here
36817                     : ts.Diagnostics._0_was_imported_here;
36818                 // Non-null assertion is safe because the optionality comes from ImportClause,
36819                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
36820                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
36821                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
36822             }
36823         }
36824         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
36825             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
36826             if (exportValue) {
36827                 return getPropertyOfType(getTypeOfSymbol(exportValue), name);
36828             }
36829             var exportSymbol = moduleSymbol.exports.get(name);
36830             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36831             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
36832             return resolved;
36833         }
36834         function isSyntacticDefault(node) {
36835             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
36836         }
36837         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
36838             if (!allowSyntheticDefaultImports) {
36839                 return false;
36840             }
36841             // Declaration files (and ambient modules)
36842             if (!file || file.isDeclarationFile) {
36843                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
36844                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
36845                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
36846                     return false;
36847                 }
36848                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
36849                 // So we check a bit more,
36850                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
36851                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
36852                     // it definitely is a module and does not have a synthetic default
36853                     return false;
36854                 }
36855                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
36856                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
36857                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
36858                 return true;
36859             }
36860             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
36861             if (!ts.isSourceFileJS(file)) {
36862                 return hasExportAssignmentSymbol(moduleSymbol);
36863             }
36864             // 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
36865             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
36866         }
36867         function getTargetOfImportClause(node, dontResolveAlias) {
36868             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
36869             if (moduleSymbol) {
36870                 var exportDefaultSymbol = void 0;
36871                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
36872                     exportDefaultSymbol = moduleSymbol;
36873                 }
36874                 else {
36875                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
36876                 }
36877                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
36878                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
36879                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
36880                     if (hasExportAssignmentSymbol(moduleSymbol)) {
36881                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
36882                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
36883                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
36884                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
36885                         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));
36886                     }
36887                     else {
36888                         reportNonDefaultExport(moduleSymbol, node);
36889                     }
36890                 }
36891                 else if (hasSyntheticDefault) {
36892                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
36893                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
36894                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
36895                     return resolved;
36896                 }
36897                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
36898                 return exportDefaultSymbol;
36899             }
36900         }
36901         function reportNonDefaultExport(moduleSymbol, node) {
36902             var _a, _b;
36903             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
36904                 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));
36905             }
36906             else {
36907                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
36908                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
36909                 if (exportStar) {
36910                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
36911                         var _a, _b;
36912                         return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier && ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)));
36913                     });
36914                     if (defaultExport) {
36915                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
36916                     }
36917                 }
36918             }
36919         }
36920         function getTargetOfNamespaceImport(node, dontResolveAlias) {
36921             var moduleSpecifier = node.parent.parent.moduleSpecifier;
36922             var immediate = resolveExternalModuleName(node, moduleSpecifier);
36923             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36924             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36925             return resolved;
36926         }
36927         function getTargetOfNamespaceExport(node, dontResolveAlias) {
36928             var moduleSpecifier = node.parent.moduleSpecifier;
36929             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
36930             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
36931             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
36932             return resolved;
36933         }
36934         // This function creates a synthetic symbol that combines the value side of one symbol with the
36935         // type/namespace side of another symbol. Consider this example:
36936         //
36937         //   declare module graphics {
36938         //       interface Point {
36939         //           x: number;
36940         //           y: number;
36941         //       }
36942         //   }
36943         //   declare var graphics: {
36944         //       Point: new (x: number, y: number) => graphics.Point;
36945         //   }
36946         //   declare module "graphics" {
36947         //       export = graphics;
36948         //   }
36949         //
36950         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
36951         // property with the type/namespace side interface 'Point'.
36952         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
36953             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
36954                 return unknownSymbol;
36955             }
36956             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
36957                 return valueSymbol;
36958             }
36959             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
36960             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
36961             result.parent = valueSymbol.parent || typeSymbol.parent;
36962             if (valueSymbol.valueDeclaration)
36963                 result.valueDeclaration = valueSymbol.valueDeclaration;
36964             if (typeSymbol.members)
36965                 result.members = ts.cloneMap(typeSymbol.members);
36966             if (valueSymbol.exports)
36967                 result.exports = ts.cloneMap(valueSymbol.exports);
36968             return result;
36969         }
36970         function getExportOfModule(symbol, specifier, dontResolveAlias) {
36971             var _a;
36972             if (symbol.flags & 1536 /* Module */) {
36973                 var name = ((_a = specifier.propertyName) !== null && _a !== void 0 ? _a : specifier.name).escapedText;
36974                 var exportSymbol = getExportsOfSymbol(symbol).get(name);
36975                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
36976                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
36977                 return resolved;
36978             }
36979         }
36980         function getPropertyOfVariable(symbol, name) {
36981             if (symbol.flags & 3 /* Variable */) {
36982                 var typeAnnotation = symbol.valueDeclaration.type;
36983                 if (typeAnnotation) {
36984                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
36985                 }
36986             }
36987         }
36988         function getExternalModuleMember(node, specifier, dontResolveAlias) {
36989             var _a;
36990             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
36991             var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); // TODO: GH#18217
36992             var name = specifier.propertyName || specifier.name;
36993             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
36994             var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier, dontResolveAlias, suppressInteropError);
36995             if (targetSymbol) {
36996                 if (name.escapedText) {
36997                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
36998                         return moduleSymbol;
36999                     }
37000                     var symbolFromVariable = void 0;
37001                     // First check if module was specified with "export=". If so, get the member from the resolved type
37002                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
37003                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
37004                     }
37005                     else {
37006                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
37007                     }
37008                     // if symbolFromVariable is export - get its final target
37009                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
37010                     var symbolFromModule = getExportOfModule(targetSymbol, specifier, dontResolveAlias);
37011                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
37012                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
37013                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
37014                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
37015                         }
37016                     }
37017                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
37018                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
37019                         symbolFromModule || symbolFromVariable;
37020                     if (!symbol) {
37021                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
37022                         var declarationName = ts.declarationNameToString(name);
37023                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
37024                         if (suggestion !== undefined) {
37025                             var suggestionName = symbolToString(suggestion);
37026                             var diagnostic = error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
37027                             if (suggestion.valueDeclaration) {
37028                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
37029                             }
37030                         }
37031                         else {
37032                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
37033                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
37034                             }
37035                             else {
37036                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
37037                             }
37038                         }
37039                     }
37040                     return symbol;
37041                 }
37042             }
37043         }
37044         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
37045             var _a;
37046             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
37047             var exports = moduleSymbol.exports;
37048             if (localSymbol) {
37049                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
37050                 if (exportedEqualsSymbol) {
37051                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
37052                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37053                 }
37054                 else {
37055                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
37056                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
37057                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
37058                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
37059                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
37060                     })));
37061                 }
37062             }
37063             else {
37064                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
37065             }
37066         }
37067         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
37068             if (moduleKind >= ts.ModuleKind.ES2015) {
37069                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
37070                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37071                 error(name, message, declarationName);
37072             }
37073             else {
37074                 if (ts.isInJSFile(node)) {
37075                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
37076                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
37077                     error(name, message, declarationName);
37078                 }
37079                 else {
37080                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
37081                         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;
37082                     error(name, message, declarationName, declarationName, moduleName);
37083                 }
37084             }
37085         }
37086         function getTargetOfImportSpecifier(node, dontResolveAlias) {
37087             var resolved = getExternalModuleMember(node.parent.parent.parent, node, dontResolveAlias);
37088             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37089             return resolved;
37090         }
37091         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
37092             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
37093             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37094             return resolved;
37095         }
37096         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
37097             var resolved = node.parent.parent.moduleSpecifier ?
37098                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
37099                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
37100             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37101             return resolved;
37102         }
37103         function getTargetOfExportAssignment(node, dontResolveAlias) {
37104             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
37105             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
37106             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
37107             return resolved;
37108         }
37109         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
37110             if (ts.isClassExpression(expression)) {
37111                 return checkExpressionCached(expression).symbol;
37112             }
37113             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
37114                 return undefined;
37115             }
37116             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
37117             if (aliasLike) {
37118                 return aliasLike;
37119             }
37120             checkExpressionCached(expression);
37121             return getNodeLinks(expression).resolvedSymbol;
37122         }
37123         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
37124             var expression = node.initializer;
37125             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
37126         }
37127         function getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve) {
37128             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
37129                 return undefined;
37130             }
37131             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
37132         }
37133         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
37134             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
37135             switch (node.kind) {
37136                 case 253 /* ImportEqualsDeclaration */:
37137                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
37138                 case 255 /* ImportClause */:
37139                     return getTargetOfImportClause(node, dontRecursivelyResolve);
37140                 case 256 /* NamespaceImport */:
37141                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
37142                 case 262 /* NamespaceExport */:
37143                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
37144                 case 258 /* ImportSpecifier */:
37145                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
37146                 case 263 /* ExportSpecifier */:
37147                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
37148                 case 259 /* ExportAssignment */:
37149                 case 209 /* BinaryExpression */:
37150                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
37151                 case 252 /* NamespaceExportDeclaration */:
37152                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
37153                 case 282 /* ShorthandPropertyAssignment */:
37154                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
37155                 case 281 /* PropertyAssignment */:
37156                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
37157                 case 194 /* PropertyAccessExpression */:
37158                     return getTargetOfPropertyAccessExpression(node, dontRecursivelyResolve);
37159                 default:
37160                     return ts.Debug.fail();
37161             }
37162         }
37163         /**
37164          * Indicates that a symbol is an alias that does not merge with a local declaration.
37165          * OR Is a JSContainer which may merge an alias with a local declaration
37166          */
37167         function isNonLocalAlias(symbol, excludes) {
37168             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
37169             if (!symbol)
37170                 return false;
37171             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
37172         }
37173         function resolveSymbol(symbol, dontResolveAlias) {
37174             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
37175         }
37176         function resolveAlias(symbol) {
37177             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
37178             var links = getSymbolLinks(symbol);
37179             if (!links.target) {
37180                 links.target = resolvingSymbol;
37181                 var node = getDeclarationOfAliasSymbol(symbol);
37182                 if (!node)
37183                     return ts.Debug.fail();
37184                 var target = getTargetOfAliasDeclaration(node);
37185                 if (links.target === resolvingSymbol) {
37186                     links.target = target || unknownSymbol;
37187                 }
37188                 else {
37189                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
37190                 }
37191             }
37192             else if (links.target === resolvingSymbol) {
37193                 links.target = unknownSymbol;
37194             }
37195             return links.target;
37196         }
37197         function tryResolveAlias(symbol) {
37198             var links = getSymbolLinks(symbol);
37199             if (links.target !== resolvingSymbol) {
37200                 return resolveAlias(symbol);
37201             }
37202             return undefined;
37203         }
37204         /**
37205          * Marks a symbol as type-only if its declaration is syntactically type-only.
37206          * If it is not itself marked type-only, but resolves to a type-only alias
37207          * somewhere in its resolution chain, save a reference to the type-only alias declaration
37208          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
37209          *
37210          * This function is called on each alias declaration that could be type-only or resolve to
37211          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
37212          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
37213          * and issue an error if so.
37214          *
37215          * @param aliasDeclaration The alias declaration not marked as type-only
37216          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
37217          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
37218          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
37219          * must still be checked for a type-only marker, overwriting the previous negative result if found.
37220          * @param immediateTarget The symbol to which the alias declaration immediately resolves
37221          * @param finalTarget The symbol to which the alias declaration ultimately resolves
37222          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
37223          */
37224         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
37225             if (!aliasDeclaration)
37226                 return false;
37227             // If the declaration itself is type-only, mark it and return.
37228             // No need to check what it resolves to.
37229             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
37230             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
37231                 var links_1 = getSymbolLinks(sourceSymbol);
37232                 links_1.typeOnlyDeclaration = aliasDeclaration;
37233                 return true;
37234             }
37235             var links = getSymbolLinks(sourceSymbol);
37236             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
37237                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
37238         }
37239         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
37240             var _a, _b, _c;
37241             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
37242                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
37243                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
37244                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
37245             }
37246             return !!aliasDeclarationLinks.typeOnlyDeclaration;
37247         }
37248         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
37249         function getTypeOnlyAliasDeclaration(symbol) {
37250             if (!(symbol.flags & 2097152 /* Alias */)) {
37251                 return undefined;
37252             }
37253             var links = getSymbolLinks(symbol);
37254             return links.typeOnlyDeclaration || undefined;
37255         }
37256         function markExportAsReferenced(node) {
37257             var symbol = getSymbolOfNode(node);
37258             var target = resolveAlias(symbol);
37259             if (target) {
37260                 var markAlias = target === unknownSymbol ||
37261                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
37262                 if (markAlias) {
37263                     markAliasSymbolAsReferenced(symbol);
37264                 }
37265             }
37266         }
37267         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
37268         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
37269         // the alias as an expression (which recursively takes us back here if the target references another alias).
37270         function markAliasSymbolAsReferenced(symbol) {
37271             var links = getSymbolLinks(symbol);
37272             if (!links.referenced) {
37273                 links.referenced = true;
37274                 var node = getDeclarationOfAliasSymbol(symbol);
37275                 if (!node)
37276                     return ts.Debug.fail();
37277                 // We defer checking of the reference of an `import =` until the import itself is referenced,
37278                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
37279                 // position.
37280                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
37281                     var target = resolveSymbol(symbol);
37282                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
37283                         // import foo = <symbol>
37284                         checkExpressionCached(node.moduleReference);
37285                     }
37286                 }
37287             }
37288         }
37289         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
37290         // but their usage in value positions must be tracked to determine if the import can be type-only.
37291         function markConstEnumAliasAsReferenced(symbol) {
37292             var links = getSymbolLinks(symbol);
37293             if (!links.constEnumReferenced) {
37294                 links.constEnumReferenced = true;
37295             }
37296         }
37297         // This function is only for imports with entity names
37298         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
37299             // There are three things we might try to look for. In the following examples,
37300             // the search term is enclosed in |...|:
37301             //
37302             //     import a = |b|; // Namespace
37303             //     import a = |b.c|; // Value, type, namespace
37304             //     import a = |b.c|.d; // Namespace
37305             if (entityName.kind === 75 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
37306                 entityName = entityName.parent;
37307             }
37308             // Check for case 1 and 3 in the above example
37309             if (entityName.kind === 75 /* Identifier */ || entityName.parent.kind === 153 /* QualifiedName */) {
37310                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37311             }
37312             else {
37313                 // Case 2 in above example
37314                 // entityName.kind could be a QualifiedName or a Missing identifier
37315                 ts.Debug.assert(entityName.parent.kind === 253 /* ImportEqualsDeclaration */);
37316                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
37317             }
37318         }
37319         function getFullyQualifiedName(symbol, containingLocation) {
37320             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
37321         }
37322         /**
37323          * Resolves a qualified name and any involved aliases.
37324          */
37325         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
37326             if (ts.nodeIsMissing(name)) {
37327                 return undefined;
37328             }
37329             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
37330             var symbol;
37331             if (name.kind === 75 /* Identifier */) {
37332                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
37333                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
37334                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
37335                 if (!symbol) {
37336                     return getMergedSymbol(symbolFromJSPrototype);
37337                 }
37338             }
37339             else if (name.kind === 153 /* QualifiedName */ || name.kind === 194 /* PropertyAccessExpression */) {
37340                 var left = name.kind === 153 /* QualifiedName */ ? name.left : name.expression;
37341                 var right = name.kind === 153 /* QualifiedName */ ? name.right : name.name;
37342                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
37343                 if (!namespace || ts.nodeIsMissing(right)) {
37344                     return undefined;
37345                 }
37346                 else if (namespace === unknownSymbol) {
37347                     return namespace;
37348                 }
37349                 if (ts.isInJSFile(name)) {
37350                     if (namespace.valueDeclaration &&
37351                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
37352                         namespace.valueDeclaration.initializer &&
37353                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
37354                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
37355                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
37356                         if (moduleSym) {
37357                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
37358                             if (resolvedModuleSymbol) {
37359                                 namespace = resolvedModuleSymbol;
37360                             }
37361                         }
37362                     }
37363                 }
37364                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
37365                 if (!symbol) {
37366                     if (!ignoreErrors) {
37367                         error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(namespace), ts.declarationNameToString(right));
37368                     }
37369                     return undefined;
37370                 }
37371             }
37372             else {
37373                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
37374             }
37375             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
37376             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 259 /* ExportAssignment */)) {
37377                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
37378             }
37379             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
37380         }
37381         /**
37382          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
37383          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
37384          * name resolution won't work either.
37385          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
37386          */
37387         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
37388             if (isJSDocTypeReference(name.parent)) {
37389                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
37390                 if (secondaryLocation) {
37391                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
37392                 }
37393             }
37394         }
37395         function getAssignmentDeclarationLocation(node) {
37396             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
37397             if (typeAlias) {
37398                 return;
37399             }
37400             var host = ts.getJSDocHost(node);
37401             if (ts.isExpressionStatement(host) &&
37402                 ts.isBinaryExpression(host.expression) &&
37403                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
37404                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
37405                 var symbol = getSymbolOfNode(host.expression.left);
37406                 if (symbol) {
37407                     return getDeclarationOfJSPrototypeContainer(symbol);
37408                 }
37409             }
37410             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
37411                 ts.isBinaryExpression(host.parent.parent) &&
37412                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
37413                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
37414                 var symbol = getSymbolOfNode(host.parent.parent.left);
37415                 if (symbol) {
37416                     return getDeclarationOfJSPrototypeContainer(symbol);
37417                 }
37418             }
37419             var sig = ts.getEffectiveJSDocHost(node);
37420             if (sig && ts.isFunctionLike(sig)) {
37421                 var symbol = getSymbolOfNode(sig);
37422                 return symbol && symbol.valueDeclaration;
37423             }
37424         }
37425         function getDeclarationOfJSPrototypeContainer(symbol) {
37426             var decl = symbol.parent.valueDeclaration;
37427             if (!decl) {
37428                 return undefined;
37429             }
37430             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
37431                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
37432                     undefined;
37433             return initializer || decl;
37434         }
37435         /**
37436          * Get the real symbol of a declaration with an expando initializer.
37437          *
37438          * Normally, declarations have an associated symbol, but when a declaration has an expando
37439          * initializer, the expando's symbol is the one that has all the members merged into it.
37440          */
37441         function getExpandoSymbol(symbol) {
37442             var decl = symbol.valueDeclaration;
37443             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
37444                 return undefined;
37445             }
37446             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
37447             if (init) {
37448                 var initSymbol = getSymbolOfNode(init);
37449                 if (initSymbol) {
37450                     return mergeJSSymbols(initSymbol, symbol);
37451                 }
37452             }
37453         }
37454         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
37455             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations);
37456         }
37457         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
37458             if (isForAugmentation === void 0) { isForAugmentation = false; }
37459             return ts.isStringLiteralLike(moduleReferenceExpression)
37460                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
37461                 : undefined;
37462         }
37463         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
37464             if (isForAugmentation === void 0) { isForAugmentation = false; }
37465             if (ts.startsWith(moduleReference, "@types/")) {
37466                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
37467                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
37468                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
37469             }
37470             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
37471             if (ambientModule) {
37472                 return ambientModule;
37473             }
37474             var currentSourceFile = ts.getSourceFileOfNode(location);
37475             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
37476             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
37477             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
37478             if (sourceFile) {
37479                 if (sourceFile.symbol) {
37480                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
37481                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
37482                     }
37483                     // merged symbol is module declaration symbol combined with all augmentations
37484                     return getMergedSymbol(sourceFile.symbol);
37485                 }
37486                 if (moduleNotFoundError) {
37487                     // report errors only if it was requested
37488                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
37489                 }
37490                 return undefined;
37491             }
37492             if (patternAmbientModules) {
37493                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
37494                 if (pattern) {
37495                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
37496                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
37497                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
37498                     // from a.foo.
37499                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
37500                     if (augmentation) {
37501                         return getMergedSymbol(augmentation);
37502                     }
37503                     return getMergedSymbol(pattern.symbol);
37504                 }
37505             }
37506             // May be an untyped module. If so, ignore resolutionDiagnostic.
37507             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) {
37508                 if (isForAugmentation) {
37509                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
37510                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
37511                 }
37512                 else {
37513                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
37514                 }
37515                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
37516                 return undefined;
37517             }
37518             if (moduleNotFoundError) {
37519                 // See if this was possibly a projectReference redirect
37520                 if (resolvedModule) {
37521                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
37522                     if (redirect) {
37523                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
37524                         return undefined;
37525                     }
37526                 }
37527                 if (resolutionDiagnostic) {
37528                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
37529                 }
37530                 else {
37531                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
37532                     if (tsExtension) {
37533                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
37534                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
37535                     }
37536                     else if (!compilerOptions.resolveJsonModule &&
37537                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
37538                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
37539                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
37540                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
37541                     }
37542                     else {
37543                         error(errorNode, moduleNotFoundError, moduleReference);
37544                     }
37545                 }
37546             }
37547             return undefined;
37548         }
37549         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
37550             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
37551             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
37552                 ? typesPackageExists(packageId.name)
37553                     ? ts.chainDiagnosticMessages(
37554                     /*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))
37555                     : ts.chainDiagnosticMessages(
37556                     /*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
37557                 : undefined;
37558             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));
37559         }
37560         function typesPackageExists(packageName) {
37561             return getPackagesSet().has(ts.getTypesPackageName(packageName));
37562         }
37563         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
37564             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
37565                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
37566                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
37567                 return getMergedSymbol(exported) || moduleSymbol;
37568             }
37569             return undefined;
37570         }
37571         function getCommonJsExportEquals(exported, moduleSymbol) {
37572             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
37573                 return exported;
37574             }
37575             var links = getSymbolLinks(exported);
37576             if (links.cjsExportMerged) {
37577                 return links.cjsExportMerged;
37578             }
37579             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
37580             merged.flags = merged.flags | 512 /* ValueModule */;
37581             if (merged.exports === undefined) {
37582                 merged.exports = ts.createSymbolTable();
37583             }
37584             moduleSymbol.exports.forEach(function (s, name) {
37585                 if (name === "export=" /* ExportEquals */)
37586                     return;
37587                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
37588             });
37589             getSymbolLinks(merged).cjsExportMerged = merged;
37590             return links.cjsExportMerged = merged;
37591         }
37592         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
37593         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
37594         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
37595         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
37596             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
37597             if (!dontResolveAlias && symbol) {
37598                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 290 /* SourceFile */)) {
37599                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
37600                         ? "allowSyntheticDefaultImports"
37601                         : "esModuleInterop";
37602                     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);
37603                     return symbol;
37604                 }
37605                 if (compilerOptions.esModuleInterop) {
37606                     var referenceParent = referencingLocation.parent;
37607                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
37608                         ts.isImportCall(referenceParent)) {
37609                         var type = getTypeOfSymbol(symbol);
37610                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
37611                         if (!sigs || !sigs.length) {
37612                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
37613                         }
37614                         if (sigs && sigs.length) {
37615                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
37616                             // Create a new symbol which has the module's type less the call and construct signatures
37617                             var result = createSymbol(symbol.flags, symbol.escapedName);
37618                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
37619                             result.parent = symbol.parent;
37620                             result.target = symbol;
37621                             result.originatingImport = referenceParent;
37622                             if (symbol.valueDeclaration)
37623                                 result.valueDeclaration = symbol.valueDeclaration;
37624                             if (symbol.constEnumOnlyModule)
37625                                 result.constEnumOnlyModule = true;
37626                             if (symbol.members)
37627                                 result.members = ts.cloneMap(symbol.members);
37628                             if (symbol.exports)
37629                                 result.exports = ts.cloneMap(symbol.exports);
37630                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
37631                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
37632                             return result;
37633                         }
37634                     }
37635                 }
37636             }
37637             return symbol;
37638         }
37639         function hasExportAssignmentSymbol(moduleSymbol) {
37640             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
37641         }
37642         function getExportsOfModuleAsArray(moduleSymbol) {
37643             return symbolsToArray(getExportsOfModule(moduleSymbol));
37644         }
37645         function getExportsAndPropertiesOfModule(moduleSymbol) {
37646             var exports = getExportsOfModuleAsArray(moduleSymbol);
37647             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37648             if (exportEquals !== moduleSymbol) {
37649                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
37650             }
37651             return exports;
37652         }
37653         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
37654             var symbolTable = getExportsOfModule(moduleSymbol);
37655             if (symbolTable) {
37656                 return symbolTable.get(memberName);
37657             }
37658         }
37659         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
37660             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
37661             if (symbol) {
37662                 return symbol;
37663             }
37664             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
37665             if (exportEquals === moduleSymbol) {
37666                 return undefined;
37667             }
37668             var type = getTypeOfSymbol(exportEquals);
37669             return type.flags & 131068 /* Primitive */ ||
37670                 ts.getObjectFlags(type) & 1 /* Class */ ||
37671                 isArrayOrTupleLikeType(type)
37672                 ? undefined
37673                 : getPropertyOfType(type, memberName);
37674         }
37675         function getExportsOfSymbol(symbol) {
37676             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
37677                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
37678                     symbol.exports || emptySymbols;
37679         }
37680         function getExportsOfModule(moduleSymbol) {
37681             var links = getSymbolLinks(moduleSymbol);
37682             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
37683         }
37684         /**
37685          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
37686          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
37687          */
37688         function extendExportSymbols(target, source, lookupTable, exportNode) {
37689             if (!source)
37690                 return;
37691             source.forEach(function (sourceSymbol, id) {
37692                 if (id === "default" /* Default */)
37693                     return;
37694                 var targetSymbol = target.get(id);
37695                 if (!targetSymbol) {
37696                     target.set(id, sourceSymbol);
37697                     if (lookupTable && exportNode) {
37698                         lookupTable.set(id, {
37699                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
37700                         });
37701                     }
37702                 }
37703                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
37704                     var collisionTracker = lookupTable.get(id);
37705                     if (!collisionTracker.exportsWithDuplicate) {
37706                         collisionTracker.exportsWithDuplicate = [exportNode];
37707                     }
37708                     else {
37709                         collisionTracker.exportsWithDuplicate.push(exportNode);
37710                     }
37711                 }
37712             });
37713         }
37714         function getExportsOfModuleWorker(moduleSymbol) {
37715             var visitedSymbols = [];
37716             // A module defined by an 'export=' consists of one export that needs to be resolved
37717             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
37718             return visit(moduleSymbol) || emptySymbols;
37719             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
37720             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
37721             function visit(symbol) {
37722                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
37723                     return;
37724                 }
37725                 var symbols = ts.cloneMap(symbol.exports);
37726                 // All export * declarations are collected in an __export symbol by the binder
37727                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
37728                 if (exportStars) {
37729                     var nestedSymbols = ts.createSymbolTable();
37730                     var lookupTable_1 = ts.createMap();
37731                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
37732                         var node = _a[_i];
37733                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
37734                         var exportedSymbols = visit(resolvedModule);
37735                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
37736                     }
37737                     lookupTable_1.forEach(function (_a, id) {
37738                         var exportsWithDuplicate = _a.exportsWithDuplicate;
37739                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
37740                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
37741                             return;
37742                         }
37743                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
37744                             var node = exportsWithDuplicate_1[_i];
37745                             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)));
37746                         }
37747                     });
37748                     extendExportSymbols(symbols, nestedSymbols);
37749                 }
37750                 return symbols;
37751             }
37752         }
37753         function getMergedSymbol(symbol) {
37754             var merged;
37755             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
37756         }
37757         function getSymbolOfNode(node) {
37758             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
37759         }
37760         function getParentOfSymbol(symbol) {
37761             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
37762         }
37763         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
37764             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
37765             var id = "" + getNodeId(containingFile);
37766             var links = getSymbolLinks(symbol);
37767             var results;
37768             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
37769                 return results;
37770             }
37771             if (containingFile && containingFile.imports) {
37772                 // Try to make an import using an import already in the enclosing file, if possible
37773                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
37774                     var importRef = _a[_i];
37775                     if (ts.nodeIsSynthesized(importRef))
37776                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
37777                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
37778                     if (!resolvedModule)
37779                         continue;
37780                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
37781                     if (!ref)
37782                         continue;
37783                     results = ts.append(results, resolvedModule);
37784                 }
37785                 if (ts.length(results)) {
37786                     (links.extendedContainersByFile || (links.extendedContainersByFile = ts.createMap())).set(id, results);
37787                     return results;
37788                 }
37789             }
37790             if (links.extendedContainers) {
37791                 return links.extendedContainers;
37792             }
37793             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
37794             var otherFiles = host.getSourceFiles();
37795             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
37796                 var file = otherFiles_1[_b];
37797                 if (!ts.isExternalModule(file))
37798                     continue;
37799                 var sym = getSymbolOfNode(file);
37800                 var ref = getAliasForSymbolInContainer(sym, symbol);
37801                 if (!ref)
37802                     continue;
37803                 results = ts.append(results, sym);
37804             }
37805             return links.extendedContainers = results || ts.emptyArray;
37806         }
37807         /**
37808          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
37809          * is just its' `.parent`, but for locals, this value is `undefined`
37810          */
37811         function getContainersOfSymbol(symbol, enclosingDeclaration) {
37812             var container = getParentOfSymbol(symbol);
37813             // Type parameters end up in the `members` lists but are not externally visible
37814             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
37815                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
37816                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
37817                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
37818                     return ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers); // This order expresses a preference for the real container if it is in scope
37819                 }
37820                 var res = ts.append(additionalContainers, container);
37821                 return ts.concatenate(res, reexportContainers);
37822             }
37823             var candidates = ts.mapDefined(symbol.declarations, function (d) {
37824                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
37825                     return getSymbolOfNode(d.parent);
37826                 }
37827                 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)) {
37828                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
37829                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
37830                     }
37831                     checkExpressionCached(d.parent.left.expression);
37832                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
37833                 }
37834             });
37835             if (!ts.length(candidates)) {
37836                 return undefined;
37837             }
37838             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
37839             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
37840                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
37841             }
37842         }
37843         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
37844             var fileSymbol = getExternalModuleContainer(d);
37845             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
37846             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
37847         }
37848         function getAliasForSymbolInContainer(container, symbol) {
37849             if (container === getParentOfSymbol(symbol)) {
37850                 // fast path, `symbol` is either already the alias or isn't aliased
37851                 return symbol;
37852             }
37853             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
37854             // the container itself as the alias for the symbol
37855             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
37856             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
37857                 return container;
37858             }
37859             var exports = getExportsOfSymbol(container);
37860             var quick = exports.get(symbol.escapedName);
37861             if (quick && getSymbolIfSameReference(quick, symbol)) {
37862                 return quick;
37863             }
37864             return ts.forEachEntry(exports, function (exported) {
37865                 if (getSymbolIfSameReference(exported, symbol)) {
37866                     return exported;
37867                 }
37868             });
37869         }
37870         /**
37871          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
37872          */
37873         function getSymbolIfSameReference(s1, s2) {
37874             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
37875                 return s1;
37876             }
37877         }
37878         function getExportSymbolOfValueSymbolIfExported(symbol) {
37879             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
37880         }
37881         function symbolIsValue(symbol) {
37882             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
37883         }
37884         function findConstructorDeclaration(node) {
37885             var members = node.members;
37886             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
37887                 var member = members_3[_i];
37888                 if (member.kind === 162 /* Constructor */ && ts.nodeIsPresent(member.body)) {
37889                     return member;
37890                 }
37891             }
37892         }
37893         function createType(flags) {
37894             var result = new Type(checker, flags);
37895             typeCount++;
37896             result.id = typeCount;
37897             return result;
37898         }
37899         function createIntrinsicType(kind, intrinsicName, objectFlags) {
37900             if (objectFlags === void 0) { objectFlags = 0; }
37901             var type = createType(kind);
37902             type.intrinsicName = intrinsicName;
37903             type.objectFlags = objectFlags;
37904             return type;
37905         }
37906         function createBooleanType(trueFalseTypes) {
37907             var type = getUnionType(trueFalseTypes);
37908             type.flags |= 16 /* Boolean */;
37909             type.intrinsicName = "boolean";
37910             return type;
37911         }
37912         function createObjectType(objectFlags, symbol) {
37913             var type = createType(524288 /* Object */);
37914             type.objectFlags = objectFlags;
37915             type.symbol = symbol;
37916             type.members = undefined;
37917             type.properties = undefined;
37918             type.callSignatures = undefined;
37919             type.constructSignatures = undefined;
37920             type.stringIndexInfo = undefined;
37921             type.numberIndexInfo = undefined;
37922             return type;
37923         }
37924         function createTypeofType() {
37925             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
37926         }
37927         function createTypeParameter(symbol) {
37928             var type = createType(262144 /* TypeParameter */);
37929             if (symbol)
37930                 type.symbol = symbol;
37931             return type;
37932         }
37933         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
37934         // @, or #. A third underscore indicates an escaped form of an identifier that started
37935         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
37936         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
37937         function isReservedMemberName(name) {
37938             return name.charCodeAt(0) === 95 /* _ */ &&
37939                 name.charCodeAt(1) === 95 /* _ */ &&
37940                 name.charCodeAt(2) !== 95 /* _ */ &&
37941                 name.charCodeAt(2) !== 64 /* at */ &&
37942                 name.charCodeAt(2) !== 35 /* hash */;
37943         }
37944         function getNamedMembers(members) {
37945             var result;
37946             members.forEach(function (symbol, id) {
37947                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
37948                     (result || (result = [])).push(symbol);
37949                 }
37950             });
37951             return result || ts.emptyArray;
37952         }
37953         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37954             type.members = members;
37955             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
37956             type.callSignatures = callSignatures;
37957             type.constructSignatures = constructSignatures;
37958             type.stringIndexInfo = stringIndexInfo;
37959             type.numberIndexInfo = numberIndexInfo;
37960             return type;
37961         }
37962         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
37963             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
37964         }
37965         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
37966             var result;
37967             var _loop_7 = function (location) {
37968                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
37969                 if (location.locals && !isGlobalSourceFile(location)) {
37970                     if (result = callback(location.locals)) {
37971                         return { value: result };
37972                     }
37973                 }
37974                 switch (location.kind) {
37975                     case 290 /* SourceFile */:
37976                         if (!ts.isExternalOrCommonJsModule(location)) {
37977                             break;
37978                         }
37979                     // falls through
37980                     case 249 /* ModuleDeclaration */:
37981                         var sym = getSymbolOfNode(location);
37982                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
37983                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
37984                         // to one another anyway)
37985                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
37986                             return { value: result };
37987                         }
37988                         break;
37989                     case 245 /* ClassDeclaration */:
37990                     case 214 /* ClassExpression */:
37991                     case 246 /* InterfaceDeclaration */:
37992                         // Type parameters are bound into `members` lists so they can merge across declarations
37993                         // This is troublesome, since in all other respects, they behave like locals :cries:
37994                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
37995                         // lookup logic in terms of `resolveName` would be nice
37996                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
37997                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
37998                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
37999                         var table_1;
38000                         // TODO: Should this filtered table be cached in some way?
38001                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
38002                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
38003                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
38004                             }
38005                         });
38006                         if (table_1 && (result = callback(table_1))) {
38007                             return { value: result };
38008                         }
38009                         break;
38010                 }
38011             };
38012             for (var location = enclosingDeclaration; location; location = location.parent) {
38013                 var state_2 = _loop_7(location);
38014                 if (typeof state_2 === "object")
38015                     return state_2.value;
38016             }
38017             return callback(globals);
38018         }
38019         function getQualifiedLeftMeaning(rightMeaning) {
38020             // If we are looking in value space, the parent meaning is value, other wise it is namespace
38021             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
38022         }
38023         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
38024             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = ts.createMap(); }
38025             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
38026                 return undefined;
38027             }
38028             var id = "" + getSymbolId(symbol);
38029             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
38030             if (!visitedSymbolTables) {
38031                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
38032             }
38033             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
38034             /**
38035              * @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)
38036              */
38037             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
38038                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
38039                     return undefined;
38040                 }
38041                 var result = trySymbolTable(symbols, ignoreQualification);
38042                 visitedSymbolTables.pop();
38043                 return result;
38044             }
38045             function canQualifySymbol(symbolFromSymbolTable, meaning) {
38046                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
38047                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
38048                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
38049                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
38050             }
38051             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
38052                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
38053                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
38054                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
38055                     // check the symbol can be qualified, it is only then this symbol is accessible
38056                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
38057                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
38058             }
38059             function trySymbolTable(symbols, ignoreQualification) {
38060                 // If symbol is directly available by its name in the symbol table
38061                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
38062                     return [symbol];
38063                 }
38064                 // Check if symbol is any of the aliases in scope
38065                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
38066                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
38067                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
38068                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
38069                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
38070                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
38071                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
38072                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
38073                         // See similar comment in `resolveName` for details
38074                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */))) {
38075                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
38076                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
38077                         if (candidate) {
38078                             return candidate;
38079                         }
38080                     }
38081                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
38082                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
38083                             return [symbol];
38084                         }
38085                     }
38086                 });
38087                 // 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
38088                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
38089             }
38090             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
38091                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
38092                     return [symbolFromSymbolTable];
38093                 }
38094                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
38095                 // but only if the symbolFromSymbolTable can be qualified
38096                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
38097                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
38098                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
38099                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
38100                 }
38101             }
38102         }
38103         function needsQualification(symbol, enclosingDeclaration, meaning) {
38104             var qualify = false;
38105             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
38106                 // If symbol of this name is not available in the symbol table we are ok
38107                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
38108                 if (!symbolFromSymbolTable) {
38109                     // Continue to the next symbol table
38110                     return false;
38111                 }
38112                 // If the symbol with this name is present it should refer to the symbol
38113                 if (symbolFromSymbolTable === symbol) {
38114                     // No need to qualify
38115                     return true;
38116                 }
38117                 // Qualify if the symbol from symbol table has same meaning as expected
38118                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 263 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
38119                 if (symbolFromSymbolTable.flags & meaning) {
38120                     qualify = true;
38121                     return true;
38122                 }
38123                 // Continue to the next symbol table
38124                 return false;
38125             });
38126             return qualify;
38127         }
38128         function isPropertyOrMethodDeclarationSymbol(symbol) {
38129             if (symbol.declarations && symbol.declarations.length) {
38130                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
38131                     var declaration = _a[_i];
38132                     switch (declaration.kind) {
38133                         case 159 /* PropertyDeclaration */:
38134                         case 161 /* MethodDeclaration */:
38135                         case 163 /* GetAccessor */:
38136                         case 164 /* SetAccessor */:
38137                             continue;
38138                         default:
38139                             return false;
38140                     }
38141                 }
38142                 return true;
38143             }
38144             return false;
38145         }
38146         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
38147             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false);
38148             return access.accessibility === 0 /* Accessible */;
38149         }
38150         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
38151             var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false);
38152             return access.accessibility === 0 /* Accessible */;
38153         }
38154         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible) {
38155             if (!ts.length(symbols))
38156                 return;
38157             var hadAccessibleChain;
38158             var earlyModuleBail = false;
38159             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
38160                 var symbol = _a[_i];
38161                 // Symbol is accessible if it by itself is accessible
38162                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
38163                 if (accessibleSymbolChain) {
38164                     hadAccessibleChain = symbol;
38165                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
38166                     if (hasAccessibleDeclarations) {
38167                         return hasAccessibleDeclarations;
38168                     }
38169                 }
38170                 else {
38171                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
38172                         if (shouldComputeAliasesToMakeVisible) {
38173                             earlyModuleBail = true;
38174                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
38175                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
38176                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
38177                             // all other visibility options (in order to capture the possible aliases used to reference the module)
38178                             continue;
38179                         }
38180                         // Any meaning of a module symbol is always accessible via an `import` type
38181                         return {
38182                             accessibility: 0 /* Accessible */
38183                         };
38184                     }
38185                 }
38186                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
38187                 // It could be a qualified symbol and hence verify the path
38188                 // e.g.:
38189                 // module m {
38190                 //     export class c {
38191                 //     }
38192                 // }
38193                 // const x: typeof m.c
38194                 // In the above example when we start with checking if typeof m.c symbol is accessible,
38195                 // we are going to see if c can be accessed in scope directly.
38196                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
38197                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
38198                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration);
38199                 // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
38200                 // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
38201                 // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
38202                 var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
38203                 if (!ts.length(containers) && meaning & 111551 /* Value */ && firstDecl && ts.isObjectLiteralExpression(firstDecl)) {
38204                     if (firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) {
38205                         containers = [getSymbolOfNode(firstDecl.parent)];
38206                     }
38207                 }
38208                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible);
38209                 if (parentResult) {
38210                     return parentResult;
38211                 }
38212             }
38213             if (earlyModuleBail) {
38214                 return {
38215                     accessibility: 0 /* Accessible */
38216                 };
38217             }
38218             if (hadAccessibleChain) {
38219                 return {
38220                     accessibility: 1 /* NotAccessible */,
38221                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
38222                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
38223                 };
38224             }
38225         }
38226         /**
38227          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
38228          *
38229          * @param symbol a Symbol to check if accessible
38230          * @param enclosingDeclaration a Node containing reference to the symbol
38231          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
38232          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
38233          */
38234         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
38235             if (symbol && enclosingDeclaration) {
38236                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible);
38237                 if (result) {
38238                     return result;
38239                 }
38240                 // This could be a symbol that is not exported in the external module
38241                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
38242                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
38243                 if (symbolExternalModule) {
38244                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
38245                     if (symbolExternalModule !== enclosingExternalModule) {
38246                         // name from different external module that is not visible
38247                         return {
38248                             accessibility: 2 /* CannotBeNamed */,
38249                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38250                             errorModuleName: symbolToString(symbolExternalModule)
38251                         };
38252                     }
38253                 }
38254                 // Just a local name that is not accessible
38255                 return {
38256                     accessibility: 1 /* NotAccessible */,
38257                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
38258                 };
38259             }
38260             return { accessibility: 0 /* Accessible */ };
38261         }
38262         function getExternalModuleContainer(declaration) {
38263             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
38264             return node && getSymbolOfNode(node);
38265         }
38266         function hasExternalModuleSymbol(declaration) {
38267             return ts.isAmbientModule(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38268         }
38269         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
38270             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
38271         }
38272         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
38273             var aliasesToMakeVisible;
38274             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 75 /* Identifier */; }), getIsDeclarationVisible)) {
38275                 return undefined;
38276             }
38277             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
38278             function getIsDeclarationVisible(declaration) {
38279                 if (!isDeclarationVisible(declaration)) {
38280                     // Mark the unexported alias as visible if its parent is visible
38281                     // because these kind of aliases can be used to name types in declaration file
38282                     var anyImportSyntax = getAnyImportSyntax(declaration);
38283                     if (anyImportSyntax &&
38284                         !ts.hasModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
38285                         isDeclarationVisible(anyImportSyntax.parent)) {
38286                         return addVisibleAlias(declaration, anyImportSyntax);
38287                     }
38288                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
38289                         !ts.hasModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
38290                         isDeclarationVisible(declaration.parent.parent.parent)) {
38291                         return addVisibleAlias(declaration, declaration.parent.parent);
38292                     }
38293                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
38294                         && !ts.hasModifier(declaration, 1 /* Export */)
38295                         && isDeclarationVisible(declaration.parent)) {
38296                         return addVisibleAlias(declaration, declaration);
38297                     }
38298                     // Declaration is not visible
38299                     return false;
38300                 }
38301                 return true;
38302             }
38303             function addVisibleAlias(declaration, aliasingStatement) {
38304                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
38305                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
38306                 // since we will do the emitting later in trackSymbol.
38307                 if (shouldComputeAliasToMakeVisible) {
38308                     getNodeLinks(declaration).isVisible = true;
38309                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
38310                 }
38311                 return true;
38312             }
38313         }
38314         function isEntityNameVisible(entityName, enclosingDeclaration) {
38315             // get symbol of the first identifier of the entityName
38316             var meaning;
38317             if (entityName.parent.kind === 172 /* TypeQuery */ ||
38318                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
38319                 entityName.parent.kind === 154 /* ComputedPropertyName */) {
38320                 // Typeof value
38321                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
38322             }
38323             else if (entityName.kind === 153 /* QualifiedName */ || entityName.kind === 194 /* PropertyAccessExpression */ ||
38324                 entityName.parent.kind === 253 /* ImportEqualsDeclaration */) {
38325                 // Left identifier from type reference or TypeAlias
38326                 // Entity name of the import declaration
38327                 meaning = 1920 /* Namespace */;
38328             }
38329             else {
38330                 // Type Reference or TypeAlias entity = Identifier
38331                 meaning = 788968 /* Type */;
38332             }
38333             var firstIdentifier = ts.getFirstIdentifier(entityName);
38334             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
38335             // Verify if the symbol is accessible
38336             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
38337                 accessibility: 1 /* NotAccessible */,
38338                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
38339                 errorNode: firstIdentifier
38340             };
38341         }
38342         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
38343             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
38344             var nodeFlags = 70221824 /* IgnoreErrors */;
38345             if (flags & 2 /* UseOnlyExternalAliasing */) {
38346                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
38347             }
38348             if (flags & 1 /* WriteTypeParametersOrArguments */) {
38349                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
38350             }
38351             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
38352                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
38353             }
38354             if (flags & 16 /* DoNotIncludeSymbolChain */) {
38355                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
38356             }
38357             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
38358             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
38359             function symbolToStringWorker(writer) {
38360                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
38361                 var printer = ts.createPrinter({ removeComments: true });
38362                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38363                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
38364                 return writer;
38365             }
38366         }
38367         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
38368             if (flags === void 0) { flags = 0 /* None */; }
38369             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
38370             function signatureToStringWorker(writer) {
38371                 var sigOutput;
38372                 if (flags & 262144 /* WriteArrowStyleSignature */) {
38373                     sigOutput = kind === 1 /* Construct */ ? 171 /* ConstructorType */ : 170 /* FunctionType */;
38374                 }
38375                 else {
38376                     sigOutput = kind === 1 /* Construct */ ? 166 /* ConstructSignature */ : 165 /* CallSignature */;
38377                 }
38378                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
38379                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
38380                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38381                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
38382                 return writer;
38383             }
38384         }
38385         function typeToString(type, enclosingDeclaration, flags, writer) {
38386             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
38387             if (writer === void 0) { writer = ts.createTextWriter(""); }
38388             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
38389             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
38390             if (typeNode === undefined)
38391                 return ts.Debug.fail("should always get typenode");
38392             var options = { removeComments: true };
38393             var printer = ts.createPrinter(options);
38394             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
38395             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
38396             var result = writer.getText();
38397             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
38398             if (maxLength && result && result.length >= maxLength) {
38399                 return result.substr(0, maxLength - "...".length) + "...";
38400             }
38401             return result;
38402         }
38403         function getTypeNamesForErrorDisplay(left, right) {
38404             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
38405             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
38406             if (leftStr === rightStr) {
38407                 leftStr = typeToString(left, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38408                 rightStr = typeToString(right, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
38409             }
38410             return [leftStr, rightStr];
38411         }
38412         function symbolValueDeclarationIsContextSensitive(symbol) {
38413             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
38414         }
38415         function toNodeBuilderFlags(flags) {
38416             if (flags === void 0) { flags = 0 /* None */; }
38417             return flags & 814775659 /* NodeBuilderFlagsMask */;
38418         }
38419         function createNodeBuilder() {
38420             return {
38421                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
38422                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
38423                 },
38424                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
38425                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); });
38426                 },
38427                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
38428                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
38429                 },
38430                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38431                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
38432                 },
38433                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
38434                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
38435                 },
38436                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
38437                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
38438                 },
38439                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
38440                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
38441                 },
38442                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
38443                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
38444                 },
38445                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
38446                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
38447                 },
38448             };
38449             function withContext(enclosingDeclaration, flags, tracker, cb) {
38450                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
38451                 var context = {
38452                     enclosingDeclaration: enclosingDeclaration,
38453                     flags: flags || 0 /* None */,
38454                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
38455                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
38456                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
38457                             getSourceFiles: function () { return host.getSourceFiles(); },
38458                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
38459                             getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks),
38460                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
38461                             redirectTargetsMap: host.redirectTargetsMap,
38462                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
38463                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
38464                             fileExists: function (fileName) { return host.fileExists(fileName); },
38465                         } : undefined },
38466                     encounteredError: false,
38467                     visitedTypes: undefined,
38468                     symbolDepth: undefined,
38469                     inferTypeParameters: undefined,
38470                     approximateLength: 0
38471                 };
38472                 var resultingNode = cb(context);
38473                 return context.encounteredError ? undefined : resultingNode;
38474             }
38475             function checkTruncationLength(context) {
38476                 if (context.truncating)
38477                     return context.truncating;
38478                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
38479             }
38480             function typeToTypeNodeHelper(type, context) {
38481                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
38482                     cancellationToken.throwIfCancellationRequested();
38483                 }
38484                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
38485                 context.flags &= ~8388608 /* InTypeAlias */;
38486                 if (!type) {
38487                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38488                         context.encounteredError = true;
38489                         return undefined; // TODO: GH#18217
38490                     }
38491                     context.approximateLength += 3;
38492                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38493                 }
38494                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
38495                     type = getReducedType(type);
38496                 }
38497                 if (type.flags & 1 /* Any */) {
38498                     context.approximateLength += 3;
38499                     return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38500                 }
38501                 if (type.flags & 2 /* Unknown */) {
38502                     return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
38503                 }
38504                 if (type.flags & 4 /* String */) {
38505                     context.approximateLength += 6;
38506                     return ts.createKeywordTypeNode(143 /* StringKeyword */);
38507                 }
38508                 if (type.flags & 8 /* Number */) {
38509                     context.approximateLength += 6;
38510                     return ts.createKeywordTypeNode(140 /* NumberKeyword */);
38511                 }
38512                 if (type.flags & 64 /* BigInt */) {
38513                     context.approximateLength += 6;
38514                     return ts.createKeywordTypeNode(151 /* BigIntKeyword */);
38515                 }
38516                 if (type.flags & 16 /* Boolean */) {
38517                     context.approximateLength += 7;
38518                     return ts.createKeywordTypeNode(128 /* BooleanKeyword */);
38519                 }
38520                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
38521                     var parentSymbol = getParentOfSymbol(type.symbol);
38522                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
38523                     var enumLiteralName = getDeclaredTypeOfSymbol(parentSymbol) === type
38524                         ? parentName
38525                         : appendReferenceToType(parentName, ts.createTypeReferenceNode(ts.symbolName(type.symbol), /*typeArguments*/ undefined));
38526                     return enumLiteralName;
38527                 }
38528                 if (type.flags & 1056 /* EnumLike */) {
38529                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
38530                 }
38531                 if (type.flags & 128 /* StringLiteral */) {
38532                     context.approximateLength += (type.value.length + 2);
38533                     return ts.createLiteralTypeNode(ts.setEmitFlags(ts.createLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
38534                 }
38535                 if (type.flags & 256 /* NumberLiteral */) {
38536                     var value = type.value;
38537                     context.approximateLength += ("" + value).length;
38538                     return ts.createLiteralTypeNode(value < 0 ? ts.createPrefix(40 /* MinusToken */, ts.createLiteral(-value)) : ts.createLiteral(value));
38539                 }
38540                 if (type.flags & 2048 /* BigIntLiteral */) {
38541                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
38542                     return ts.createLiteralTypeNode((ts.createLiteral(type.value)));
38543                 }
38544                 if (type.flags & 512 /* BooleanLiteral */) {
38545                     context.approximateLength += type.intrinsicName.length;
38546                     return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse();
38547                 }
38548                 if (type.flags & 8192 /* UniqueESSymbol */) {
38549                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
38550                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38551                             context.approximateLength += 6;
38552                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
38553                         }
38554                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
38555                             context.tracker.reportInaccessibleUniqueSymbolError();
38556                         }
38557                     }
38558                     context.approximateLength += 13;
38559                     return ts.createTypeOperatorNode(147 /* UniqueKeyword */, ts.createKeywordTypeNode(144 /* SymbolKeyword */));
38560                 }
38561                 if (type.flags & 16384 /* Void */) {
38562                     context.approximateLength += 4;
38563                     return ts.createKeywordTypeNode(110 /* VoidKeyword */);
38564                 }
38565                 if (type.flags & 32768 /* Undefined */) {
38566                     context.approximateLength += 9;
38567                     return ts.createKeywordTypeNode(146 /* UndefinedKeyword */);
38568                 }
38569                 if (type.flags & 65536 /* Null */) {
38570                     context.approximateLength += 4;
38571                     return ts.createKeywordTypeNode(100 /* NullKeyword */);
38572                 }
38573                 if (type.flags & 131072 /* Never */) {
38574                     context.approximateLength += 5;
38575                     return ts.createKeywordTypeNode(137 /* NeverKeyword */);
38576                 }
38577                 if (type.flags & 4096 /* ESSymbol */) {
38578                     context.approximateLength += 6;
38579                     return ts.createKeywordTypeNode(144 /* SymbolKeyword */);
38580                 }
38581                 if (type.flags & 67108864 /* NonPrimitive */) {
38582                     context.approximateLength += 6;
38583                     return ts.createKeywordTypeNode(141 /* ObjectKeyword */);
38584                 }
38585                 if (isThisTypeParameter(type)) {
38586                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
38587                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
38588                             context.encounteredError = true;
38589                         }
38590                         if (context.tracker.reportInaccessibleThisError) {
38591                             context.tracker.reportInaccessibleThisError();
38592                         }
38593                     }
38594                     context.approximateLength += 4;
38595                     return ts.createThis();
38596                 }
38597                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
38598                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
38599                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
38600                         return ts.createTypeReferenceNode(ts.createIdentifier(""), typeArgumentNodes);
38601                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
38602                 }
38603                 var objectFlags = ts.getObjectFlags(type);
38604                 if (objectFlags & 4 /* Reference */) {
38605                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38606                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
38607                 }
38608                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
38609                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
38610                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
38611                         return ts.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
38612                     }
38613                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
38614                         type.flags & 262144 /* TypeParameter */ &&
38615                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38616                         var name = typeParameterToName(type, context);
38617                         context.approximateLength += ts.idText(name).length;
38618                         return ts.createTypeReferenceNode(ts.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
38619                     }
38620                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
38621                     return type.symbol
38622                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
38623                         : ts.createTypeReferenceNode(ts.createIdentifier("?"), /*typeArguments*/ undefined);
38624                 }
38625                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
38626                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
38627                     if (ts.length(types) === 1) {
38628                         return typeToTypeNodeHelper(types[0], context);
38629                     }
38630                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
38631                     if (typeNodes && typeNodes.length > 0) {
38632                         var unionOrIntersectionTypeNode = ts.createUnionOrIntersectionTypeNode(type.flags & 1048576 /* Union */ ? 178 /* UnionType */ : 179 /* IntersectionType */, typeNodes);
38633                         return unionOrIntersectionTypeNode;
38634                     }
38635                     else {
38636                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
38637                             context.encounteredError = true;
38638                         }
38639                         return undefined; // TODO: GH#18217
38640                     }
38641                 }
38642                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
38643                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38644                     // The type is an object literal type.
38645                     return createAnonymousTypeNode(type);
38646                 }
38647                 if (type.flags & 4194304 /* Index */) {
38648                     var indexedType = type.type;
38649                     context.approximateLength += 6;
38650                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
38651                     return ts.createTypeOperatorNode(indexTypeNode);
38652                 }
38653                 if (type.flags & 8388608 /* IndexedAccess */) {
38654                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
38655                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
38656                     context.approximateLength += 2;
38657                     return ts.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
38658                 }
38659                 if (type.flags & 16777216 /* Conditional */) {
38660                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
38661                     var saveInferTypeParameters = context.inferTypeParameters;
38662                     context.inferTypeParameters = type.root.inferTypeParameters;
38663                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
38664                     context.inferTypeParameters = saveInferTypeParameters;
38665                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
38666                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
38667                     context.approximateLength += 15;
38668                     return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
38669                 }
38670                 if (type.flags & 33554432 /* Substitution */) {
38671                     return typeToTypeNodeHelper(type.baseType, context);
38672                 }
38673                 return ts.Debug.fail("Should be unreachable.");
38674                 function typeToTypeNodeOrCircularityElision(type) {
38675                     var _a, _b;
38676                     if (type.flags & 1048576 /* Union */) {
38677                         if (context.visitedTypes && context.visitedTypes.has("" + getTypeId(type))) {
38678                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
38679                                 context.encounteredError = true;
38680                                 (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportCyclicStructureError) === null || _b === void 0 ? void 0 : _b.call(_a);
38681                             }
38682                             return createElidedInformationPlaceholder(context);
38683                         }
38684                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
38685                     }
38686                     return typeToTypeNodeHelper(type, context);
38687                 }
38688                 function createMappedTypeNodeFromType(type) {
38689                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
38690                     var readonlyToken = type.declaration.readonlyToken ? ts.createToken(type.declaration.readonlyToken.kind) : undefined;
38691                     var questionToken = type.declaration.questionToken ? ts.createToken(type.declaration.questionToken.kind) : undefined;
38692                     var appropriateConstraintTypeNode;
38693                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
38694                         // We have a { [P in keyof T]: X }
38695                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
38696                         appropriateConstraintTypeNode = ts.createTypeOperatorNode(typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
38697                     }
38698                     else {
38699                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
38700                     }
38701                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
38702                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
38703                     var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode);
38704                     context.approximateLength += 10;
38705                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
38706                 }
38707                 function createAnonymousTypeNode(type) {
38708                     var typeId = "" + type.id;
38709                     var symbol = type.symbol;
38710                     if (symbol) {
38711                         if (isJSConstructor(symbol.valueDeclaration)) {
38712                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
38713                             var isInstanceType = type === getDeclaredTypeOfClassOrInterface(symbol) ? 788968 /* Type */ : 111551 /* Value */;
38714                             return symbolToTypeNode(symbol, context, isInstanceType);
38715                         }
38716                         // Always use 'typeof T' for type of class, enum, and module objects
38717                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 214 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
38718                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
38719                             shouldWriteTypeOfFunctionSymbol()) {
38720                             return symbolToTypeNode(symbol, context, 111551 /* Value */);
38721                         }
38722                         else if (context.visitedTypes && context.visitedTypes.has(typeId)) {
38723                             // If type is an anonymous type literal in a type alias declaration, use type alias name
38724                             var typeAlias = getTypeAliasForTypeLiteral(type);
38725                             if (typeAlias) {
38726                                 // The specified symbol flags need to be reinterpreted as type flags
38727                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
38728                             }
38729                             else {
38730                                 return createElidedInformationPlaceholder(context);
38731                             }
38732                         }
38733                         else {
38734                             return visitAndTransformType(type, createTypeNodeFromObjectType);
38735                         }
38736                     }
38737                     else {
38738                         // Anonymous types without a symbol are never circular.
38739                         return createTypeNodeFromObjectType(type);
38740                     }
38741                     function shouldWriteTypeOfFunctionSymbol() {
38742                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
38743                             ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); });
38744                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
38745                             (symbol.parent || // is exported function symbol
38746                                 ts.forEach(symbol.declarations, function (declaration) {
38747                                     return declaration.parent.kind === 290 /* SourceFile */ || declaration.parent.kind === 250 /* ModuleBlock */;
38748                                 }));
38749                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
38750                             // typeof is allowed only for static/non local functions
38751                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || (context.visitedTypes && context.visitedTypes.has(typeId))) && // it is type of the symbol uses itself recursively
38752                                 (!(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
38753                         }
38754                     }
38755                 }
38756                 function visitAndTransformType(type, transform) {
38757                     var typeId = "" + type.id;
38758                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
38759                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
38760                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
38761                             undefined;
38762                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
38763                     // of types allows us to catch circular references to instantiations of the same anonymous type
38764                     if (!context.visitedTypes) {
38765                         context.visitedTypes = ts.createMap();
38766                     }
38767                     if (id && !context.symbolDepth) {
38768                         context.symbolDepth = ts.createMap();
38769                     }
38770                     var depth;
38771                     if (id) {
38772                         depth = context.symbolDepth.get(id) || 0;
38773                         if (depth > 10) {
38774                             return createElidedInformationPlaceholder(context);
38775                         }
38776                         context.symbolDepth.set(id, depth + 1);
38777                     }
38778                     context.visitedTypes.set(typeId, true);
38779                     var result = transform(type);
38780                     context.visitedTypes.delete(typeId);
38781                     if (id) {
38782                         context.symbolDepth.set(id, depth);
38783                     }
38784                     return result;
38785                 }
38786                 function createTypeNodeFromObjectType(type) {
38787                     if (isGenericMappedType(type)) {
38788                         return createMappedTypeNodeFromType(type);
38789                     }
38790                     var resolved = resolveStructuredTypeMembers(type);
38791                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
38792                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
38793                             context.approximateLength += 2;
38794                             return ts.setEmitFlags(ts.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
38795                         }
38796                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
38797                             var signature = resolved.callSignatures[0];
38798                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 170 /* FunctionType */, context);
38799                             return signatureNode;
38800                         }
38801                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
38802                             var signature = resolved.constructSignatures[0];
38803                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 171 /* ConstructorType */, context);
38804                             return signatureNode;
38805                         }
38806                     }
38807                     var savedFlags = context.flags;
38808                     context.flags |= 4194304 /* InObjectTypeLiteral */;
38809                     var members = createTypeNodesFromResolvedType(resolved);
38810                     context.flags = savedFlags;
38811                     var typeLiteralNode = ts.createTypeLiteralNode(members);
38812                     context.approximateLength += 2;
38813                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
38814                 }
38815                 function typeReferenceToTypeNode(type) {
38816                     var typeArguments = getTypeArguments(type);
38817                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
38818                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
38819                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
38820                             return ts.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
38821                         }
38822                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
38823                         var arrayType = ts.createArrayTypeNode(elementType);
38824                         return type.target === globalArrayType ? arrayType : ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, arrayType);
38825                     }
38826                     else if (type.target.objectFlags & 8 /* Tuple */) {
38827                         if (typeArguments.length > 0) {
38828                             var arity = getTypeReferenceArity(type);
38829                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
38830                             var hasRestElement = type.target.hasRestElement;
38831                             if (tupleConstituentNodes) {
38832                                 for (var i = type.target.minLength; i < Math.min(arity, tupleConstituentNodes.length); i++) {
38833                                     tupleConstituentNodes[i] = hasRestElement && i === arity - 1 ?
38834                                         ts.createRestTypeNode(ts.createArrayTypeNode(tupleConstituentNodes[i])) :
38835                                         ts.createOptionalTypeNode(tupleConstituentNodes[i]);
38836                                 }
38837                                 var tupleTypeNode = ts.createTupleTypeNode(tupleConstituentNodes);
38838                                 return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38839                             }
38840                         }
38841                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
38842                             var tupleTypeNode = ts.createTupleTypeNode([]);
38843                             return type.target.readonly ? ts.createTypeOperatorNode(138 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
38844                         }
38845                         context.encounteredError = true;
38846                         return undefined; // TODO: GH#18217
38847                     }
38848                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
38849                         type.symbol.valueDeclaration &&
38850                         ts.isClassLike(type.symbol.valueDeclaration) &&
38851                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
38852                         return createAnonymousTypeNode(type);
38853                     }
38854                     else {
38855                         var outerTypeParameters = type.target.outerTypeParameters;
38856                         var i = 0;
38857                         var resultType = void 0;
38858                         if (outerTypeParameters) {
38859                             var length_2 = outerTypeParameters.length;
38860                             while (i < length_2) {
38861                                 // Find group of type arguments for type parameters with the same declaring container.
38862                                 var start = i;
38863                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
38864                                 do {
38865                                     i++;
38866                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
38867                                 // When type parameters are their own type arguments for the whole group (i.e. we have
38868                                 // the default outer type arguments), we don't show the group.
38869                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
38870                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
38871                                     var flags_2 = context.flags;
38872                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38873                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
38874                                     context.flags = flags_2;
38875                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
38876                                 }
38877                             }
38878                         }
38879                         var typeArgumentNodes = void 0;
38880                         if (typeArguments.length > 0) {
38881                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
38882                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
38883                         }
38884                         var flags = context.flags;
38885                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
38886                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
38887                         context.flags = flags;
38888                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
38889                     }
38890                 }
38891                 function appendReferenceToType(root, ref) {
38892                     if (ts.isImportTypeNode(root)) {
38893                         // first shift type arguments
38894                         var innerParams = root.typeArguments;
38895                         if (root.qualifier) {
38896                             (ts.isIdentifier(root.qualifier) ? root.qualifier : root.qualifier.right).typeArguments = innerParams;
38897                         }
38898                         root.typeArguments = ref.typeArguments;
38899                         // then move qualifiers
38900                         var ids = getAccessStack(ref);
38901                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
38902                             var id = ids_1[_i];
38903                             root.qualifier = root.qualifier ? ts.createQualifiedName(root.qualifier, id) : id;
38904                         }
38905                         return root;
38906                     }
38907                     else {
38908                         // first shift type arguments
38909                         var innerParams = root.typeArguments;
38910                         (ts.isIdentifier(root.typeName) ? root.typeName : root.typeName.right).typeArguments = innerParams;
38911                         root.typeArguments = ref.typeArguments;
38912                         // then move qualifiers
38913                         var ids = getAccessStack(ref);
38914                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
38915                             var id = ids_2[_a];
38916                             root.typeName = ts.createQualifiedName(root.typeName, id);
38917                         }
38918                         return root;
38919                     }
38920                 }
38921                 function getAccessStack(ref) {
38922                     var state = ref.typeName;
38923                     var ids = [];
38924                     while (!ts.isIdentifier(state)) {
38925                         ids.unshift(state.right);
38926                         state = state.left;
38927                     }
38928                     ids.unshift(state);
38929                     return ids;
38930                 }
38931                 function createTypeNodesFromResolvedType(resolvedType) {
38932                     if (checkTruncationLength(context)) {
38933                         return [ts.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)];
38934                     }
38935                     var typeElements = [];
38936                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
38937                         var signature = _a[_i];
38938                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 165 /* CallSignature */, context));
38939                     }
38940                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
38941                         var signature = _c[_b];
38942                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 166 /* ConstructSignature */, context));
38943                     }
38944                     if (resolvedType.stringIndexInfo) {
38945                         var indexSignature = void 0;
38946                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
38947                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context);
38948                             indexSignature.type = createElidedInformationPlaceholder(context);
38949                         }
38950                         else {
38951                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context);
38952                         }
38953                         typeElements.push(indexSignature);
38954                     }
38955                     if (resolvedType.numberIndexInfo) {
38956                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context));
38957                     }
38958                     var properties = resolvedType.properties;
38959                     if (!properties) {
38960                         return typeElements;
38961                     }
38962                     var i = 0;
38963                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
38964                         var propertySymbol = properties_1[_d];
38965                         i++;
38966                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
38967                             if (propertySymbol.flags & 4194304 /* Prototype */) {
38968                                 continue;
38969                             }
38970                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
38971                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
38972                             }
38973                         }
38974                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
38975                             typeElements.push(ts.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
38976                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
38977                             break;
38978                         }
38979                         addPropertyToElementList(propertySymbol, context, typeElements);
38980                     }
38981                     return typeElements.length ? typeElements : undefined;
38982                 }
38983             }
38984             function createElidedInformationPlaceholder(context) {
38985                 context.approximateLength += 3;
38986                 if (!(context.flags & 1 /* NoTruncation */)) {
38987                     return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined);
38988                 }
38989                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
38990             }
38991             function addPropertyToElementList(propertySymbol, context, typeElements) {
38992                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
38993                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
38994                     anyType : getTypeOfSymbol(propertySymbol);
38995                 var saveEnclosingDeclaration = context.enclosingDeclaration;
38996                 context.enclosingDeclaration = undefined;
38997                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
38998                     var decl = ts.first(propertySymbol.declarations);
38999                     if (hasLateBindableName(decl)) {
39000                         if (ts.isBinaryExpression(decl)) {
39001                             var name = ts.getNameOfDeclaration(decl);
39002                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
39003                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
39004                             }
39005                         }
39006                         else {
39007                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
39008                         }
39009                     }
39010                 }
39011                 context.enclosingDeclaration = saveEnclosingDeclaration;
39012                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
39013                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
39014                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined;
39015                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
39016                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
39017                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
39018                         var signature = signatures_1[_i];
39019                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 160 /* MethodSignature */, context);
39020                         methodDeclaration.name = propertyName;
39021                         methodDeclaration.questionToken = optionalToken;
39022                         typeElements.push(preserveCommentsOn(methodDeclaration));
39023                     }
39024                 }
39025                 else {
39026                     var savedFlags = context.flags;
39027                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
39028                     var propertyTypeNode = void 0;
39029                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
39030                         propertyTypeNode = createElidedInformationPlaceholder(context);
39031                     }
39032                     else {
39033                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
39034                     }
39035                     context.flags = savedFlags;
39036                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined;
39037                     if (modifiers) {
39038                         context.approximateLength += 9;
39039                     }
39040                     var propertySignature = ts.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode, 
39041                     /*initializer*/ undefined);
39042                     typeElements.push(preserveCommentsOn(propertySignature));
39043                 }
39044                 function preserveCommentsOn(node) {
39045                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; })) {
39046                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 323 /* JSDocPropertyTag */; });
39047                         var commentText = d.comment;
39048                         if (commentText) {
39049                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
39050                         }
39051                     }
39052                     else if (propertySymbol.valueDeclaration) {
39053                         // Copy comments to node for declaration emit
39054                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
39055                     }
39056                     return node;
39057                 }
39058             }
39059             function mapToTypeNodes(types, context, isBareList) {
39060                 if (ts.some(types)) {
39061                     if (checkTruncationLength(context)) {
39062                         if (!isBareList) {
39063                             return [ts.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
39064                         }
39065                         else if (types.length > 2) {
39066                             return [
39067                                 typeToTypeNodeHelper(types[0], context),
39068                                 ts.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
39069                                 typeToTypeNodeHelper(types[types.length - 1], context)
39070                             ];
39071                         }
39072                     }
39073                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
39074                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
39075                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
39076                     var result_3 = [];
39077                     var i = 0;
39078                     for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {
39079                         var type = types_1[_i];
39080                         i++;
39081                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
39082                             result_3.push(ts.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
39083                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
39084                             if (typeNode_1) {
39085                                 result_3.push(typeNode_1);
39086                             }
39087                             break;
39088                         }
39089                         context.approximateLength += 2; // Account for whitespace + separator
39090                         var typeNode = typeToTypeNodeHelper(type, context);
39091                         if (typeNode) {
39092                             result_3.push(typeNode);
39093                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
39094                                 seenNames.add(typeNode.typeName.escapedText, [type, result_3.length - 1]);
39095                             }
39096                         }
39097                     }
39098                     if (seenNames) {
39099                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
39100                         // occurrences of the same name actually come from different
39101                         // namespaces, go through the single-identifier type reference nodes
39102                         // we just generated, and see if any names were generated more than
39103                         // once while referring to different types. If so, regenerate the
39104                         // type node for each entry by that name with the
39105                         // `UseFullyQualifiedType` flag enabled.
39106                         var saveContextFlags = context.flags;
39107                         context.flags |= 64 /* UseFullyQualifiedType */;
39108                         seenNames.forEach(function (types) {
39109                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
39110                                 var a = _a[0];
39111                                 var b = _b[0];
39112                                 return typesAreSameReference(a, b);
39113                             })) {
39114                                 for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
39115                                     var _a = types_2[_i], type = _a[0], resultIndex = _a[1];
39116                                     result_3[resultIndex] = typeToTypeNodeHelper(type, context);
39117                                 }
39118                             }
39119                         });
39120                         context.flags = saveContextFlags;
39121                     }
39122                     return result_3;
39123                 }
39124             }
39125             function typesAreSameReference(a, b) {
39126                 return a === b
39127                     || !!a.symbol && a.symbol === b.symbol
39128                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
39129             }
39130             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context) {
39131                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
39132                 var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 /* String */ ? 143 /* StringKeyword */ : 140 /* NumberKeyword */);
39133                 var indexingParameter = ts.createParameter(
39134                 /*decorators*/ undefined, 
39135                 /*modifiers*/ undefined, 
39136                 /*dotDotDotToken*/ undefined, name, 
39137                 /*questionToken*/ undefined, indexerTypeNode, 
39138                 /*initializer*/ undefined);
39139                 var typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
39140                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
39141                     context.encounteredError = true;
39142                 }
39143                 context.approximateLength += (name.length + 4);
39144                 return ts.createIndexSignature(
39145                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(138 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
39146             }
39147             function signatureToSignatureDeclarationHelper(signature, kind, context, privateSymbolVisitor, bundledImports) {
39148                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
39149                 if (suppressAny)
39150                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
39151                 var typeParameters;
39152                 var typeArguments;
39153                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
39154                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
39155                 }
39156                 else {
39157                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
39158                 }
39159                 var parameters = getExpandedParameters(signature).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 162 /* Constructor */, privateSymbolVisitor, bundledImports); });
39160                 if (signature.thisParameter) {
39161                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
39162                     parameters.unshift(thisParameter);
39163                 }
39164                 var returnTypeNode;
39165                 var typePredicate = getTypePredicateOfSignature(signature);
39166                 if (typePredicate) {
39167                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39168                         ts.createToken(124 /* AssertsKeyword */) :
39169                         undefined;
39170                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
39171                         ts.setEmitFlags(ts.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
39172                         ts.createThisTypeNode();
39173                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
39174                     returnTypeNode = ts.createTypePredicateNodeWithModifier(assertsModifier, parameterName, typeNode);
39175                 }
39176                 else {
39177                     var returnType = getReturnTypeOfSignature(signature);
39178                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
39179                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, privateSymbolVisitor, bundledImports);
39180                     }
39181                     else if (!suppressAny) {
39182                         returnTypeNode = ts.createKeywordTypeNode(125 /* AnyKeyword */);
39183                     }
39184                 }
39185                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
39186                 return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments);
39187             }
39188             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
39189                 var savedContextFlags = context.flags;
39190                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
39191                 var name = typeParameterToName(type, context);
39192                 var defaultParameter = getDefaultFromTypeParameter(type);
39193                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
39194                 context.flags = savedContextFlags;
39195                 return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
39196             }
39197             function typeParameterToDeclaration(type, context, constraint) {
39198                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
39199                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
39200                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
39201             }
39202             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
39203                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 156 /* Parameter */);
39204                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
39205                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 317 /* JSDocParameterTag */);
39206                 }
39207                 var parameterType = getTypeOfSymbol(parameterSymbol);
39208                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
39209                     parameterType = getOptionalType(parameterType);
39210                 }
39211                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
39212                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined;
39213                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
39214                 var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined;
39215                 var name = parameterDeclaration ? parameterDeclaration.name ?
39216                     parameterDeclaration.name.kind === 75 /* Identifier */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
39217                         parameterDeclaration.name.kind === 153 /* QualifiedName */ ? ts.setEmitFlags(ts.getSynthesizedClone(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
39218                             cloneBindingName(parameterDeclaration.name) :
39219                     ts.symbolName(parameterSymbol) :
39220                     ts.symbolName(parameterSymbol);
39221                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
39222                 var questionToken = isOptional ? ts.createToken(57 /* QuestionToken */) : undefined;
39223                 var parameterNode = ts.createParameter(
39224                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
39225                 /*initializer*/ undefined);
39226                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
39227                 return parameterNode;
39228                 function cloneBindingName(node) {
39229                     return elideInitializerAndSetEmitFlags(node);
39230                     function elideInitializerAndSetEmitFlags(node) {
39231                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
39232                             trackComputedName(node.expression, context.enclosingDeclaration, context);
39233                         }
39234                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
39235                         var clone = ts.nodeIsSynthesized(visited) ? visited : ts.getSynthesizedClone(visited);
39236                         if (clone.kind === 191 /* BindingElement */) {
39237                             clone.initializer = undefined;
39238                         }
39239                         return ts.setEmitFlags(clone, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
39240                     }
39241                 }
39242             }
39243             function trackComputedName(accessExpression, enclosingDeclaration, context) {
39244                 if (!context.tracker.trackSymbol)
39245                     return;
39246                 // get symbol of the first identifier of the entityName
39247                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
39248                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
39249                 if (name) {
39250                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
39251                 }
39252             }
39253             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
39254                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
39255                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
39256             }
39257             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
39258                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
39259                 var chain;
39260                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
39261                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
39262                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
39263                     ts.Debug.assert(chain && chain.length > 0);
39264                 }
39265                 else {
39266                     chain = [symbol];
39267                 }
39268                 return chain;
39269                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
39270                 function getSymbolChain(symbol, meaning, endOfChain) {
39271                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
39272                     var parentSpecifiers;
39273                     if (!accessibleSymbolChain ||
39274                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
39275                         // Go up and add our parent.
39276                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration);
39277                         if (ts.length(parents_1)) {
39278                             parentSpecifiers = parents_1.map(function (symbol) {
39279                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
39280                                     ? getSpecifierForModuleSymbol(symbol, context)
39281                                     : undefined;
39282                             });
39283                             var indices = parents_1.map(function (_, i) { return i; });
39284                             indices.sort(sortByBestName);
39285                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
39286                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
39287                                 var parent = sortedParents_1[_i];
39288                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
39289                                 if (parentChain) {
39290                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
39291                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
39292                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
39293                                         // No need to lookup an alias for the symbol in itself
39294                                         accessibleSymbolChain = parentChain;
39295                                         break;
39296                                     }
39297                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
39298                                     break;
39299                                 }
39300                             }
39301                         }
39302                     }
39303                     if (accessibleSymbolChain) {
39304                         return accessibleSymbolChain;
39305                     }
39306                     if (
39307                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
39308                     endOfChain ||
39309                         // If a parent symbol is an anonymous type, don't write it.
39310                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
39311                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
39312                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39313                             return;
39314                         }
39315                         return [symbol];
39316                     }
39317                     function sortByBestName(a, b) {
39318                         var specifierA = parentSpecifiers[a];
39319                         var specifierB = parentSpecifiers[b];
39320                         if (specifierA && specifierB) {
39321                             var isBRelative = ts.pathIsRelative(specifierB);
39322                             if (ts.pathIsRelative(specifierA) === isBRelative) {
39323                                 // Both relative or both non-relative, sort by number of parts
39324                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
39325                             }
39326                             if (isBRelative) {
39327                                 // A is non-relative, B is relative: prefer A
39328                                 return -1;
39329                             }
39330                             // A is relative, B is non-relative: prefer B
39331                             return 1;
39332                         }
39333                         return 0;
39334                     }
39335                 }
39336             }
39337             function typeParametersToTypeParameterDeclarations(symbol, context) {
39338                 var typeParameterNodes;
39339                 var targetSymbol = getTargetSymbol(symbol);
39340                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
39341                     typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
39342                 }
39343                 return typeParameterNodes;
39344             }
39345             function lookupTypeParameterNodes(chain, index, context) {
39346                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
39347                 var symbol = chain[index];
39348                 var symbolId = "" + getSymbolId(symbol);
39349                 if (context.typeParameterSymbolList && context.typeParameterSymbolList.get(symbolId)) {
39350                     return undefined;
39351                 }
39352                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = ts.createMap())).set(symbolId, true);
39353                 var typeParameterNodes;
39354                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
39355                     var parentSymbol = symbol;
39356                     var nextSymbol_1 = chain[index + 1];
39357                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
39358                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
39359                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
39360                     }
39361                     else {
39362                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
39363                     }
39364                 }
39365                 return typeParameterNodes;
39366             }
39367             /**
39368              * Given A[B][C][D], finds A[B]
39369              */
39370             function getTopmostIndexedAccessType(top) {
39371                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
39372                     return getTopmostIndexedAccessType(top.objectType);
39373                 }
39374                 return top;
39375             }
39376             function getSpecifierForModuleSymbol(symbol, context) {
39377                 var file = ts.getDeclarationOfKind(symbol, 290 /* SourceFile */);
39378                 if (!file) {
39379                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
39380                     if (equivalentFileSymbol) {
39381                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 290 /* SourceFile */);
39382                     }
39383                 }
39384                 if (file && file.moduleName !== undefined) {
39385                     // Use the amd name if it is available
39386                     return file.moduleName;
39387                 }
39388                 if (!file) {
39389                     if (context.tracker.trackReferencedAmbientModule) {
39390                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
39391                         if (ts.length(ambientDecls)) {
39392                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
39393                                 var decl = ambientDecls_1[_i];
39394                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
39395                             }
39396                         }
39397                     }
39398                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39399                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39400                     }
39401                 }
39402                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
39403                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
39404                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
39405                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
39406                     }
39407                     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
39408                 }
39409                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
39410                 var links = getSymbolLinks(symbol);
39411                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
39412                 if (!specifier) {
39413                     var isBundle_1 = (compilerOptions.out || compilerOptions.outFile);
39414                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
39415                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
39416                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
39417                     // specifier preference
39418                     var moduleResolverHost = context.tracker.moduleResolverHost;
39419                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
39420                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative" }));
39421                     links.specifierCache = links.specifierCache || ts.createMap();
39422                     links.specifierCache.set(contextFile.path, specifier);
39423                 }
39424                 return specifier;
39425             }
39426             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
39427                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
39428                 var isTypeOf = meaning === 111551 /* Value */;
39429                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39430                     // module is root, must use `ImportTypeNode`
39431                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
39432                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
39433                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
39434                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
39435                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
39436                         // since declaration files with these kinds of references are liable to fail when published :(
39437                         context.encounteredError = true;
39438                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
39439                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
39440                         }
39441                     }
39442                     var lit = ts.createLiteralTypeNode(ts.createLiteral(specifier));
39443                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
39444                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
39445                     context.approximateLength += specifier.length + 10; // specifier + import("")
39446                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
39447                         if (nonRootParts) {
39448                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
39449                             lastId.typeArguments = undefined;
39450                         }
39451                         return ts.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
39452                     }
39453                     else {
39454                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
39455                         var qualifier = splitNode.objectType.typeName;
39456                         return ts.createIndexedAccessTypeNode(ts.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
39457                     }
39458                 }
39459                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
39460                 if (ts.isIndexedAccessTypeNode(entityName)) {
39461                     return entityName; // Indexed accesses can never be `typeof`
39462                 }
39463                 if (isTypeOf) {
39464                     return ts.createTypeQueryNode(entityName);
39465                 }
39466                 else {
39467                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
39468                     var lastTypeArgs = lastId.typeArguments;
39469                     lastId.typeArguments = undefined;
39470                     return ts.createTypeReferenceNode(entityName, lastTypeArgs);
39471                 }
39472                 function createAccessFromSymbolChain(chain, index, stopper) {
39473                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
39474                     var symbol = chain[index];
39475                     var parent = chain[index - 1];
39476                     var symbolName;
39477                     if (index === 0) {
39478                         context.flags |= 16777216 /* InInitialEntityName */;
39479                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39480                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
39481                         context.flags ^= 16777216 /* InInitialEntityName */;
39482                     }
39483                     else {
39484                         if (parent && getExportsOfSymbol(parent)) {
39485                             var exports_1 = getExportsOfSymbol(parent);
39486                             ts.forEachEntry(exports_1, function (ex, name) {
39487                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
39488                                     symbolName = ts.unescapeLeadingUnderscores(name);
39489                                     return true;
39490                                 }
39491                             });
39492                         }
39493                     }
39494                     if (!symbolName) {
39495                         symbolName = getNameOfSymbolAsWritten(symbol, context);
39496                     }
39497                     context.approximateLength += symbolName.length + 1;
39498                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
39499                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
39500                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
39501                         // Should use an indexed access
39502                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39503                         if (ts.isIndexedAccessTypeNode(LHS)) {
39504                             return ts.createIndexedAccessTypeNode(LHS, ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39505                         }
39506                         else {
39507                             return ts.createIndexedAccessTypeNode(ts.createTypeReferenceNode(LHS, typeParameterNodes), ts.createLiteralTypeNode(ts.createLiteral(symbolName)));
39508                         }
39509                     }
39510                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39511                     identifier.symbol = symbol;
39512                     if (index > stopper) {
39513                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
39514                         if (!ts.isEntityName(LHS)) {
39515                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
39516                         }
39517                         return ts.createQualifiedName(LHS, identifier);
39518                     }
39519                     return identifier;
39520                 }
39521             }
39522             function typeParameterShadowsNameInScope(escapedName, context, type) {
39523                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
39524                 if (result) {
39525                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
39526                         return false;
39527                     }
39528                     return true;
39529                 }
39530                 return false;
39531             }
39532             function typeParameterToName(type, context) {
39533                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
39534                     var cached = context.typeParameterNames.get("" + getTypeId(type));
39535                     if (cached) {
39536                         return cached;
39537                     }
39538                 }
39539                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
39540                 if (!(result.kind & 75 /* Identifier */)) {
39541                     return ts.createIdentifier("(Missing type parameter)");
39542                 }
39543                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
39544                     var rawtext = result.escapedText;
39545                     var i = 0;
39546                     var text = rawtext;
39547                     while ((context.typeParameterNamesByText && context.typeParameterNamesByText.get(text)) || typeParameterShadowsNameInScope(text, context, type)) {
39548                         i++;
39549                         text = rawtext + "_" + i;
39550                     }
39551                     if (text !== rawtext) {
39552                         result = ts.createIdentifier(text, result.typeArguments);
39553                     }
39554                     (context.typeParameterNames || (context.typeParameterNames = ts.createMap())).set("" + getTypeId(type), result);
39555                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = ts.createMap())).set(result.escapedText, true);
39556                 }
39557                 return result;
39558             }
39559             function symbolToName(symbol, context, meaning, expectsIdentifier) {
39560                 var chain = lookupSymbolChain(symbol, context, meaning);
39561                 if (expectsIdentifier && chain.length !== 1
39562                     && !context.encounteredError
39563                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
39564                     context.encounteredError = true;
39565                 }
39566                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
39567                 function createEntityNameFromSymbolChain(chain, index) {
39568                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39569                     var symbol = chain[index];
39570                     if (index === 0) {
39571                         context.flags |= 16777216 /* InInitialEntityName */;
39572                     }
39573                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39574                     if (index === 0) {
39575                         context.flags ^= 16777216 /* InInitialEntityName */;
39576                     }
39577                     var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39578                     identifier.symbol = symbol;
39579                     return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
39580                 }
39581             }
39582             function symbolToExpression(symbol, context, meaning) {
39583                 var chain = lookupSymbolChain(symbol, context, meaning);
39584                 return createExpressionFromSymbolChain(chain, chain.length - 1);
39585                 function createExpressionFromSymbolChain(chain, index) {
39586                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
39587                     var symbol = chain[index];
39588                     if (index === 0) {
39589                         context.flags |= 16777216 /* InInitialEntityName */;
39590                     }
39591                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
39592                     if (index === 0) {
39593                         context.flags ^= 16777216 /* InInitialEntityName */;
39594                     }
39595                     var firstChar = symbolName.charCodeAt(0);
39596                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
39597                         return ts.createLiteral(getSpecifierForModuleSymbol(symbol, context));
39598                     }
39599                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
39600                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
39601                         ts.isIdentifierStart(firstChar, languageVersion);
39602                     if (index === 0 || canUsePropertyAccess) {
39603                         var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39604                         identifier.symbol = symbol;
39605                         return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
39606                     }
39607                     else {
39608                         if (firstChar === 91 /* openBracket */) {
39609                             symbolName = symbolName.substring(1, symbolName.length - 1);
39610                             firstChar = symbolName.charCodeAt(0);
39611                         }
39612                         var expression = void 0;
39613                         if (ts.isSingleOrDoubleQuote(firstChar)) {
39614                             expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); }));
39615                             expression.singleQuote = firstChar === 39 /* singleQuote */;
39616                         }
39617                         else if (("" + +symbolName) === symbolName) {
39618                             expression = ts.createLiteral(+symbolName);
39619                         }
39620                         if (!expression) {
39621                             expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
39622                             expression.symbol = symbol;
39623                         }
39624                         return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression);
39625                     }
39626                 }
39627             }
39628             function isSingleQuotedStringNamed(d) {
39629                 var name = ts.getNameOfDeclaration(d);
39630                 if (name && ts.isStringLiteral(name) && (name.singleQuote ||
39631                     (!ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")))) {
39632                     return true;
39633                 }
39634                 return false;
39635             }
39636             function getPropertyNameNodeForSymbol(symbol, context) {
39637                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
39638                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
39639                 if (fromNameType) {
39640                     return fromNameType;
39641                 }
39642                 if (ts.isKnownSymbol(symbol)) {
39643                     return ts.createComputedPropertyName(ts.createPropertyAccess(ts.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
39644                 }
39645                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
39646                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, singleQuote);
39647             }
39648             // See getNameForSymbolFromNameType for a stringy equivalent
39649             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
39650                 var nameType = getSymbolLinks(symbol).nameType;
39651                 if (nameType) {
39652                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
39653                         var name = "" + nameType.value;
39654                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
39655                             return ts.createLiteral(name, !!singleQuote);
39656                         }
39657                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
39658                             return ts.createComputedPropertyName(ts.createLiteral(+name));
39659                         }
39660                         return createPropertyNameNodeForIdentifierOrLiteral(name);
39661                     }
39662                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
39663                         return ts.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
39664                     }
39665                 }
39666             }
39667             function createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote) {
39668                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.createIdentifier(name) : ts.createLiteral(isNumericLiteralName(name) && +name >= 0 ? +name : name, !!singleQuote);
39669             }
39670             function cloneNodeBuilderContext(context) {
39671                 var initial = __assign({}, context);
39672                 // Make type parameters created within this context not consume the name outside this context
39673                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
39674                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
39675                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
39676                 // were multiple generic overloads with similar generated type parameter names
39677                 // The effect:
39678                 // When we write out
39679                 // export const x: <T>(x: T) => T
39680                 // export const y: <T>(x: T) => T
39681                 // we write it out like that, rather than as
39682                 // export const x: <T>(x: T) => T
39683                 // export const y: <T_1>(x: T_1) => T_1
39684                 if (initial.typeParameterNames) {
39685                     initial.typeParameterNames = ts.cloneMap(initial.typeParameterNames);
39686                 }
39687                 if (initial.typeParameterNamesByText) {
39688                     initial.typeParameterNamesByText = ts.cloneMap(initial.typeParameterNamesByText);
39689                 }
39690                 if (initial.typeParameterSymbolList) {
39691                     initial.typeParameterSymbolList = ts.cloneMap(initial.typeParameterSymbolList);
39692                 }
39693                 return initial;
39694             }
39695             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
39696                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
39697             }
39698             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
39699                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
39700             }
39701             /**
39702              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
39703              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
39704              */
39705             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
39706                 if (type !== errorType && enclosingDeclaration) {
39707                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
39708                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
39709                         // try to reuse the existing annotation
39710                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
39711                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
39712                             var result_4 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
39713                             if (result_4) {
39714                                 return result_4;
39715                             }
39716                         }
39717                     }
39718                 }
39719                 var oldFlags = context.flags;
39720                 if (type.flags & 8192 /* UniqueESSymbol */ &&
39721                     type.symbol === symbol) {
39722                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
39723                 }
39724                 var result = typeToTypeNodeHelper(type, context);
39725                 context.flags = oldFlags;
39726                 return result;
39727             }
39728             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
39729                 if (type !== errorType && context.enclosingDeclaration) {
39730                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
39731                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
39732                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
39733                         if (result) {
39734                             return result;
39735                         }
39736                     }
39737                 }
39738                 return typeToTypeNodeHelper(type, context);
39739             }
39740             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
39741                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
39742                     cancellationToken.throwIfCancellationRequested();
39743                 }
39744                 var hadError = false;
39745                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
39746                 if (hadError) {
39747                     return undefined;
39748                 }
39749                 return transformed === existing ? ts.getMutableClone(existing) : transformed;
39750                 function visitExistingNodeTreeSymbols(node) {
39751                     var _a, _b;
39752                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
39753                     if (ts.isJSDocAllType(node) || node.kind === 302 /* JSDocNamepathType */) {
39754                         return ts.createKeywordTypeNode(125 /* AnyKeyword */);
39755                     }
39756                     if (ts.isJSDocUnknownType(node)) {
39757                         return ts.createKeywordTypeNode(148 /* UnknownKeyword */);
39758                     }
39759                     if (ts.isJSDocNullableType(node)) {
39760                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(100 /* NullKeyword */)]);
39761                     }
39762                     if (ts.isJSDocOptionalType(node)) {
39763                         return ts.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.createKeywordTypeNode(146 /* UndefinedKeyword */)]);
39764                     }
39765                     if (ts.isJSDocNonNullableType(node)) {
39766                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
39767                     }
39768                     if (ts.isJSDocVariadicType(node)) {
39769                         return ts.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39770                     }
39771                     if (ts.isJSDocTypeLiteral(node)) {
39772                         return ts.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
39773                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
39774                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
39775                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
39776                             return ts.createPropertySignature(
39777                             /*modifiers*/ undefined, name, t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.createToken(57 /* QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.createKeywordTypeNode(125 /* AnyKeyword */), 
39778                             /*initializer*/ undefined);
39779                         }));
39780                     }
39781                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
39782                         return ts.setOriginalNode(ts.createKeywordTypeNode(125 /* AnyKeyword */), node);
39783                     }
39784                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
39785                         return ts.createTypeLiteralNode([ts.createIndexSignature(
39786                             /*decorators*/ undefined, 
39787                             /*modifiers*/ undefined, [ts.createParameter(
39788                                 /*decorators*/ undefined, 
39789                                 /*modifiers*/ undefined, 
39790                                 /*dotdotdotToken*/ undefined, "x", 
39791                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
39792                     }
39793                     if (ts.isJSDocFunctionType(node)) {
39794                         if (ts.isJSDocConstructSignature(node)) {
39795                             var newTypeNode_1;
39796                             return ts.createConstructorTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.mapDefined(node.parameters, function (p, i) { return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode_1 = p.type, undefined) : ts.createParameter(
39797                             /*decorators*/ undefined, 
39798                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39799                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols));
39800                         }
39801                         else {
39802                             return ts.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.createParameter(
39803                             /*decorators*/ undefined, 
39804                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), p.name || getEffectiveDotDotDotForParameter(p) ? "args" : "arg" + i, p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
39805                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols));
39806                         }
39807                     }
39808                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
39809                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
39810                     }
39811                     if (ts.isLiteralImportTypeNode(node)) {
39812                         return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
39813                     }
39814                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
39815                         var leftmost = ts.getFirstIdentifier(node);
39816                         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)))) {
39817                             hadError = true;
39818                             return node;
39819                         }
39820                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
39821                         if (sym) {
39822                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
39823                                 hadError = true;
39824                             }
39825                             else {
39826                                 (_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 */);
39827                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
39828                             }
39829                             if (ts.isIdentifier(node)) {
39830                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.getMutableClone(node);
39831                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
39832                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
39833                             }
39834                         }
39835                     }
39836                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
39837                     function getEffectiveDotDotDotForParameter(p) {
39838                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.createToken(25 /* DotDotDotToken */) : undefined);
39839                     }
39840                     function rewriteModuleSpecifier(parent, lit) {
39841                         if (bundled) {
39842                             if (context.tracker && context.tracker.moduleResolverHost) {
39843                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
39844                                 if (targetFile) {
39845                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
39846                                     var resolverHost = {
39847                                         getCanonicalFileName: getCanonicalFileName,
39848                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
39849                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
39850                                     };
39851                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
39852                                     return ts.createLiteral(newName);
39853                                 }
39854                             }
39855                         }
39856                         else {
39857                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
39858                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
39859                                 if (moduleSym) {
39860                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
39861                                 }
39862                             }
39863                         }
39864                         return lit;
39865                     }
39866                 }
39867             }
39868             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
39869                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.createProperty, 161 /* MethodDeclaration */, /*useAcessors*/ true);
39870                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type, initializer) { return ts.createPropertySignature(mods, name, question, type, initializer); }, 160 /* MethodSignature */, /*useAcessors*/ false);
39871                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
39872                 // declaration mapping
39873                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
39874                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
39875                 // we're trying to emit from later on)
39876                 var enclosingDeclaration = context.enclosingDeclaration;
39877                 var results = [];
39878                 var visitedSymbols = ts.createMap();
39879                 var deferredPrivates;
39880                 var oldcontext = context;
39881                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: ts.createMap(), remappedSymbolNames: ts.createMap(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
39882                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
39883                             if (accessibleResult.accessibility === 0 /* Accessible */) {
39884                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
39885                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
39886                                 if (!(sym.flags & 4 /* Property */)) {
39887                                     includePrivateSymbol(chain[0]);
39888                                 }
39889                             }
39890                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
39891                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
39892                             }
39893                         } }) });
39894                 if (oldcontext.usedSymbolNames) {
39895                     oldcontext.usedSymbolNames.forEach(function (_, name) {
39896                         context.usedSymbolNames.set(name, true);
39897                     });
39898                 }
39899                 ts.forEachEntry(symbolTable, function (symbol, name) {
39900                     var baseName = ts.unescapeLeadingUnderscores(name);
39901                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
39902                 });
39903                 var addingDeclare = !bundled;
39904                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
39905                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
39906                     symbolTable = ts.createSymbolTable();
39907                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
39908                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
39909                 }
39910                 visitSymbolTable(symbolTable);
39911                 return mergeRedundantStatements(results);
39912                 function isIdentifierAndNotUndefined(node) {
39913                     return !!node && node.kind === 75 /* Identifier */;
39914                 }
39915                 function getNamesOfDeclaration(statement) {
39916                     if (ts.isVariableStatement(statement)) {
39917                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
39918                     }
39919                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
39920                 }
39921                 function flattenExportAssignedNamespace(statements) {
39922                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
39923                     var ns = ts.find(statements, ts.isModuleDeclaration);
39924                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
39925                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
39926                         ns.body && ts.isModuleBlock(ns.body)) {
39927                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
39928                         //  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
39929                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getModifierFlags(s) & 1 /* Export */); });
39930                         if (ts.length(excessExports)) {
39931                             ns.body.statements = ts.createNodeArray(__spreadArrays(ns.body.statements, [ts.createExportDeclaration(
39932                                 /*decorators*/ undefined, 
39933                                 /*modifiers*/ undefined, ts.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.createExportSpecifier(/*alias*/ undefined, id); })), 
39934                                 /*moduleSpecifier*/ undefined)]));
39935                         }
39936                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
39937                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, ns.name); })) {
39938                             results = [];
39939                             ts.forEach(ns.body.statements, function (s) {
39940                                 addResult(s, 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
39941                             });
39942                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
39943                         }
39944                     }
39945                     return statements;
39946                 }
39947                 function mergeExportDeclarations(statements) {
39948                     // Pass 2: Combine all `export {}` declarations
39949                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39950                     if (ts.length(exports) > 1) {
39951                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
39952                         statements = __spreadArrays(nonExports, [ts.createExportDeclaration(
39953                             /*decorators*/ undefined, 
39954                             /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
39955                             /*moduleSpecifier*/ undefined)]);
39956                     }
39957                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
39958                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
39959                     if (ts.length(reexports) > 1) {
39960                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
39961                         if (groups.length !== reexports.length) {
39962                             var _loop_8 = function (group_1) {
39963                                 if (group_1.length > 1) {
39964                                     // remove group members from statements and then merge group members and add back to statements
39965                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
39966                                         ts.createExportDeclaration(
39967                                         /*decorators*/ undefined, 
39968                                         /*modifiers*/ undefined, ts.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
39969                                     ]);
39970                                 }
39971                             };
39972                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
39973                                 var group_1 = groups_1[_i];
39974                                 _loop_8(group_1);
39975                             }
39976                         }
39977                     }
39978                     return statements;
39979                 }
39980                 function inlineExportModifiers(statements) {
39981                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
39982                     var exportDecl = ts.find(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause; });
39983                     if (exportDecl && exportDecl.exportClause && ts.isNamedExports(exportDecl.exportClause)) {
39984                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
39985                             if (!e.propertyName) {
39986                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
39987                                 var associated = ts.filter(statements, function (s) { return ts.nodeHasName(s, e.name); });
39988                                 if (ts.length(associated) && ts.every(associated, canHaveExportModifier)) {
39989                                     ts.forEach(associated, addExportModifier);
39990                                     return undefined;
39991                                 }
39992                             }
39993                             return e;
39994                         });
39995                         if (!ts.length(replacements)) {
39996                             // all clauses removed, filter the export declaration
39997                             statements = ts.filter(statements, function (s) { return s !== exportDecl; });
39998                         }
39999                         else {
40000                             // some items filtered, others not - update the export declaration
40001                             // (mutating because why not, we're building a whole new tree here anyway)
40002                             exportDecl.exportClause.elements = ts.createNodeArray(replacements);
40003                         }
40004                     }
40005                     return statements;
40006                 }
40007                 function mergeRedundantStatements(statements) {
40008                     statements = flattenExportAssignedNamespace(statements);
40009                     statements = mergeExportDeclarations(statements);
40010                     statements = inlineExportModifiers(statements);
40011                     // 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
40012                     // declaration privacy is respected.
40013                     if (enclosingDeclaration &&
40014                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
40015                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
40016                         statements.push(ts.createEmptyExports());
40017                     }
40018                     return statements;
40019                 }
40020                 function canHaveExportModifier(node) {
40021                     return ts.isEnumDeclaration(node) ||
40022                         ts.isVariableStatement(node) ||
40023                         ts.isFunctionDeclaration(node) ||
40024                         ts.isClassDeclaration(node) ||
40025                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
40026                         ts.isInterfaceDeclaration(node) ||
40027                         isTypeDeclaration(node);
40028                 }
40029                 function addExportModifier(statement) {
40030                     var flags = (ts.getModifierFlags(statement) | 1 /* Export */) & ~2 /* Ambient */;
40031                     statement.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flags));
40032                     statement.modifierFlagsCache = 0;
40033                 }
40034                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
40035                     var oldDeferredPrivates = deferredPrivates;
40036                     if (!suppressNewPrivateContext) {
40037                         deferredPrivates = ts.createMap();
40038                     }
40039                     symbolTable.forEach(function (symbol) {
40040                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
40041                     });
40042                     if (!suppressNewPrivateContext) {
40043                         // deferredPrivates will be filled up by visiting the symbol table
40044                         // And will continue to iterate as elements are added while visited `deferredPrivates`
40045                         // (As that's how a map iterator is defined to work)
40046                         deferredPrivates.forEach(function (symbol) {
40047                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
40048                         });
40049                     }
40050                     deferredPrivates = oldDeferredPrivates;
40051                 }
40052                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
40053                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
40054                     // still skip reserializing it if we encounter the merged product later on
40055                     var visitedSym = getMergedSymbol(symbol);
40056                     if (visitedSymbols.has("" + getSymbolId(visitedSym))) {
40057                         return; // Already printed
40058                     }
40059                     visitedSymbols.set("" + getSymbolId(visitedSym), true);
40060                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
40061                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
40062                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
40063                         var oldContext = context;
40064                         context = cloneNodeBuilderContext(context);
40065                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
40066                         context = oldContext;
40067                         return result;
40068                     }
40069                 }
40070                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
40071                 // or a merge of some number of those.
40072                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
40073                 // each symbol in only one of the representations
40074                 // Also, synthesizing a default export of some kind
40075                 // If it's an alias: emit `export default ref`
40076                 // If it's a property: emit `export default _default` with a `_default` prop
40077                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
40078                 // These forms can merge, eg (`export default 12; export default interface A {}`)
40079                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
40080                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
40081                     var isDefault = symbol.escapedName === "default" /* Default */;
40082                     if (!(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
40083                         // 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` :(
40084                         context.encounteredError = true;
40085                         // TODO: Issue error via symbol tracker?
40086                         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
40087                     }
40088                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
40089                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
40090                     if (needsPostExportDefault) {
40091                         isPrivate = true;
40092                     }
40093                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
40094                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
40095                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
40096                         symbol.escapedName !== "export=" /* ExportEquals */;
40097                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
40098                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
40099                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40100                     }
40101                     if (symbol.flags & 524288 /* TypeAlias */) {
40102                         serializeTypeAlias(symbol, symbolName, modifierFlags);
40103                     }
40104                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
40105                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
40106                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
40107                         && symbol.escapedName !== "export=" /* ExportEquals */
40108                         && !(symbol.flags & 4194304 /* Prototype */)
40109                         && !(symbol.flags & 32 /* Class */)
40110                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
40111                         serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags);
40112                     }
40113                     if (symbol.flags & 384 /* Enum */) {
40114                         serializeEnum(symbol, symbolName, modifierFlags);
40115                     }
40116                     if (symbol.flags & 32 /* Class */) {
40117                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
40118                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
40119                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
40120                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
40121                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40122                         }
40123                         else {
40124                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40125                         }
40126                     }
40127                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
40128                         serializeModule(symbol, symbolName, modifierFlags);
40129                     }
40130                     if (symbol.flags & 64 /* Interface */) {
40131                         serializeInterface(symbol, symbolName, modifierFlags);
40132                     }
40133                     if (symbol.flags & 2097152 /* Alias */) {
40134                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
40135                     }
40136                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
40137                         serializeMaybeAliasAssignment(symbol);
40138                     }
40139                     if (symbol.flags & 8388608 /* ExportStar */) {
40140                         // synthesize export * from "moduleReference"
40141                         // Straightforward - only one thing to do - make an export declaration
40142                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
40143                             var node = _a[_i];
40144                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
40145                             if (!resolvedModule)
40146                                 continue;
40147                             addResult(ts.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*exportClause*/ undefined, ts.createLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
40148                         }
40149                     }
40150                     if (needsPostExportDefault) {
40151                         addResult(ts.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
40152                     }
40153                 }
40154                 function includePrivateSymbol(symbol) {
40155                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
40156                         return;
40157                     ts.Debug.assertIsDefined(deferredPrivates);
40158                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
40159                     deferredPrivates.set("" + getSymbolId(symbol), symbol);
40160                 }
40161                 function isExportingScope(enclosingDeclaration) {
40162                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
40163                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
40164                 }
40165                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
40166                 // Note: This _mutates_ `node` without using `updateNode` - the assumption being that all nodes should be manufactured fresh by the node builder
40167                 function addResult(node, additionalModifierFlags) {
40168                     var newModifierFlags = 0 /* None */;
40169                     if (additionalModifierFlags & 1 /* Export */ &&
40170                         enclosingDeclaration &&
40171                         isExportingScope(enclosingDeclaration) &&
40172                         canHaveExportModifier(node)) {
40173                         // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
40174                         newModifierFlags |= 1 /* Export */;
40175                     }
40176                     if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
40177                         (!enclosingDeclaration || !(enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
40178                         (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
40179                         // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
40180                         newModifierFlags |= 2 /* Ambient */;
40181                     }
40182                     if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
40183                         newModifierFlags |= 512 /* Default */;
40184                     }
40185                     if (newModifierFlags) {
40186                         node.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(newModifierFlags | ts.getModifierFlags(node)));
40187                         node.modifierFlagsCache = 0; // Reset computed flags cache
40188                     }
40189                     results.push(node);
40190                 }
40191                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
40192                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
40193                     var typeParams = getSymbolLinks(symbol).typeParameters;
40194                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
40195                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
40196                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
40197                     var oldFlags = context.flags;
40198                     context.flags |= 8388608 /* InTypeAlias */;
40199                     addResult(ts.setSyntheticLeadingComments(ts.createTypeAliasDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, typeToTypeNodeHelper(aliasType, context)), !commentText ? [] : [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]), modifierFlags);
40200                     context.flags = oldFlags;
40201                 }
40202                 function serializeInterface(symbol, symbolName, modifierFlags) {
40203                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
40204                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40205                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40206                     var baseTypes = getBaseTypes(interfaceType);
40207                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
40208                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
40209                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 165 /* CallSignature */);
40210                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 166 /* ConstructSignature */);
40211                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
40212                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b); }))];
40213                     addResult(ts.createInterfaceDeclaration(
40214                     /*decorators*/ undefined, 
40215                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
40216                 }
40217                 function getNamespaceMembersForSerialization(symbol) {
40218                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
40219                 }
40220                 function isTypeOnlyNamespace(symbol) {
40221                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
40222                 }
40223                 function serializeModule(symbol, symbolName, modifierFlags) {
40224                     var members = getNamespaceMembersForSerialization(symbol);
40225                     // 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)
40226                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
40227                     var realMembers = locationMap.get("real") || ts.emptyArray;
40228                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
40229                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
40230                     // 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,
40231                     // so we don't even have placeholders to fill in.
40232                     if (ts.length(realMembers)) {
40233                         var localName = getInternalSymbolName(symbol, symbolName);
40234                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
40235                     }
40236                     if (ts.length(mergedMembers)) {
40237                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
40238                         var localName = getInternalSymbolName(symbol, symbolName);
40239                         var nsBody = ts.createModuleBlock([ts.createExportDeclaration(
40240                             /*decorators*/ undefined, 
40241                             /*modifiers*/ undefined, ts.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
40242                                 var _a, _b;
40243                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
40244                                 var localName = getInternalSymbolName(s, name);
40245                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
40246                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
40247                                     (_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);
40248                                     return undefined;
40249                                 }
40250                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40251                                 includePrivateSymbol(target || s);
40252                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
40253                                 return ts.createExportSpecifier(name === targetName ? undefined : targetName, name);
40254                             })))]);
40255                         addResult(ts.createModuleDeclaration(
40256                         /*decorators*/ undefined, 
40257                         /*modifiers*/ undefined, ts.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
40258                     }
40259                 }
40260                 function serializeEnum(symbol, symbolName, modifierFlags) {
40261                     addResult(ts.createEnumDeclaration(
40262                     /*decorators*/ undefined, ts.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) {
40263                         // TODO: Handle computed names
40264                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
40265                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
40266                         // _on the declaration_, not on the declaration's symbol...
40267                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) && getConstantValue(p.declarations[0]);
40268                         return ts.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined : ts.createLiteral(initializedValue));
40269                     })), modifierFlags);
40270                 }
40271                 function serializeVariableOrProperty(symbol, symbolName, isPrivate, needsPostExportDefault, propertyAsAlias, modifierFlags) {
40272                     if (propertyAsAlias) {
40273                         serializeMaybeAliasAssignment(symbol);
40274                     }
40275                     else {
40276                         var type = getTypeOfSymbol(symbol);
40277                         var localName = getInternalSymbolName(symbol, symbolName);
40278                         if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
40279                             // 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
40280                             serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
40281                         }
40282                         else {
40283                             // 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!_
40284                             // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
40285                             var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
40286                                 : isConstVariable(symbol) ? 2 /* Const */
40287                                     : 1 /* Let */;
40288                             var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
40289                             var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
40290                             if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
40291                                 textRange = textRange.parent.parent;
40292                             }
40293                             var statement = ts.setTextRange(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40294                                 ts.createVariableDeclaration(name, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40295                             ], flags)), textRange);
40296                             addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
40297                             if (name !== localName && !isPrivate) {
40298                                 // We rename the variable declaration we generate for Property symbols since they may have a name which
40299                                 // conflicts with a local declaration. For example, given input:
40300                                 // ```
40301                                 // function g() {}
40302                                 // module.exports.g = g
40303                                 // ```
40304                                 // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
40305                                 // Naively, we would emit
40306                                 // ```
40307                                 // function g() {}
40308                                 // export const g: typeof g;
40309                                 // ```
40310                                 // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
40311                                 // the export declaration shadows it.
40312                                 // To work around that, we instead write
40313                                 // ```
40314                                 // function g() {}
40315                                 // const g_1: typeof g;
40316                                 // export { g_1 as g };
40317                                 // ```
40318                                 // To create an export named `g` that does _not_ shadow the local `g`
40319                                 addResult(ts.createExportDeclaration(
40320                                 /*decorators*/ undefined, 
40321                                 /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(name, localName)])), 0 /* None */);
40322                             }
40323                         }
40324                     }
40325                 }
40326                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
40327                     var signatures = getSignaturesOfType(type, 0 /* Call */);
40328                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
40329                         var sig = signatures_2[_i];
40330                         // Each overload becomes a separate function declaration, in order
40331                         var decl = signatureToSignatureDeclarationHelper(sig, 244 /* FunctionDeclaration */, context, includePrivateSymbol, bundled);
40332                         decl.name = ts.createIdentifier(localName);
40333                         // for expressions assigned to `var`s, use the `var` as the text range
40334                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
40335                     }
40336                     // Module symbol emit will take care of module-y members, provided it has exports
40337                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
40338                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
40339                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
40340                     }
40341                 }
40342                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
40343                     if (ts.length(props)) {
40344                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
40345                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
40346                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
40347                             }) ? "local" : "remote";
40348                         });
40349                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
40350                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
40351                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
40352                         // Example:
40353                         // import Foo_1 = require("./exporter");
40354                         // export namespace ns {
40355                         //     import Foo = Foo_1.Foo;
40356                         //     export { Foo };
40357                         //     export const c: number;
40358                         // }
40359                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
40360                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
40361                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
40362                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
40363                         // emit akin to the above would be needed.
40364                         // Add a namespace
40365                         var fakespace = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.createIdentifier(localName), ts.createModuleBlock([]), 16 /* Namespace */);
40366                         fakespace.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
40367                         fakespace.parent = enclosingDeclaration;
40368                         fakespace.locals = ts.createSymbolTable(props);
40369                         fakespace.symbol = props[0].parent;
40370                         var oldResults = results;
40371                         results = [];
40372                         var oldAddingDeclare = addingDeclare;
40373                         addingDeclare = false;
40374                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
40375                         var oldContext = context;
40376                         context = subcontext;
40377                         // 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
40378                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
40379                         context = oldContext;
40380                         addingDeclare = oldAddingDeclare;
40381                         var declarations = results;
40382                         results = oldResults;
40383                         fakespace.flags ^= 8 /* Synthesized */; // reset synthesized
40384                         fakespace.parent = undefined;
40385                         fakespace.locals = undefined;
40386                         fakespace.symbol = undefined;
40387                         fakespace.body = ts.createModuleBlock(declarations);
40388                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
40389                     }
40390                 }
40391                 function isNamespaceMember(p) {
40392                     return !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.isClassLike(p.valueDeclaration.parent));
40393                 }
40394                 function serializeAsClass(symbol, localName, modifierFlags) {
40395                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
40396                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
40397                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
40398                     var baseTypes = getBaseTypes(classType);
40399                     var implementsTypes = getImplementsTypes(classType);
40400                     var staticType = getTypeOfSymbol(symbol);
40401                     var staticBaseType = getBaseConstructorTypeOfClass(staticType);
40402                     var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.createHeritageClause(90 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsTypes) ? [] : [ts.createHeritageClause(113 /* ImplementsKeyword */, ts.map(implementsTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]);
40403                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
40404                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
40405                         // `valueDeclaration` could be undefined if inherited from
40406                         // a union/intersection base type, but inherited properties
40407                         // don't matter here.
40408                         var valueDecl = s.valueDeclaration;
40409                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
40410                     });
40411                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
40412                         // `valueDeclaration` could be undefined if inherited from
40413                         // a union/intersection base type, but inherited properties
40414                         // don't matter here.
40415                         var valueDecl = s.valueDeclaration;
40416                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
40417                     });
40418                     // Boil down all private properties into a single one.
40419                     var privateProperties = hasPrivateIdentifier ?
40420                         [ts.createProperty(
40421                             /*decorators*/ undefined, 
40422                             /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
40423                             /*questionOrExclamationToken*/ undefined, 
40424                             /*type*/ undefined, 
40425                             /*initializer*/ undefined)] :
40426                         ts.emptyArray;
40427                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
40428                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
40429                     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); });
40430                     var constructors = serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 162 /* Constructor */);
40431                     for (var _i = 0, constructors_1 = constructors; _i < constructors_1.length; _i++) {
40432                         var c = constructors_1[_i];
40433                         // A constructor's return type and type parameters are supposed to be controlled by the enclosing class declaration
40434                         // `signatureToSignatureDeclarationHelper` appends them regardless, so for now we delete them here
40435                         c.type = undefined;
40436                         c.typeParameters = undefined;
40437                     }
40438                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
40439                     addResult(ts.setTextRange(ts.createClassDeclaration(
40440                     /*decorators*/ undefined, 
40441                     /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, staticMembers, constructors, publicProperties, privateProperties)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags);
40442                 }
40443                 function serializeAsAlias(symbol, localName, modifierFlags) {
40444                     // synthesize an alias, eg `export { symbolName as Name }`
40445                     // need to mark the alias `symbol` points at
40446                     // as something we need to serialize as a private declaration as well
40447                     var node = getDeclarationOfAliasSymbol(symbol);
40448                     if (!node)
40449                         return ts.Debug.fail();
40450                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
40451                     if (!target) {
40452                         return;
40453                     }
40454                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
40455                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
40456                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
40457                         verbatimTargetName = "default" /* Default */;
40458                     }
40459                     var targetName = getInternalSymbolName(target, verbatimTargetName);
40460                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
40461                     switch (node.kind) {
40462                         case 253 /* ImportEqualsDeclaration */:
40463                             // Could be a local `import localName = ns.member` or
40464                             // an external `import localName = require("whatever")`
40465                             var isLocalImport = !(target.flags & 512 /* ValueModule */);
40466                             addResult(ts.createImportEqualsDeclaration(
40467                             /*decorators*/ undefined, 
40468                             /*modifiers*/ undefined, ts.createIdentifier(localName), isLocalImport
40469                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
40470                                 : ts.createExternalModuleReference(ts.createLiteral(getSpecifierForModuleSymbol(symbol, context)))), isLocalImport ? modifierFlags : 0 /* None */);
40471                             break;
40472                         case 252 /* NamespaceExportDeclaration */:
40473                             // export as namespace foo
40474                             // TODO: Not part of a file's local or export symbol tables
40475                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
40476                             addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
40477                             break;
40478                         case 255 /* ImportClause */:
40479                             addResult(ts.createImportDeclaration(
40480                             /*decorators*/ undefined, 
40481                             /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), 
40482                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
40483                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
40484                             // In such cases, the `target` refers to the module itself already
40485                             ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40486                             break;
40487                         case 256 /* NamespaceImport */:
40488                             addResult(ts.createImportDeclaration(
40489                             /*decorators*/ undefined, 
40490                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40491                             break;
40492                         case 262 /* NamespaceExport */:
40493                             addResult(ts.createExportDeclaration(
40494                             /*decorators*/ undefined, 
40495                             /*modifiers*/ undefined, ts.createNamespaceExport(ts.createIdentifier(localName)), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
40496                             break;
40497                         case 258 /* ImportSpecifier */:
40498                             addResult(ts.createImportDeclaration(
40499                             /*decorators*/ undefined, 
40500                             /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([
40501                                 ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName))
40502                             ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
40503                             break;
40504                         case 263 /* ExportSpecifier */:
40505                             // does not use localName because the symbol name in this case refers to the name in the exports table,
40506                             // which we must exactly preserve
40507                             var specifier = node.parent.parent.moduleSpecifier;
40508                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
40509                             // another file
40510                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.createLiteral(specifier.text) : undefined);
40511                             break;
40512                         case 259 /* ExportAssignment */:
40513                             serializeMaybeAliasAssignment(symbol);
40514                             break;
40515                         case 209 /* BinaryExpression */:
40516                         case 194 /* PropertyAccessExpression */:
40517                             // Could be best encoded as though an export specifier or as though an export assignment
40518                             // If name is default or export=, do an export assignment
40519                             // Otherwise do an export specifier
40520                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
40521                                 serializeMaybeAliasAssignment(symbol);
40522                             }
40523                             else {
40524                                 serializeExportSpecifier(localName, targetName);
40525                             }
40526                             break;
40527                         default:
40528                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
40529                     }
40530                 }
40531                 function serializeExportSpecifier(localName, targetName, specifier) {
40532                     addResult(ts.createExportDeclaration(
40533                     /*decorators*/ undefined, 
40534                     /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
40535                 }
40536                 function serializeMaybeAliasAssignment(symbol) {
40537                     if (symbol.flags & 4194304 /* Prototype */) {
40538                         return;
40539                     }
40540                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
40541                     var isExportEquals = name === "export=" /* ExportEquals */;
40542                     var isDefault = name === "default" /* Default */;
40543                     var isExportAssignment = isExportEquals || isDefault;
40544                     // synthesize export = ref
40545                     // ref should refer to either be a locally scoped symbol which we need to emit, or
40546                     // a reference to another namespace/module which we may need to emit an `import` statement for
40547                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
40548                     // serialize what the alias points to, preserve the declaration's initializer
40549                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
40550                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
40551                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
40552                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
40553                         // eg, `namespace A { export class B {} }; exports = A.B;`
40554                         // Technically, this is all that's required in the case where the assignment is an entity name expression
40555                         var expr = isExportAssignment ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl);
40556                         var first_1 = ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
40557                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
40558                         if (referenced || target) {
40559                             includePrivateSymbol(referenced || target);
40560                         }
40561                         // We disable the context's symbol tracker for the duration of this name serialization
40562                         // as, by virtue of being here, the name is required to print something, and we don't want to
40563                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
40564                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
40565                         // into the containing scope anyway, so we want to skip the visibility checks.
40566                         var oldTrack = context.tracker.trackSymbol;
40567                         context.tracker.trackSymbol = ts.noop;
40568                         if (isExportAssignment) {
40569                             results.push(ts.createExportAssignment(
40570                             /*decorators*/ undefined, 
40571                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
40572                         }
40573                         else {
40574                             if (first_1 === expr) {
40575                                 // serialize as `export {target as name}`
40576                                 serializeExportSpecifier(name, ts.idText(first_1));
40577                             }
40578                             else if (ts.isClassExpression(expr)) {
40579                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
40580                             }
40581                             else {
40582                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
40583                                 var varName = getUnusedName(name, symbol);
40584                                 addResult(ts.createImportEqualsDeclaration(
40585                                 /*decorators*/ undefined, 
40586                                 /*modifiers*/ undefined, ts.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
40587                                 serializeExportSpecifier(name, varName);
40588                             }
40589                         }
40590                         context.tracker.trackSymbol = oldTrack;
40591                     }
40592                     else {
40593                         // serialize as an anonymous property declaration
40594                         var varName = getUnusedName(name, symbol);
40595                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
40596                         // (Unwidened types can only exist in expression contexts and should never be serialized)
40597                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
40598                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
40599                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
40600                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignment ? 0 /* None */ : 1 /* Export */);
40601                         }
40602                         else {
40603                             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40604                                 ts.createVariableDeclaration(varName, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
40605                             ], 2 /* Const */));
40606                             addResult(statement, name === varName ? 1 /* Export */ : 0 /* None */);
40607                         }
40608                         if (isExportAssignment) {
40609                             results.push(ts.createExportAssignment(
40610                             /*decorators*/ undefined, 
40611                             /*modifiers*/ undefined, isExportEquals, ts.createIdentifier(varName)));
40612                         }
40613                         else if (name !== varName) {
40614                             serializeExportSpecifier(name, varName);
40615                         }
40616                     }
40617                 }
40618                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
40619                     // Only object types which are not constructable, or indexable, whose members all come from the
40620                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
40621                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
40622                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
40623                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
40624                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
40625                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
40626                         !!(ts.length(getPropertiesOfType(typeToSerialize)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
40627                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
40628                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
40629                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
40630                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
40631                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
40632                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion) && !ts.isStringAKeyword(ts.symbolName(p)); });
40633                 }
40634                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
40635                     return function serializePropertySymbol(p, isStatic, baseType) {
40636                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
40637                         var isPrivate = !!(modifierFlags & 8 /* Private */);
40638                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
40639                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
40640                             // need to be merged namespace members
40641                             return [];
40642                         }
40643                         if (p.flags & 4194304 /* Prototype */ ||
40644                             (baseType && getPropertyOfType(baseType, p.escapedName)
40645                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
40646                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
40647                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
40648                             return [];
40649                         }
40650                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
40651                         var name = getPropertyNameNodeForSymbol(p, context);
40652                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
40653                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
40654                             var result = [];
40655                             if (p.flags & 65536 /* SetAccessor */) {
40656                                 result.push(ts.setTextRange(ts.createSetAccessor(
40657                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [ts.createParameter(
40658                                     /*decorators*/ undefined, 
40659                                     /*modifiers*/ undefined, 
40660                                     /*dotDotDotToken*/ undefined, "arg", 
40661                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
40662                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
40663                             }
40664                             if (p.flags & 32768 /* GetAccessor */) {
40665                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
40666                                 result.push(ts.setTextRange(ts.createGetAccessor(
40667                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40668                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
40669                             }
40670                             return result;
40671                         }
40672                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
40673                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
40674                         else if (p.flags & (4 /* Property */ | 3 /* Variable */)) {
40675                             return ts.setTextRange(createProperty(
40676                             /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
40677                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
40678                             // interface members can't have initializers, however class members _can_
40679                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
40680                         }
40681                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
40682                             var type = getTypeOfSymbol(p);
40683                             var signatures = getSignaturesOfType(type, 0 /* Call */);
40684                             if (flag & 8 /* Private */) {
40685                                 return ts.setTextRange(createProperty(
40686                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.createToken(57 /* QuestionToken */) : undefined, 
40687                                 /*type*/ undefined, 
40688                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
40689                             }
40690                             var results_1 = [];
40691                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
40692                                 var sig = signatures_3[_i];
40693                                 // Each overload becomes a separate method declaration, in order
40694                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context);
40695                                 decl.name = name; // TODO: Clone
40696                                 if (flag) {
40697                                     decl.modifiers = ts.createNodeArray(ts.createModifiersFromModifierFlags(flag));
40698                                 }
40699                                 if (p.flags & 16777216 /* Optional */) {
40700                                     decl.questionToken = ts.createToken(57 /* QuestionToken */);
40701                                 }
40702                                 results_1.push(ts.setTextRange(decl, sig.declaration));
40703                             }
40704                             return results_1;
40705                         }
40706                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
40707                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
40708                     };
40709                 }
40710                 function serializePropertySymbolForInterface(p, baseType) {
40711                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
40712                 }
40713                 function serializeSignatures(kind, input, baseType, outputKind) {
40714                     var signatures = getSignaturesOfType(input, kind);
40715                     if (kind === 1 /* Construct */) {
40716                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40717                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
40718                         }
40719                         if (baseType) {
40720                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
40721                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
40722                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
40723                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
40724                             }
40725                             if (baseSigs.length === signatures.length) {
40726                                 var failed = false;
40727                                 for (var i = 0; i < baseSigs.length; i++) {
40728                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
40729                                         failed = true;
40730                                         break;
40731                                     }
40732                                 }
40733                                 if (!failed) {
40734                                     return []; // Every signature was identical - elide constructor list as it is inherited
40735                                 }
40736                             }
40737                         }
40738                         var privateProtected = 0;
40739                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
40740                             var s = signatures_4[_i];
40741                             if (s.declaration) {
40742                                 privateProtected |= ts.getSelectedModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
40743                             }
40744                         }
40745                         if (privateProtected) {
40746                             return [ts.setTextRange(ts.createConstructor(
40747                                 /*decorators*/ undefined, ts.createModifiersFromModifierFlags(privateProtected), 
40748                                 /*parameters*/ [], 
40749                                 /*body*/ undefined), signatures[0].declaration)];
40750                         }
40751                     }
40752                     var results = [];
40753                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
40754                         var sig = signatures_5[_a];
40755                         // Each overload becomes a separate constructor declaration, in order
40756                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
40757                         results.push(ts.setTextRange(decl, sig.declaration));
40758                     }
40759                     return results;
40760                 }
40761                 function serializeIndexSignatures(input, baseType) {
40762                     var results = [];
40763                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
40764                         var type = _a[_i];
40765                         var info = getIndexInfoOfType(input, type);
40766                         if (info) {
40767                             if (baseType) {
40768                                 var baseInfo = getIndexInfoOfType(baseType, type);
40769                                 if (baseInfo) {
40770                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
40771                                         continue; // elide identical index signatures
40772                                     }
40773                                 }
40774                             }
40775                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context));
40776                         }
40777                     }
40778                     return results;
40779                 }
40780                 function serializeBaseType(t, staticType, rootName) {
40781                     var ref = trySerializeAsTypeReference(t);
40782                     if (ref) {
40783                         return ref;
40784                     }
40785                     var tempName = getUnusedName(rootName + "_base");
40786                     var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([
40787                         ts.createVariableDeclaration(tempName, typeToTypeNodeHelper(staticType, context))
40788                     ], 2 /* Const */));
40789                     addResult(statement, 0 /* None */);
40790                     return ts.createExpressionWithTypeArguments(/*typeArgs*/ undefined, ts.createIdentifier(tempName));
40791                 }
40792                 function trySerializeAsTypeReference(t) {
40793                     var typeArgs;
40794                     var reference;
40795                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
40796                     // which we can't write out in a syntactically valid way as an expression
40797                     if (t.target && getAccessibleSymbolChain(t.target.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40798                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
40799                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
40800                     }
40801                     else if (t.symbol && getAccessibleSymbolChain(t.symbol, enclosingDeclaration, 111551 /* Value */, /*useOnlyExternalAliasing*/ false)) {
40802                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
40803                     }
40804                     if (reference) {
40805                         return ts.createExpressionWithTypeArguments(typeArgs, reference);
40806                     }
40807                 }
40808                 function getUnusedName(input, symbol) {
40809                     if (symbol) {
40810                         if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40811                             return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40812                         }
40813                     }
40814                     if (symbol) {
40815                         input = getNameCandidateWorker(symbol, input);
40816                     }
40817                     var i = 0;
40818                     var original = input;
40819                     while (context.usedSymbolNames.has(input)) {
40820                         i++;
40821                         input = original + "_" + i;
40822                     }
40823                     context.usedSymbolNames.set(input, true);
40824                     if (symbol) {
40825                         context.remappedSymbolNames.set("" + getSymbolId(symbol), input);
40826                     }
40827                     return input;
40828                 }
40829                 function getNameCandidateWorker(symbol, localName) {
40830                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
40831                         var flags = context.flags;
40832                         context.flags |= 16777216 /* InInitialEntityName */;
40833                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
40834                         context.flags = flags;
40835                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
40836                     }
40837                     if (localName === "default" /* Default */) {
40838                         localName = "_default";
40839                     }
40840                     else if (localName === "export=" /* ExportEquals */) {
40841                         localName = "_exports";
40842                     }
40843                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
40844                     return localName;
40845                 }
40846                 function getInternalSymbolName(symbol, localName) {
40847                     if (context.remappedSymbolNames.has("" + getSymbolId(symbol))) {
40848                         return context.remappedSymbolNames.get("" + getSymbolId(symbol));
40849                     }
40850                     localName = getNameCandidateWorker(symbol, localName);
40851                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
40852                     context.remappedSymbolNames.set("" + getSymbolId(symbol), localName);
40853                     return localName;
40854                 }
40855             }
40856         }
40857         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
40858             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
40859             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
40860             function typePredicateToStringWorker(writer) {
40861                 var predicate = ts.createTypePredicateNodeWithModifier(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.createToken(124 /* AssertsKeyword */) : undefined, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217
40862                 );
40863                 var printer = ts.createPrinter({ removeComments: true });
40864                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
40865                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
40866                 return writer;
40867             }
40868         }
40869         function formatUnionTypes(types) {
40870             var result = [];
40871             var flags = 0;
40872             for (var i = 0; i < types.length; i++) {
40873                 var t = types[i];
40874                 flags |= t.flags;
40875                 if (!(t.flags & 98304 /* Nullable */)) {
40876                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
40877                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
40878                         if (baseType.flags & 1048576 /* Union */) {
40879                             var count = baseType.types.length;
40880                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
40881                                 result.push(baseType);
40882                                 i += count - 1;
40883                                 continue;
40884                             }
40885                         }
40886                     }
40887                     result.push(t);
40888                 }
40889             }
40890             if (flags & 65536 /* Null */)
40891                 result.push(nullType);
40892             if (flags & 32768 /* Undefined */)
40893                 result.push(undefinedType);
40894             return result || types;
40895         }
40896         function visibilityToString(flags) {
40897             if (flags === 8 /* Private */) {
40898                 return "private";
40899             }
40900             if (flags === 16 /* Protected */) {
40901                 return "protected";
40902             }
40903             return "public";
40904         }
40905         function getTypeAliasForTypeLiteral(type) {
40906             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
40907                 var node = ts.findAncestor(type.symbol.declarations[0].parent, function (n) { return n.kind !== 182 /* ParenthesizedType */; });
40908                 if (node.kind === 247 /* TypeAliasDeclaration */) {
40909                     return getSymbolOfNode(node);
40910                 }
40911             }
40912             return undefined;
40913         }
40914         function isTopLevelInExternalModuleAugmentation(node) {
40915             return node && node.parent &&
40916                 node.parent.kind === 250 /* ModuleBlock */ &&
40917                 ts.isExternalModuleAugmentation(node.parent.parent);
40918         }
40919         function isDefaultBindingContext(location) {
40920             return location.kind === 290 /* SourceFile */ || ts.isAmbientModule(location);
40921         }
40922         function getNameOfSymbolFromNameType(symbol, context) {
40923             var nameType = getSymbolLinks(symbol).nameType;
40924             if (nameType) {
40925                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
40926                     var name = "" + nameType.value;
40927                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
40928                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
40929                     }
40930                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
40931                         return "[" + name + "]";
40932                     }
40933                     return name;
40934                 }
40935                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
40936                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
40937                 }
40938             }
40939         }
40940         /**
40941          * Gets a human-readable name for a symbol.
40942          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
40943          *
40944          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
40945          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
40946          */
40947         function getNameOfSymbolAsWritten(symbol, context) {
40948             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
40949                 // If it's not the first part of an entity name, it must print as `default`
40950                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
40951                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
40952                     !symbol.declarations ||
40953                     // if not in the same binding context (source file, module declaration), it must print as `default`
40954                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
40955                 return "default";
40956             }
40957             if (symbol.declarations && symbol.declarations.length) {
40958                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
40959                 var name_2 = declaration && ts.getNameOfDeclaration(declaration);
40960                 if (declaration && name_2) {
40961                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
40962                         return ts.symbolName(symbol);
40963                     }
40964                     if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
40965                         var nameType = getSymbolLinks(symbol).nameType;
40966                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
40967                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
40968                             var result = getNameOfSymbolFromNameType(symbol, context);
40969                             if (result !== undefined) {
40970                                 return result;
40971                             }
40972                         }
40973                     }
40974                     return ts.declarationNameToString(name_2);
40975                 }
40976                 if (!declaration) {
40977                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
40978                 }
40979                 if (declaration.parent && declaration.parent.kind === 242 /* VariableDeclaration */) {
40980                     return ts.declarationNameToString(declaration.parent.name);
40981                 }
40982                 switch (declaration.kind) {
40983                     case 214 /* ClassExpression */:
40984                     case 201 /* FunctionExpression */:
40985                     case 202 /* ArrowFunction */:
40986                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
40987                             context.encounteredError = true;
40988                         }
40989                         return declaration.kind === 214 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
40990                 }
40991             }
40992             var name = getNameOfSymbolFromNameType(symbol, context);
40993             return name !== undefined ? name : ts.symbolName(symbol);
40994         }
40995         function isDeclarationVisible(node) {
40996             if (node) {
40997                 var links = getNodeLinks(node);
40998                 if (links.isVisible === undefined) {
40999                     links.isVisible = !!determineIfDeclarationIsVisible();
41000                 }
41001                 return links.isVisible;
41002             }
41003             return false;
41004             function determineIfDeclarationIsVisible() {
41005                 switch (node.kind) {
41006                     case 315 /* JSDocCallbackTag */:
41007                     case 322 /* JSDocTypedefTag */:
41008                     case 316 /* JSDocEnumTag */:
41009                         // Top-level jsdoc type aliases are considered exported
41010                         // 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
41011                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
41012                     case 191 /* BindingElement */:
41013                         return isDeclarationVisible(node.parent.parent);
41014                     case 242 /* VariableDeclaration */:
41015                         if (ts.isBindingPattern(node.name) &&
41016                             !node.name.elements.length) {
41017                             // If the binding pattern is empty, this variable declaration is not visible
41018                             return false;
41019                         }
41020                     // falls through
41021                     case 249 /* ModuleDeclaration */:
41022                     case 245 /* ClassDeclaration */:
41023                     case 246 /* InterfaceDeclaration */:
41024                     case 247 /* TypeAliasDeclaration */:
41025                     case 244 /* FunctionDeclaration */:
41026                     case 248 /* EnumDeclaration */:
41027                     case 253 /* ImportEqualsDeclaration */:
41028                         // external module augmentation is always visible
41029                         if (ts.isExternalModuleAugmentation(node)) {
41030                             return true;
41031                         }
41032                         var parent = getDeclarationContainer(node);
41033                         // If the node is not exported or it is not ambient module element (except import declaration)
41034                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
41035                             !(node.kind !== 253 /* ImportEqualsDeclaration */ && parent.kind !== 290 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
41036                             return isGlobalSourceFile(parent);
41037                         }
41038                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
41039                         return isDeclarationVisible(parent);
41040                     case 159 /* PropertyDeclaration */:
41041                     case 158 /* PropertySignature */:
41042                     case 163 /* GetAccessor */:
41043                     case 164 /* SetAccessor */:
41044                     case 161 /* MethodDeclaration */:
41045                     case 160 /* MethodSignature */:
41046                         if (ts.hasModifier(node, 8 /* Private */ | 16 /* Protected */)) {
41047                             // Private/protected properties/methods are not visible
41048                             return false;
41049                         }
41050                     // Public properties/methods are visible if its parents are visible, so:
41051                     // falls through
41052                     case 162 /* Constructor */:
41053                     case 166 /* ConstructSignature */:
41054                     case 165 /* CallSignature */:
41055                     case 167 /* IndexSignature */:
41056                     case 156 /* Parameter */:
41057                     case 250 /* ModuleBlock */:
41058                     case 170 /* FunctionType */:
41059                     case 171 /* ConstructorType */:
41060                     case 173 /* TypeLiteral */:
41061                     case 169 /* TypeReference */:
41062                     case 174 /* ArrayType */:
41063                     case 175 /* TupleType */:
41064                     case 178 /* UnionType */:
41065                     case 179 /* IntersectionType */:
41066                     case 182 /* ParenthesizedType */:
41067                         return isDeclarationVisible(node.parent);
41068                     // Default binding, import specifier and namespace import is visible
41069                     // only on demand so by default it is not visible
41070                     case 255 /* ImportClause */:
41071                     case 256 /* NamespaceImport */:
41072                     case 258 /* ImportSpecifier */:
41073                         return false;
41074                     // Type parameters are always visible
41075                     case 155 /* TypeParameter */:
41076                     // Source file and namespace export are always visible
41077                     // falls through
41078                     case 290 /* SourceFile */:
41079                     case 252 /* NamespaceExportDeclaration */:
41080                         return true;
41081                     // Export assignments do not create name bindings outside the module
41082                     case 259 /* ExportAssignment */:
41083                         return false;
41084                     default:
41085                         return false;
41086                 }
41087             }
41088         }
41089         function collectLinkedAliases(node, setVisibility) {
41090             var exportSymbol;
41091             if (node.parent && node.parent.kind === 259 /* ExportAssignment */) {
41092                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
41093             }
41094             else if (node.parent.kind === 263 /* ExportSpecifier */) {
41095                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
41096             }
41097             var result;
41098             var visited;
41099             if (exportSymbol) {
41100                 visited = ts.createMap();
41101                 visited.set("" + getSymbolId(exportSymbol), true);
41102                 buildVisibleNodeList(exportSymbol.declarations);
41103             }
41104             return result;
41105             function buildVisibleNodeList(declarations) {
41106                 ts.forEach(declarations, function (declaration) {
41107                     var resultNode = getAnyImportSyntax(declaration) || declaration;
41108                     if (setVisibility) {
41109                         getNodeLinks(declaration).isVisible = true;
41110                     }
41111                     else {
41112                         result = result || [];
41113                         ts.pushIfUnique(result, resultNode);
41114                     }
41115                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
41116                         // Add the referenced top container visible
41117                         var internalModuleReference = declaration.moduleReference;
41118                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
41119                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
41120                         var id = importSymbol && "" + getSymbolId(importSymbol);
41121                         if (importSymbol && !visited.has(id)) {
41122                             visited.set(id, true);
41123                             buildVisibleNodeList(importSymbol.declarations);
41124                         }
41125                     }
41126                 });
41127             }
41128         }
41129         /**
41130          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
41131          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
41132          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
41133          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
41134          * In order to see if the same query has already been done before, the target object and the propertyName both
41135          * must match the one passed in.
41136          *
41137          * @param target The symbol, type, or signature whose type is being queried
41138          * @param propertyName The property name that should be used to query the target for its type
41139          */
41140         function pushTypeResolution(target, propertyName) {
41141             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
41142             if (resolutionCycleStartIndex >= 0) {
41143                 // A cycle was found
41144                 var length_3 = resolutionTargets.length;
41145                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
41146                     resolutionResults[i] = false;
41147                 }
41148                 return false;
41149             }
41150             resolutionTargets.push(target);
41151             resolutionResults.push(/*items*/ true);
41152             resolutionPropertyNames.push(propertyName);
41153             return true;
41154         }
41155         function findResolutionCycleStartIndex(target, propertyName) {
41156             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
41157                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
41158                     return -1;
41159                 }
41160                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
41161                     return i;
41162                 }
41163             }
41164             return -1;
41165         }
41166         function hasType(target, propertyName) {
41167             switch (propertyName) {
41168                 case 0 /* Type */:
41169                     return !!getSymbolLinks(target).type;
41170                 case 5 /* EnumTagType */:
41171                     return !!(getNodeLinks(target).resolvedEnumType);
41172                 case 2 /* DeclaredType */:
41173                     return !!getSymbolLinks(target).declaredType;
41174                 case 1 /* ResolvedBaseConstructorType */:
41175                     return !!target.resolvedBaseConstructorType;
41176                 case 3 /* ResolvedReturnType */:
41177                     return !!target.resolvedReturnType;
41178                 case 4 /* ImmediateBaseConstraint */:
41179                     return !!target.immediateBaseConstraint;
41180                 case 6 /* ResolvedTypeArguments */:
41181                     return !!target.resolvedTypeArguments;
41182             }
41183             return ts.Debug.assertNever(propertyName);
41184         }
41185         /**
41186          * Pop an entry from the type resolution stack and return its associated result value. The result value will
41187          * be true if no circularities were detected, or false if a circularity was found.
41188          */
41189         function popTypeResolution() {
41190             resolutionTargets.pop();
41191             resolutionPropertyNames.pop();
41192             return resolutionResults.pop();
41193         }
41194         function getDeclarationContainer(node) {
41195             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
41196                 switch (node.kind) {
41197                     case 242 /* VariableDeclaration */:
41198                     case 243 /* VariableDeclarationList */:
41199                     case 258 /* ImportSpecifier */:
41200                     case 257 /* NamedImports */:
41201                     case 256 /* NamespaceImport */:
41202                     case 255 /* ImportClause */:
41203                         return false;
41204                     default:
41205                         return true;
41206                 }
41207             }).parent;
41208         }
41209         function getTypeOfPrototypeProperty(prototype) {
41210             // TypeScript 1.0 spec (April 2014): 8.4
41211             // Every class automatically contains a static property member named 'prototype',
41212             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
41213             // It is an error to explicitly declare a static property member with the name 'prototype'.
41214             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
41215             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
41216         }
41217         // Return the type of the given property in the given type, or undefined if no such property exists
41218         function getTypeOfPropertyOfType(type, name) {
41219             var prop = getPropertyOfType(type, name);
41220             return prop ? getTypeOfSymbol(prop) : undefined;
41221         }
41222         function getTypeOfPropertyOrIndexSignature(type, name) {
41223             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
41224         }
41225         function isTypeAny(type) {
41226             return type && (type.flags & 1 /* Any */) !== 0;
41227         }
41228         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
41229         // assigned by contextual typing.
41230         function getTypeForBindingElementParent(node) {
41231             var symbol = getSymbolOfNode(node);
41232             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
41233         }
41234         function getRestType(source, properties, symbol) {
41235             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
41236             if (source.flags & 131072 /* Never */) {
41237                 return emptyObjectType;
41238             }
41239             if (source.flags & 1048576 /* Union */) {
41240                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
41241             }
41242             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
41243             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
41244                 if (omitKeyType.flags & 131072 /* Never */) {
41245                     return source;
41246                 }
41247                 var omitTypeAlias = getGlobalOmitSymbol();
41248                 if (!omitTypeAlias) {
41249                     return errorType;
41250                 }
41251                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
41252             }
41253             var members = ts.createSymbolTable();
41254             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
41255                 var prop = _a[_i];
41256                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
41257                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
41258                     && isSpreadableProperty(prop)) {
41259                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
41260                 }
41261             }
41262             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
41263             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
41264             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
41265             result.objectFlags |= 131072 /* ObjectRestType */;
41266             return result;
41267         }
41268         // Determine the control flow type associated with a destructuring declaration or assignment. The following
41269         // forms of destructuring are possible:
41270         //   let { x } = obj;  // BindingElement
41271         //   let [ x ] = obj;  // BindingElement
41272         //   { x } = obj;      // ShorthandPropertyAssignment
41273         //   { x: v } = obj;   // PropertyAssignment
41274         //   [ x ] = obj;      // Expression
41275         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
41276         // flow analyzer doesn't have to handle all the different syntactic forms.
41277         function getFlowTypeOfDestructuring(node, declaredType) {
41278             var reference = getSyntheticElementAccess(node);
41279             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
41280         }
41281         function getSyntheticElementAccess(node) {
41282             var parentAccess = getParentElementAccess(node);
41283             if (parentAccess && parentAccess.flowNode) {
41284                 var propName = getDestructuringPropertyName(node);
41285                 if (propName) {
41286                     var result = ts.createNode(195 /* ElementAccessExpression */, node.pos, node.end);
41287                     result.parent = node;
41288                     result.expression = parentAccess;
41289                     var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end);
41290                     literal.parent = result;
41291                     literal.text = propName;
41292                     result.argumentExpression = literal;
41293                     result.flowNode = parentAccess.flowNode;
41294                     return result;
41295                 }
41296             }
41297         }
41298         function getParentElementAccess(node) {
41299             var ancestor = node.parent.parent;
41300             switch (ancestor.kind) {
41301                 case 191 /* BindingElement */:
41302                 case 281 /* PropertyAssignment */:
41303                     return getSyntheticElementAccess(ancestor);
41304                 case 192 /* ArrayLiteralExpression */:
41305                     return getSyntheticElementAccess(node.parent);
41306                 case 242 /* VariableDeclaration */:
41307                     return ancestor.initializer;
41308                 case 209 /* BinaryExpression */:
41309                     return ancestor.right;
41310             }
41311         }
41312         function getDestructuringPropertyName(node) {
41313             var parent = node.parent;
41314             if (node.kind === 191 /* BindingElement */ && parent.kind === 189 /* ObjectBindingPattern */) {
41315                 return getLiteralPropertyNameText(node.propertyName || node.name);
41316             }
41317             if (node.kind === 281 /* PropertyAssignment */ || node.kind === 282 /* ShorthandPropertyAssignment */) {
41318                 return getLiteralPropertyNameText(node.name);
41319             }
41320             return "" + parent.elements.indexOf(node);
41321         }
41322         function getLiteralPropertyNameText(name) {
41323             var type = getLiteralTypeFromPropertyName(name);
41324             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
41325         }
41326         /** Return the inferred type for a binding element */
41327         function getTypeForBindingElement(declaration) {
41328             var pattern = declaration.parent;
41329             var parentType = getTypeForBindingElementParent(pattern.parent);
41330             // If no type or an any type was inferred for parent, infer that for the binding element
41331             if (!parentType || isTypeAny(parentType)) {
41332                 return parentType;
41333             }
41334             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
41335             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
41336                 parentType = getNonNullableType(parentType);
41337             }
41338             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
41339             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
41340                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
41341             }
41342             var type;
41343             if (pattern.kind === 189 /* ObjectBindingPattern */) {
41344                 if (declaration.dotDotDotToken) {
41345                     parentType = getReducedType(parentType);
41346                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
41347                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
41348                         return errorType;
41349                     }
41350                     var literalMembers = [];
41351                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
41352                         var element = _a[_i];
41353                         if (!element.dotDotDotToken) {
41354                             literalMembers.push(element.propertyName || element.name);
41355                         }
41356                     }
41357                     type = getRestType(parentType, literalMembers, declaration.symbol);
41358                 }
41359                 else {
41360                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
41361                     var name = declaration.propertyName || declaration.name;
41362                     var indexType = getLiteralTypeFromPropertyName(name);
41363                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name);
41364                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41365                 }
41366             }
41367             else {
41368                 // This elementType will be used if the specific property corresponding to this index is not
41369                 // present (aka the tuple element property). This call also checks that the parentType is in
41370                 // fact an iterable or array (depending on target language).
41371                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, parentType, undefinedType, pattern);
41372                 var index_1 = pattern.elements.indexOf(declaration);
41373                 if (declaration.dotDotDotToken) {
41374                     // If the parent is a tuple type, the rest element has a tuple type of the
41375                     // remaining tuple element types. Otherwise, the rest element has an array type with same
41376                     // element type as the parent type.
41377                     type = everyType(parentType, isTupleType) ?
41378                         mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) :
41379                         createArrayType(elementType);
41380                 }
41381                 else if (isArrayLikeType(parentType)) {
41382                     var indexType = getLiteralType(index_1);
41383                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
41384                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, declaration.name, accessFlags) || errorType, declaration.name);
41385                     type = getFlowTypeOfDestructuring(declaration, declaredType);
41386                 }
41387                 else {
41388                     type = elementType;
41389                 }
41390             }
41391             if (!declaration.initializer) {
41392                 return type;
41393             }
41394             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
41395                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
41396                 // undefined from the final type.
41397                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
41398                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
41399                     type;
41400             }
41401             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
41402         }
41403         function getTypeForDeclarationFromJSDocComment(declaration) {
41404             var jsdocType = ts.getJSDocType(declaration);
41405             if (jsdocType) {
41406                 return getTypeFromTypeNode(jsdocType);
41407             }
41408             return undefined;
41409         }
41410         function isNullOrUndefined(node) {
41411             var expr = ts.skipParentheses(node);
41412             return expr.kind === 100 /* NullKeyword */ || expr.kind === 75 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
41413         }
41414         function isEmptyArrayLiteral(node) {
41415             var expr = ts.skipParentheses(node);
41416             return expr.kind === 192 /* ArrayLiteralExpression */ && expr.elements.length === 0;
41417         }
41418         function addOptionality(type, optional) {
41419             if (optional === void 0) { optional = true; }
41420             return strictNullChecks && optional ? getOptionalType(type) : type;
41421         }
41422         // Return the inferred type for a variable, parameter, or property declaration
41423         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
41424             // A variable declared in a for..in statement is of type string, or of type keyof T when the
41425             // right hand expression is of a type parameter type.
41426             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 231 /* ForInStatement */) {
41427                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
41428                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
41429             }
41430             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
41431                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
41432                 // missing properties/signatures required to get its iteratedType (like
41433                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
41434                 // or it may have led to an error inside getElementTypeOfIterable.
41435                 var forOfStatement = declaration.parent.parent;
41436                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
41437             }
41438             if (ts.isBindingPattern(declaration.parent)) {
41439                 return getTypeForBindingElement(declaration);
41440             }
41441             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
41442                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
41443             // Use type from type annotation if one is present
41444             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
41445             if (declaredType) {
41446                 return addOptionality(declaredType, isOptional);
41447             }
41448             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
41449                 declaration.kind === 242 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) &&
41450                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
41451                 // If --noImplicitAny is on or the declaration is in a Javascript file,
41452                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
41453                 // initializer or a 'null' or 'undefined' initializer.
41454                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
41455                     return autoType;
41456                 }
41457                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
41458                 // literal initializer.
41459                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
41460                     return autoArrayType;
41461                 }
41462             }
41463             if (declaration.kind === 156 /* Parameter */) {
41464                 var func = declaration.parent;
41465                 // For a parameter of a set accessor, use the type of the get accessor if one is present
41466                 if (func.kind === 164 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
41467                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 163 /* GetAccessor */);
41468                     if (getter) {
41469                         var getterSignature = getSignatureFromDeclaration(getter);
41470                         var thisParameter = getAccessorThisParameter(func);
41471                         if (thisParameter && declaration === thisParameter) {
41472                             // Use the type from the *getter*
41473                             ts.Debug.assert(!thisParameter.type);
41474                             return getTypeOfSymbol(getterSignature.thisParameter);
41475                         }
41476                         return getReturnTypeOfSignature(getterSignature);
41477                     }
41478                 }
41479                 if (ts.isInJSFile(declaration)) {
41480                     var typeTag = ts.getJSDocType(func);
41481                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
41482                         return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration));
41483                     }
41484                 }
41485                 // Use contextual parameter type if one is available
41486                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
41487                 if (type) {
41488                     return addOptionality(type, isOptional);
41489                 }
41490             }
41491             else if (ts.isInJSFile(declaration)) {
41492                 var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
41493                 if (containerObjectType) {
41494                     return containerObjectType;
41495                 }
41496             }
41497             // Use the type of the initializer expression if one is present and the declaration is
41498             // not a parameter of a contextually typed function
41499             if (declaration.initializer) {
41500                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
41501                 return addOptionality(type, isOptional);
41502             }
41503             if (ts.isJsxAttribute(declaration)) {
41504                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
41505                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
41506                 return trueType;
41507             }
41508             // If the declaration specifies a binding pattern and is not a parameter of a contextually
41509             // typed function, use the type implied by the binding pattern
41510             if (ts.isBindingPattern(declaration.name)) {
41511                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
41512             }
41513             // No type specified and nothing can be inferred
41514             return undefined;
41515         }
41516         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
41517             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
41518             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
41519             if (container) {
41520                 var tag = ts.getJSDocTypeTag(container);
41521                 if (tag && tag.typeExpression) {
41522                     return getTypeFromTypeNode(tag.typeExpression);
41523                 }
41524                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
41525                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
41526             }
41527             var definedInConstructor = false;
41528             var definedInMethod = false;
41529             var jsdocType;
41530             var types;
41531             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
41532                 var declaration = _a[_i];
41533                 var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
41534                     ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
41535                         undefined;
41536                 if (!expression) {
41537                     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
41538                 }
41539                 var kind = ts.isAccessExpression(expression)
41540                     ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
41541                     : ts.getAssignmentDeclarationKind(expression);
41542                 if (kind === 4 /* ThisProperty */) {
41543                     if (isDeclarationInConstructor(expression)) {
41544                         definedInConstructor = true;
41545                     }
41546                     else {
41547                         definedInMethod = true;
41548                     }
41549                 }
41550                 if (!ts.isCallExpression(expression)) {
41551                     jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
41552                 }
41553                 if (!jsdocType) {
41554                     (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
41555                 }
41556             }
41557             var type = jsdocType;
41558             if (!type) {
41559                 if (!ts.length(types)) {
41560                     return errorType; // No types from any declarations :(
41561                 }
41562                 var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
41563                 // use only the constructor types unless they were only assigned null | undefined (including widening variants)
41564                 if (definedInMethod) {
41565                     var propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol);
41566                     if (propType) {
41567                         (constructorTypes || (constructorTypes = [])).push(propType);
41568                         definedInConstructor = true;
41569                     }
41570                 }
41571                 var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
41572                 type = getUnionType(sourceTypes, 2 /* Subtype */);
41573             }
41574             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
41575             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
41576                 reportImplicitAny(symbol.valueDeclaration, anyType);
41577                 return anyType;
41578             }
41579             return widened;
41580         }
41581         function getJSContainerObjectType(decl, symbol, init) {
41582             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
41583                 return undefined;
41584             }
41585             var exports = ts.createSymbolTable();
41586             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
41587                 var s_2 = getSymbolOfNode(decl);
41588                 if (s_2 && ts.hasEntries(s_2.exports)) {
41589                     mergeSymbolTable(exports, s_2.exports);
41590                 }
41591                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
41592             }
41593             var s = getSymbolOfNode(decl);
41594             if (s && ts.hasEntries(s.exports)) {
41595                 mergeSymbolTable(exports, s.exports);
41596             }
41597             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
41598             type.objectFlags |= 16384 /* JSLiteral */;
41599             return type;
41600         }
41601         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
41602             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
41603             if (typeNode) {
41604                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
41605                 if (!declaredType) {
41606                     return type;
41607                 }
41608                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
41609                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
41610                 }
41611             }
41612             if (symbol.parent) {
41613                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
41614                 if (typeNode_2) {
41615                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
41616                 }
41617             }
41618             return declaredType;
41619         }
41620         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
41621         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
41622             if (ts.isCallExpression(expression)) {
41623                 if (resolvedSymbol) {
41624                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
41625                 }
41626                 var objectLitType = checkExpressionCached(expression.arguments[2]);
41627                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
41628                 if (valueType) {
41629                     return valueType;
41630                 }
41631                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
41632                 if (getFunc) {
41633                     var getSig = getSingleCallSignature(getFunc);
41634                     if (getSig) {
41635                         return getReturnTypeOfSignature(getSig);
41636                     }
41637                 }
41638                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
41639                 if (setFunc) {
41640                     var setSig = getSingleCallSignature(setFunc);
41641                     if (setSig) {
41642                         return getTypeOfFirstParameterOfSignature(setSig);
41643                     }
41644                 }
41645                 return anyType;
41646             }
41647             if (containsSameNamedThisProperty(expression.left, expression.right)) {
41648                 return anyType;
41649             }
41650             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
41651             if (type.flags & 524288 /* Object */ &&
41652                 kind === 2 /* ModuleExports */ &&
41653                 symbol.escapedName === "export=" /* ExportEquals */) {
41654                 var exportedType = resolveStructuredTypeMembers(type);
41655                 var members_4 = ts.createSymbolTable();
41656                 ts.copyEntries(exportedType.members, members_4);
41657                 if (resolvedSymbol && !resolvedSymbol.exports) {
41658                     resolvedSymbol.exports = ts.createSymbolTable();
41659                 }
41660                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
41661                     var _a;
41662                     var exportedMember = members_4.get(name);
41663                     if (exportedMember && exportedMember !== s) {
41664                         if (s.flags & 111551 /* Value */) {
41665                             // If the member has an additional value-like declaration, union the types from the two declarations,
41666                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
41667                             // a pattern like:
41668                             //
41669                             // module.exports = { a: true };
41670                             // module.exports.a = 3;
41671                             //
41672                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
41673                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
41674                             // it's unclear what that's supposed to mean, so it's probably a mistake.
41675                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
41676                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
41677                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
41678                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41679                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
41680                             }
41681                             var union = createSymbol(s.flags | exportedMember.flags, name);
41682                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
41683                             union.valueDeclaration = exportedMember.valueDeclaration;
41684                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
41685                             members_4.set(name, union);
41686                         }
41687                         else {
41688                             members_4.set(name, mergeSymbol(s, exportedMember));
41689                         }
41690                     }
41691                     else {
41692                         members_4.set(name, s);
41693                     }
41694                 });
41695                 var result = createAnonymousType(exportedType.symbol, members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
41696                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
41697                 return result;
41698             }
41699             if (isEmptyArrayLiteralType(type)) {
41700                 reportImplicitAny(expression, anyArrayType);
41701                 return anyArrayType;
41702             }
41703             return type;
41704         }
41705         function containsSameNamedThisProperty(thisProperty, expression) {
41706             return ts.isPropertyAccessExpression(thisProperty)
41707                 && thisProperty.expression.kind === 104 /* ThisKeyword */
41708                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
41709         }
41710         function isDeclarationInConstructor(expression) {
41711             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
41712             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
41713             // Function expressions that are assigned to the prototype count as methods.
41714             return thisContainer.kind === 162 /* Constructor */ ||
41715                 thisContainer.kind === 244 /* FunctionDeclaration */ ||
41716                 (thisContainer.kind === 201 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
41717         }
41718         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
41719             ts.Debug.assert(types.length === declarations.length);
41720             return types.filter(function (_, i) {
41721                 var declaration = declarations[i];
41722                 var expression = ts.isBinaryExpression(declaration) ? declaration :
41723                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
41724                 return expression && isDeclarationInConstructor(expression);
41725             });
41726         }
41727         /** check for definition in base class if any declaration is in a class */
41728         function getTypeOfAssignmentDeclarationPropertyOfBaseType(property) {
41729             var parentDeclaration = ts.forEach(property.declarations, function (d) {
41730                 var parent = ts.getThisContainer(d, /*includeArrowFunctions*/ false).parent;
41731                 return ts.isClassLike(parent) && parent;
41732             });
41733             if (parentDeclaration) {
41734                 var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration));
41735                 var baseClassType = classType && getBaseTypes(classType)[0];
41736                 if (baseClassType) {
41737                     return getTypeOfPropertyOfType(baseClassType, property.escapedName);
41738                 }
41739             }
41740         }
41741         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
41742         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
41743         // pattern. Otherwise, it is the type any.
41744         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
41745             if (element.initializer) {
41746                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
41747                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
41748                 // pattern.
41749                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
41750                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
41751             }
41752             if (ts.isBindingPattern(element.name)) {
41753                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
41754             }
41755             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
41756                 reportImplicitAny(element, anyType);
41757             }
41758             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
41759             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
41760             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
41761             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
41762             return includePatternInType ? nonInferrableAnyType : anyType;
41763         }
41764         // Return the type implied by an object binding pattern
41765         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
41766             var members = ts.createSymbolTable();
41767             var stringIndexInfo;
41768             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
41769             ts.forEach(pattern.elements, function (e) {
41770                 var name = e.propertyName || e.name;
41771                 if (e.dotDotDotToken) {
41772                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
41773                     return;
41774                 }
41775                 var exprType = getLiteralTypeFromPropertyName(name);
41776                 if (!isTypeUsableAsPropertyName(exprType)) {
41777                     // do not include computed properties in the implied type
41778                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
41779                     return;
41780                 }
41781                 var text = getPropertyNameFromType(exprType);
41782                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
41783                 var symbol = createSymbol(flags, text);
41784                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
41785                 symbol.bindingElement = e;
41786                 members.set(symbol.escapedName, symbol);
41787             });
41788             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
41789             result.objectFlags |= objectFlags;
41790             if (includePatternInType) {
41791                 result.pattern = pattern;
41792                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41793             }
41794             return result;
41795         }
41796         // Return the type implied by an array binding pattern
41797         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
41798             var elements = pattern.elements;
41799             var lastElement = ts.lastOrUndefined(elements);
41800             var hasRestElement = !!(lastElement && lastElement.kind === 191 /* BindingElement */ && lastElement.dotDotDotToken);
41801             if (elements.length === 0 || elements.length === 1 && hasRestElement) {
41802                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
41803             }
41804             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
41805             var minLength = ts.findLastIndex(elements, function (e) { return !ts.isOmittedExpression(e) && !hasDefaultValue(e); }, elements.length - (hasRestElement ? 2 : 1)) + 1;
41806             var result = createTupleType(elementTypes, minLength, hasRestElement);
41807             if (includePatternInType) {
41808                 result = cloneTypeReference(result);
41809                 result.pattern = pattern;
41810                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
41811             }
41812             return result;
41813         }
41814         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
41815         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
41816         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
41817         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
41818         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
41819         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
41820         // the parameter.
41821         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
41822             if (includePatternInType === void 0) { includePatternInType = false; }
41823             if (reportErrors === void 0) { reportErrors = false; }
41824             return pattern.kind === 189 /* ObjectBindingPattern */
41825                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
41826                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
41827         }
41828         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
41829         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
41830         // is a bit more involved. For example:
41831         //
41832         //   var [x, s = ""] = [1, "one"];
41833         //
41834         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
41835         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
41836         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
41837         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
41838             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
41839         }
41840         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
41841             if (type) {
41842                 if (reportErrors) {
41843                     reportErrorsFromWidening(declaration, type);
41844                 }
41845                 // always widen a 'unique symbol' type if the type was created for a different declaration.
41846                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
41847                     type = esSymbolType;
41848                 }
41849                 return getWidenedType(type);
41850             }
41851             // Rest parameters default to type any[], other parameters default to type any
41852             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
41853             // Report implicit any errors unless this is a private property within an ambient declaration
41854             if (reportErrors) {
41855                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
41856                     reportImplicitAny(declaration, type);
41857                 }
41858             }
41859             return type;
41860         }
41861         function declarationBelongsToPrivateAmbientMember(declaration) {
41862             var root = ts.getRootDeclaration(declaration);
41863             var memberDeclaration = root.kind === 156 /* Parameter */ ? root.parent : root;
41864             return isPrivateWithinAmbient(memberDeclaration);
41865         }
41866         function tryGetTypeFromEffectiveTypeNode(declaration) {
41867             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
41868             if (typeNode) {
41869                 return getTypeFromTypeNode(typeNode);
41870             }
41871         }
41872         function getTypeOfVariableOrParameterOrProperty(symbol) {
41873             var links = getSymbolLinks(symbol);
41874             if (!links.type) {
41875                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
41876                 // For a contextually typed parameter it is possible that a type has already
41877                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
41878                 // to preserve this type.
41879                 if (!links.type) {
41880                     links.type = type;
41881                 }
41882             }
41883             return links.type;
41884         }
41885         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
41886             // Handle prototype property
41887             if (symbol.flags & 4194304 /* Prototype */) {
41888                 return getTypeOfPrototypeProperty(symbol);
41889             }
41890             // CommonsJS require and module both have type any.
41891             if (symbol === requireSymbol) {
41892                 return anyType;
41893             }
41894             if (symbol.flags & 134217728 /* ModuleExports */) {
41895                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
41896                 var members = ts.createSymbolTable();
41897                 members.set("exports", fileSymbol);
41898                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
41899             }
41900             // Handle catch clause variables
41901             var declaration = symbol.valueDeclaration;
41902             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
41903                 return anyType;
41904             }
41905             // Handle export default expressions
41906             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
41907                 if (!declaration.statements.length) {
41908                     return emptyObjectType;
41909                 }
41910                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
41911             }
41912             // Handle variable, parameter or property
41913             if (!pushTypeResolution(symbol, 0 /* Type */)) {
41914                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41915                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41916                     return getTypeOfFuncClassEnumModule(symbol);
41917                 }
41918                 return reportCircularityError(symbol);
41919             }
41920             var type;
41921             if (declaration.kind === 259 /* ExportAssignment */) {
41922                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
41923             }
41924             else if (ts.isBinaryExpression(declaration) ||
41925                 (ts.isInJSFile(declaration) &&
41926                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
41927                 type = getWidenedTypeForAssignmentDeclaration(symbol);
41928             }
41929             else if (ts.isJSDocPropertyLikeTag(declaration)
41930                 || ts.isPropertyAccessExpression(declaration)
41931                 || ts.isElementAccessExpression(declaration)
41932                 || ts.isIdentifier(declaration)
41933                 || ts.isStringLiteralLike(declaration)
41934                 || ts.isNumericLiteral(declaration)
41935                 || ts.isClassDeclaration(declaration)
41936                 || ts.isFunctionDeclaration(declaration)
41937                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
41938                 || ts.isMethodSignature(declaration)
41939                 || ts.isSourceFile(declaration)) {
41940                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41941                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
41942                     return getTypeOfFuncClassEnumModule(symbol);
41943                 }
41944                 type = ts.isBinaryExpression(declaration.parent) ?
41945                     getWidenedTypeForAssignmentDeclaration(symbol) :
41946                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
41947             }
41948             else if (ts.isPropertyAssignment(declaration)) {
41949                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
41950             }
41951             else if (ts.isJsxAttribute(declaration)) {
41952                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
41953             }
41954             else if (ts.isShorthandPropertyAssignment(declaration)) {
41955                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
41956             }
41957             else if (ts.isObjectLiteralMethod(declaration)) {
41958                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
41959             }
41960             else if (ts.isParameter(declaration)
41961                 || ts.isPropertyDeclaration(declaration)
41962                 || ts.isPropertySignature(declaration)
41963                 || ts.isVariableDeclaration(declaration)
41964                 || ts.isBindingElement(declaration)) {
41965                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
41966             }
41967             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
41968             // Re-dispatch based on valueDeclaration.kind instead.
41969             else if (ts.isEnumDeclaration(declaration)) {
41970                 type = getTypeOfFuncClassEnumModule(symbol);
41971             }
41972             else if (ts.isEnumMember(declaration)) {
41973                 type = getTypeOfEnumMember(symbol);
41974             }
41975             else if (ts.isAccessor(declaration)) {
41976                 type = resolveTypeOfAccessors(symbol);
41977             }
41978             else {
41979                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
41980             }
41981             if (!popTypeResolution()) {
41982                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
41983                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
41984                     return getTypeOfFuncClassEnumModule(symbol);
41985                 }
41986                 return reportCircularityError(symbol);
41987             }
41988             return type;
41989         }
41990         function getAnnotatedAccessorTypeNode(accessor) {
41991             if (accessor) {
41992                 if (accessor.kind === 163 /* GetAccessor */) {
41993                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
41994                     return getterTypeAnnotation;
41995                 }
41996                 else {
41997                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
41998                     return setterTypeAnnotation;
41999                 }
42000             }
42001             return undefined;
42002         }
42003         function getAnnotatedAccessorType(accessor) {
42004             var node = getAnnotatedAccessorTypeNode(accessor);
42005             return node && getTypeFromTypeNode(node);
42006         }
42007         function getAnnotatedAccessorThisParameter(accessor) {
42008             var parameter = getAccessorThisParameter(accessor);
42009             return parameter && parameter.symbol;
42010         }
42011         function getThisTypeOfDeclaration(declaration) {
42012             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
42013         }
42014         function getTypeOfAccessors(symbol) {
42015             var links = getSymbolLinks(symbol);
42016             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
42017         }
42018         function getTypeOfAccessorsWorker(symbol) {
42019             if (!pushTypeResolution(symbol, 0 /* Type */)) {
42020                 return errorType;
42021             }
42022             var type = resolveTypeOfAccessors(symbol);
42023             if (!popTypeResolution()) {
42024                 type = anyType;
42025                 if (noImplicitAny) {
42026                     var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42027                     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));
42028                 }
42029             }
42030             return type;
42031         }
42032         function resolveTypeOfAccessors(symbol) {
42033             var getter = ts.getDeclarationOfKind(symbol, 163 /* GetAccessor */);
42034             var setter = ts.getDeclarationOfKind(symbol, 164 /* SetAccessor */);
42035             if (getter && ts.isInJSFile(getter)) {
42036                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
42037                 if (jsDocType) {
42038                     return jsDocType;
42039                 }
42040             }
42041             // First try to see if the user specified a return type on the get-accessor.
42042             var getterReturnType = getAnnotatedAccessorType(getter);
42043             if (getterReturnType) {
42044                 return getterReturnType;
42045             }
42046             else {
42047                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
42048                 var setterParameterType = getAnnotatedAccessorType(setter);
42049                 if (setterParameterType) {
42050                     return setterParameterType;
42051                 }
42052                 else {
42053                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
42054                     if (getter && getter.body) {
42055                         return getReturnTypeFromBody(getter);
42056                     }
42057                     // Otherwise, fall back to 'any'.
42058                     else {
42059                         if (setter) {
42060                             if (!isPrivateWithinAmbient(setter)) {
42061                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
42062                             }
42063                         }
42064                         else {
42065                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
42066                             if (!isPrivateWithinAmbient(getter)) {
42067                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
42068                             }
42069                         }
42070                         return anyType;
42071                     }
42072                 }
42073             }
42074         }
42075         function getBaseTypeVariableOfClass(symbol) {
42076             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
42077             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
42078                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
42079                     undefined;
42080         }
42081         function getTypeOfFuncClassEnumModule(symbol) {
42082             var links = getSymbolLinks(symbol);
42083             var originalLinks = links;
42084             if (!links.type) {
42085                 var jsDeclaration = symbol.valueDeclaration && ts.getDeclarationOfExpando(symbol.valueDeclaration);
42086                 if (jsDeclaration) {
42087                     var merged = mergeJSSymbols(symbol, getSymbolOfNode(jsDeclaration));
42088                     if (merged) {
42089                         // note:we overwrite links because we just cloned the symbol
42090                         symbol = links = merged;
42091                     }
42092                 }
42093                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
42094             }
42095             return links.type;
42096         }
42097         function getTypeOfFuncClassEnumModuleWorker(symbol) {
42098             var declaration = symbol.valueDeclaration;
42099             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
42100                 return anyType;
42101             }
42102             else if (declaration && (declaration.kind === 209 /* BinaryExpression */ ||
42103                 ts.isAccessExpression(declaration) &&
42104                     declaration.parent.kind === 209 /* BinaryExpression */)) {
42105                 return getWidenedTypeForAssignmentDeclaration(symbol);
42106             }
42107             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
42108                 var resolvedModule = resolveExternalModuleSymbol(symbol);
42109                 if (resolvedModule !== symbol) {
42110                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
42111                         return errorType;
42112                     }
42113                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
42114                     var type_1 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
42115                     if (!popTypeResolution()) {
42116                         return reportCircularityError(symbol);
42117                     }
42118                     return type_1;
42119                 }
42120             }
42121             var type = createObjectType(16 /* Anonymous */, symbol);
42122             if (symbol.flags & 32 /* Class */) {
42123                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
42124                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
42125             }
42126             else {
42127                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
42128             }
42129         }
42130         function getTypeOfEnumMember(symbol) {
42131             var links = getSymbolLinks(symbol);
42132             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
42133         }
42134         function getTypeOfAlias(symbol) {
42135             var links = getSymbolLinks(symbol);
42136             if (!links.type) {
42137                 var targetSymbol = resolveAlias(symbol);
42138                 // It only makes sense to get the type of a value symbol. If the result of resolving
42139                 // the alias is not a value, then it has no type. To get the type associated with a
42140                 // type symbol, call getDeclaredTypeOfSymbol.
42141                 // This check is important because without it, a call to getTypeOfSymbol could end
42142                 // up recursively calling getTypeOfAlias, causing a stack overflow.
42143                 links.type = targetSymbol.flags & 111551 /* Value */
42144                     ? getTypeOfSymbol(targetSymbol)
42145                     : errorType;
42146             }
42147             return links.type;
42148         }
42149         function getTypeOfInstantiatedSymbol(symbol) {
42150             var links = getSymbolLinks(symbol);
42151             if (!links.type) {
42152                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
42153                     return links.type = errorType;
42154                 }
42155                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
42156                 if (!popTypeResolution()) {
42157                     type = reportCircularityError(symbol);
42158                 }
42159                 links.type = type;
42160             }
42161             return links.type;
42162         }
42163         function reportCircularityError(symbol) {
42164             var declaration = symbol.valueDeclaration;
42165             // Check if variable has type annotation that circularly references the variable itself
42166             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
42167                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
42168                 return errorType;
42169             }
42170             // Check if variable has initializer that circularly references the variable itself
42171             if (noImplicitAny && (declaration.kind !== 156 /* Parameter */ || declaration.initializer)) {
42172                 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));
42173             }
42174             // Circularities could also result from parameters in function expressions that end up
42175             // having themselves as contextual types following type argument inference. In those cases
42176             // we have already reported an implicit any error so we don't report anything here.
42177             return anyType;
42178         }
42179         function getTypeOfSymbolWithDeferredType(symbol) {
42180             var links = getSymbolLinks(symbol);
42181             if (!links.type) {
42182                 ts.Debug.assertIsDefined(links.deferralParent);
42183                 ts.Debug.assertIsDefined(links.deferralConstituents);
42184                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
42185             }
42186             return links.type;
42187         }
42188         function getTypeOfSymbol(symbol) {
42189             var checkFlags = ts.getCheckFlags(symbol);
42190             if (checkFlags & 65536 /* DeferredType */) {
42191                 return getTypeOfSymbolWithDeferredType(symbol);
42192             }
42193             if (checkFlags & 1 /* Instantiated */) {
42194                 return getTypeOfInstantiatedSymbol(symbol);
42195             }
42196             if (checkFlags & 262144 /* Mapped */) {
42197                 return getTypeOfMappedSymbol(symbol);
42198             }
42199             if (checkFlags & 8192 /* ReverseMapped */) {
42200                 return getTypeOfReverseMappedSymbol(symbol);
42201             }
42202             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
42203                 return getTypeOfVariableOrParameterOrProperty(symbol);
42204             }
42205             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
42206                 return getTypeOfFuncClassEnumModule(symbol);
42207             }
42208             if (symbol.flags & 8 /* EnumMember */) {
42209                 return getTypeOfEnumMember(symbol);
42210             }
42211             if (symbol.flags & 98304 /* Accessor */) {
42212                 return getTypeOfAccessors(symbol);
42213             }
42214             if (symbol.flags & 2097152 /* Alias */) {
42215                 return getTypeOfAlias(symbol);
42216             }
42217             return errorType;
42218         }
42219         function isReferenceToType(type, target) {
42220             return type !== undefined
42221                 && target !== undefined
42222                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
42223                 && type.target === target;
42224         }
42225         function getTargetType(type) {
42226             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
42227         }
42228         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
42229         function hasBaseType(type, checkBase) {
42230             return check(type);
42231             function check(type) {
42232                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
42233                     var target = getTargetType(type);
42234                     return target === checkBase || ts.some(getBaseTypes(target), check);
42235                 }
42236                 else if (type.flags & 2097152 /* Intersection */) {
42237                     return ts.some(type.types, check);
42238                 }
42239                 return false;
42240             }
42241         }
42242         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
42243         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
42244         // in-place and returns the same array.
42245         function appendTypeParameters(typeParameters, declarations) {
42246             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
42247                 var declaration = declarations_2[_i];
42248                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
42249             }
42250             return typeParameters;
42251         }
42252         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
42253         function getOuterTypeParameters(node, includeThisTypes) {
42254             while (true) {
42255                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
42256                 if (node && ts.isBinaryExpression(node)) {
42257                     // prototype assignments get the outer type parameters of their constructor function
42258                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42259                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
42260                         var symbol = getSymbolOfNode(node.left);
42261                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
42262                             node = symbol.parent.valueDeclaration;
42263                         }
42264                     }
42265                 }
42266                 if (!node) {
42267                     return undefined;
42268                 }
42269                 switch (node.kind) {
42270                     case 225 /* VariableStatement */:
42271                     case 245 /* ClassDeclaration */:
42272                     case 214 /* ClassExpression */:
42273                     case 246 /* InterfaceDeclaration */:
42274                     case 165 /* CallSignature */:
42275                     case 166 /* ConstructSignature */:
42276                     case 160 /* MethodSignature */:
42277                     case 170 /* FunctionType */:
42278                     case 171 /* ConstructorType */:
42279                     case 300 /* JSDocFunctionType */:
42280                     case 244 /* FunctionDeclaration */:
42281                     case 161 /* MethodDeclaration */:
42282                     case 201 /* FunctionExpression */:
42283                     case 202 /* ArrowFunction */:
42284                     case 247 /* TypeAliasDeclaration */:
42285                     case 321 /* JSDocTemplateTag */:
42286                     case 322 /* JSDocTypedefTag */:
42287                     case 316 /* JSDocEnumTag */:
42288                     case 315 /* JSDocCallbackTag */:
42289                     case 186 /* MappedType */:
42290                     case 180 /* ConditionalType */:
42291                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
42292                         if (node.kind === 186 /* MappedType */) {
42293                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
42294                         }
42295                         else if (node.kind === 180 /* ConditionalType */) {
42296                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
42297                         }
42298                         else if (node.kind === 225 /* VariableStatement */ && !ts.isInJSFile(node)) {
42299                             break;
42300                         }
42301                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
42302                         var thisType = includeThisTypes &&
42303                             (node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */ || node.kind === 246 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
42304                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
42305                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
42306                 }
42307             }
42308         }
42309         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
42310         function getOuterTypeParametersOfClassOrInterface(symbol) {
42311             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
42312             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
42313             return getOuterTypeParameters(declaration);
42314         }
42315         // The local type parameters are the combined set of type parameters from all declarations of the class,
42316         // interface, or type alias.
42317         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
42318             var result;
42319             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42320                 var node = _a[_i];
42321                 if (node.kind === 246 /* InterfaceDeclaration */ ||
42322                     node.kind === 245 /* ClassDeclaration */ ||
42323                     node.kind === 214 /* ClassExpression */ ||
42324                     isJSConstructor(node) ||
42325                     ts.isTypeAlias(node)) {
42326                     var declaration = node;
42327                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
42328                 }
42329             }
42330             return result;
42331         }
42332         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
42333         // its locally declared type parameters.
42334         function getTypeParametersOfClassOrInterface(symbol) {
42335             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
42336         }
42337         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
42338         // rest parameter of type any[].
42339         function isMixinConstructorType(type) {
42340             var signatures = getSignaturesOfType(type, 1 /* Construct */);
42341             if (signatures.length === 1) {
42342                 var s = signatures[0];
42343                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
42344             }
42345             return false;
42346         }
42347         function isConstructorType(type) {
42348             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
42349                 return true;
42350             }
42351             if (type.flags & 8650752 /* TypeVariable */) {
42352                 var constraint = getBaseConstraintOfType(type);
42353                 return !!constraint && isMixinConstructorType(constraint);
42354             }
42355             return false;
42356         }
42357         function getBaseTypeNodeOfClass(type) {
42358             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
42359         }
42360         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42361             var typeArgCount = ts.length(typeArgumentNodes);
42362             var isJavascript = ts.isInJSFile(location);
42363             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
42364         }
42365         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
42366             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
42367             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
42368             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
42369         }
42370         /**
42371          * The base constructor of a class can resolve to
42372          * * undefinedType if the class has no extends clause,
42373          * * unknownType if an error occurred during resolution of the extends expression,
42374          * * nullType if the extends expression is the null value,
42375          * * anyType if the extends expression has type any, or
42376          * * an object type with at least one construct signature.
42377          */
42378         function getBaseConstructorTypeOfClass(type) {
42379             if (!type.resolvedBaseConstructorType) {
42380                 var decl = type.symbol.valueDeclaration;
42381                 var extended = ts.getEffectiveBaseTypeNode(decl);
42382                 var baseTypeNode = getBaseTypeNodeOfClass(type);
42383                 if (!baseTypeNode) {
42384                     return type.resolvedBaseConstructorType = undefinedType;
42385                 }
42386                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
42387                     return errorType;
42388                 }
42389                 var baseConstructorType = checkExpression(baseTypeNode.expression);
42390                 if (extended && baseTypeNode !== extended) {
42391                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
42392                     checkExpression(extended.expression);
42393                 }
42394                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
42395                     // Resolving the members of a class requires us to resolve the base class of that class.
42396                     // We force resolution here such that we catch circularities now.
42397                     resolveStructuredTypeMembers(baseConstructorType);
42398                 }
42399                 if (!popTypeResolution()) {
42400                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
42401                     return type.resolvedBaseConstructorType = errorType;
42402                 }
42403                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
42404                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
42405                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
42406                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
42407                         var ctorReturn = unknownType;
42408                         if (constraint) {
42409                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
42410                             if (ctorSig[0]) {
42411                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
42412                             }
42413                         }
42414                         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)));
42415                     }
42416                     return type.resolvedBaseConstructorType = errorType;
42417                 }
42418                 type.resolvedBaseConstructorType = baseConstructorType;
42419             }
42420             return type.resolvedBaseConstructorType;
42421         }
42422         function getImplementsTypes(type) {
42423             var resolvedImplementsTypes = ts.emptyArray;
42424             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42425                 var declaration = _a[_i];
42426                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
42427                 if (!implementsTypeNodes)
42428                     continue;
42429                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
42430                     var node = implementsTypeNodes_1[_b];
42431                     var implementsType = getTypeFromTypeNode(node);
42432                     if (implementsType !== errorType) {
42433                         if (resolvedImplementsTypes === ts.emptyArray) {
42434                             resolvedImplementsTypes = [implementsType];
42435                         }
42436                         else {
42437                             resolvedImplementsTypes.push(implementsType);
42438                         }
42439                     }
42440                 }
42441             }
42442             return resolvedImplementsTypes;
42443         }
42444         function getBaseTypes(type) {
42445             if (!type.resolvedBaseTypes) {
42446                 if (type.objectFlags & 8 /* Tuple */) {
42447                     type.resolvedBaseTypes = [createArrayType(getUnionType(type.typeParameters || ts.emptyArray), type.readonly)];
42448                 }
42449                 else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42450                     if (type.symbol.flags & 32 /* Class */) {
42451                         resolveBaseTypesOfClass(type);
42452                     }
42453                     if (type.symbol.flags & 64 /* Interface */) {
42454                         resolveBaseTypesOfInterface(type);
42455                     }
42456                 }
42457                 else {
42458                     ts.Debug.fail("type must be class or interface");
42459                 }
42460             }
42461             return type.resolvedBaseTypes;
42462         }
42463         function resolveBaseTypesOfClass(type) {
42464             type.resolvedBaseTypes = ts.resolvingEmptyArray;
42465             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
42466             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
42467                 return type.resolvedBaseTypes = ts.emptyArray;
42468             }
42469             var baseTypeNode = getBaseTypeNodeOfClass(type);
42470             var baseType;
42471             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
42472             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
42473                 areAllOuterTypeParametersApplied(originalBaseType)) {
42474                 // 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
42475                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
42476                 // type arguments in the same manner as a type reference to get the same error reporting experience.
42477                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
42478             }
42479             else if (baseConstructorType.flags & 1 /* Any */) {
42480                 baseType = baseConstructorType;
42481             }
42482             else {
42483                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
42484                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
42485                 // we check that all instantiated signatures return the same type.
42486                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
42487                 if (!constructors.length) {
42488                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
42489                     return type.resolvedBaseTypes = ts.emptyArray;
42490                 }
42491                 baseType = getReturnTypeOfSignature(constructors[0]);
42492             }
42493             if (baseType === errorType) {
42494                 return type.resolvedBaseTypes = ts.emptyArray;
42495             }
42496             var reducedBaseType = getReducedType(baseType);
42497             if (!isValidBaseType(reducedBaseType)) {
42498                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
42499                 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));
42500                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
42501                 return type.resolvedBaseTypes = ts.emptyArray;
42502             }
42503             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
42504                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42505                 return type.resolvedBaseTypes = ts.emptyArray;
42506             }
42507             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
42508                 // Circular reference, likely through instantiation of default parameters
42509                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
42510                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
42511                 // partial instantiation of the members without the base types fully resolved
42512                 type.members = undefined;
42513             }
42514             return type.resolvedBaseTypes = [reducedBaseType];
42515         }
42516         function areAllOuterTypeParametersApplied(type) {
42517             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
42518             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
42519             var outerTypeParameters = type.outerTypeParameters;
42520             if (outerTypeParameters) {
42521                 var last_1 = outerTypeParameters.length - 1;
42522                 var typeArguments = getTypeArguments(type);
42523                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
42524             }
42525             return true;
42526         }
42527         // A valid base type is `any`, an object type or intersection of object types.
42528         function isValidBaseType(type) {
42529             if (type.flags & 262144 /* TypeParameter */) {
42530                 var constraint = getBaseConstraintOfType(type);
42531                 if (constraint) {
42532                     return isValidBaseType(constraint);
42533                 }
42534             }
42535             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
42536             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
42537             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
42538                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
42539         }
42540         function resolveBaseTypesOfInterface(type) {
42541             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
42542             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
42543                 var declaration = _a[_i];
42544                 if (declaration.kind === 246 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
42545                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
42546                         var node = _c[_b];
42547                         var baseType = getReducedType(getTypeFromTypeNode(node));
42548                         if (baseType !== errorType) {
42549                             if (isValidBaseType(baseType)) {
42550                                 if (type !== baseType && !hasBaseType(baseType, type)) {
42551                                     if (type.resolvedBaseTypes === ts.emptyArray) {
42552                                         type.resolvedBaseTypes = [baseType];
42553                                     }
42554                                     else {
42555                                         type.resolvedBaseTypes.push(baseType);
42556                                     }
42557                                 }
42558                                 else {
42559                                     error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
42560                                 }
42561                             }
42562                             else {
42563                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
42564                             }
42565                         }
42566                     }
42567                 }
42568             }
42569         }
42570         /**
42571          * Returns true if the interface given by the symbol is free of "this" references.
42572          *
42573          * Specifically, the result is true if the interface itself contains no references
42574          * to "this" in its body, if all base types are interfaces,
42575          * and if none of the base interfaces have a "this" type.
42576          */
42577         function isThislessInterface(symbol) {
42578             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42579                 var declaration = _a[_i];
42580                 if (declaration.kind === 246 /* InterfaceDeclaration */) {
42581                     if (declaration.flags & 128 /* ContainsThis */) {
42582                         return false;
42583                     }
42584                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
42585                     if (baseTypeNodes) {
42586                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
42587                             var node = baseTypeNodes_1[_b];
42588                             if (ts.isEntityNameExpression(node.expression)) {
42589                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
42590                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
42591                                     return false;
42592                                 }
42593                             }
42594                         }
42595                     }
42596                 }
42597             }
42598             return true;
42599         }
42600         function getDeclaredTypeOfClassOrInterface(symbol) {
42601             var links = getSymbolLinks(symbol);
42602             var originalLinks = links;
42603             if (!links.declaredType) {
42604                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
42605                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
42606                 if (merged) {
42607                     // note:we overwrite links because we just cloned the symbol
42608                     symbol = links = merged;
42609                 }
42610                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
42611                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
42612                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42613                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
42614                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
42615                 // property types inferred from initializers and method return types inferred from return statements are very hard
42616                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
42617                 // "this" references.
42618                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
42619                     type.objectFlags |= 4 /* Reference */;
42620                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
42621                     type.outerTypeParameters = outerTypeParameters;
42622                     type.localTypeParameters = localTypeParameters;
42623                     type.instantiations = ts.createMap();
42624                     type.instantiations.set(getTypeListId(type.typeParameters), type);
42625                     type.target = type;
42626                     type.resolvedTypeArguments = type.typeParameters;
42627                     type.thisType = createTypeParameter(symbol);
42628                     type.thisType.isThisType = true;
42629                     type.thisType.constraint = type;
42630                 }
42631             }
42632             return links.declaredType;
42633         }
42634         function getDeclaredTypeOfTypeAlias(symbol) {
42635             var links = getSymbolLinks(symbol);
42636             if (!links.declaredType) {
42637                 // Note that we use the links object as the target here because the symbol object is used as the unique
42638                 // identity for resolution of the 'type' property in SymbolLinks.
42639                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
42640                     return errorType;
42641                 }
42642                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
42643                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
42644                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
42645                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
42646                 if (popTypeResolution()) {
42647                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
42648                     if (typeParameters) {
42649                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
42650                         // an instantiation of the type alias with the type parameters supplied as type arguments.
42651                         links.typeParameters = typeParameters;
42652                         links.instantiations = ts.createMap();
42653                         links.instantiations.set(getTypeListId(typeParameters), type);
42654                     }
42655                 }
42656                 else {
42657                     type = errorType;
42658                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
42659                 }
42660                 links.declaredType = type;
42661             }
42662             return links.declaredType;
42663         }
42664         function isStringConcatExpression(expr) {
42665             if (ts.isStringLiteralLike(expr)) {
42666                 return true;
42667             }
42668             else if (expr.kind === 209 /* BinaryExpression */) {
42669                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
42670             }
42671             return false;
42672         }
42673         function isLiteralEnumMember(member) {
42674             var expr = member.initializer;
42675             if (!expr) {
42676                 return !(member.flags & 8388608 /* Ambient */);
42677             }
42678             switch (expr.kind) {
42679                 case 10 /* StringLiteral */:
42680                 case 8 /* NumericLiteral */:
42681                 case 14 /* NoSubstitutionTemplateLiteral */:
42682                     return true;
42683                 case 207 /* PrefixUnaryExpression */:
42684                     return expr.operator === 40 /* MinusToken */ &&
42685                         expr.operand.kind === 8 /* NumericLiteral */;
42686                 case 75 /* Identifier */:
42687                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
42688                 case 209 /* BinaryExpression */:
42689                     return isStringConcatExpression(expr);
42690                 default:
42691                     return false;
42692             }
42693         }
42694         function getEnumKind(symbol) {
42695             var links = getSymbolLinks(symbol);
42696             if (links.enumKind !== undefined) {
42697                 return links.enumKind;
42698             }
42699             var hasNonLiteralMember = false;
42700             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42701                 var declaration = _a[_i];
42702                 if (declaration.kind === 248 /* EnumDeclaration */) {
42703                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42704                         var member = _c[_b];
42705                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
42706                             return links.enumKind = 1 /* Literal */;
42707                         }
42708                         if (!isLiteralEnumMember(member)) {
42709                             hasNonLiteralMember = true;
42710                         }
42711                     }
42712                 }
42713             }
42714             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
42715         }
42716         function getBaseTypeOfEnumLiteralType(type) {
42717             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
42718         }
42719         function getDeclaredTypeOfEnum(symbol) {
42720             var links = getSymbolLinks(symbol);
42721             if (links.declaredType) {
42722                 return links.declaredType;
42723             }
42724             if (getEnumKind(symbol) === 1 /* Literal */) {
42725                 enumCount++;
42726                 var memberTypeList = [];
42727                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
42728                     var declaration = _a[_i];
42729                     if (declaration.kind === 248 /* EnumDeclaration */) {
42730                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
42731                             var member = _c[_b];
42732                             var value = getEnumMemberValue(member);
42733                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
42734                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
42735                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
42736                         }
42737                     }
42738                 }
42739                 if (memberTypeList.length) {
42740                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
42741                     if (enumType_1.flags & 1048576 /* Union */) {
42742                         enumType_1.flags |= 1024 /* EnumLiteral */;
42743                         enumType_1.symbol = symbol;
42744                     }
42745                     return links.declaredType = enumType_1;
42746                 }
42747             }
42748             var enumType = createType(32 /* Enum */);
42749             enumType.symbol = symbol;
42750             return links.declaredType = enumType;
42751         }
42752         function getDeclaredTypeOfEnumMember(symbol) {
42753             var links = getSymbolLinks(symbol);
42754             if (!links.declaredType) {
42755                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
42756                 if (!links.declaredType) {
42757                     links.declaredType = enumType;
42758                 }
42759             }
42760             return links.declaredType;
42761         }
42762         function getDeclaredTypeOfTypeParameter(symbol) {
42763             var links = getSymbolLinks(symbol);
42764             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
42765         }
42766         function getDeclaredTypeOfAlias(symbol) {
42767             var links = getSymbolLinks(symbol);
42768             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
42769         }
42770         function getDeclaredTypeOfSymbol(symbol) {
42771             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
42772         }
42773         function tryGetDeclaredTypeOfSymbol(symbol) {
42774             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
42775                 return getDeclaredTypeOfClassOrInterface(symbol);
42776             }
42777             if (symbol.flags & 524288 /* TypeAlias */) {
42778                 return getDeclaredTypeOfTypeAlias(symbol);
42779             }
42780             if (symbol.flags & 262144 /* TypeParameter */) {
42781                 return getDeclaredTypeOfTypeParameter(symbol);
42782             }
42783             if (symbol.flags & 384 /* Enum */) {
42784                 return getDeclaredTypeOfEnum(symbol);
42785             }
42786             if (symbol.flags & 8 /* EnumMember */) {
42787                 return getDeclaredTypeOfEnumMember(symbol);
42788             }
42789             if (symbol.flags & 2097152 /* Alias */) {
42790                 return getDeclaredTypeOfAlias(symbol);
42791             }
42792             return undefined;
42793         }
42794         /**
42795          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
42796          * literal type, an array with an element type that is free of this references, or a type reference that is
42797          * free of this references.
42798          */
42799         function isThislessType(node) {
42800             switch (node.kind) {
42801                 case 125 /* AnyKeyword */:
42802                 case 148 /* UnknownKeyword */:
42803                 case 143 /* StringKeyword */:
42804                 case 140 /* NumberKeyword */:
42805                 case 151 /* BigIntKeyword */:
42806                 case 128 /* BooleanKeyword */:
42807                 case 144 /* SymbolKeyword */:
42808                 case 141 /* ObjectKeyword */:
42809                 case 110 /* VoidKeyword */:
42810                 case 146 /* UndefinedKeyword */:
42811                 case 100 /* NullKeyword */:
42812                 case 137 /* NeverKeyword */:
42813                 case 187 /* LiteralType */:
42814                     return true;
42815                 case 174 /* ArrayType */:
42816                     return isThislessType(node.elementType);
42817                 case 169 /* TypeReference */:
42818                     return !node.typeArguments || node.typeArguments.every(isThislessType);
42819             }
42820             return false;
42821         }
42822         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
42823         function isThislessTypeParameter(node) {
42824             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
42825             return !constraint || isThislessType(constraint);
42826         }
42827         /**
42828          * A variable-like declaration is free of this references if it has a type annotation
42829          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
42830          */
42831         function isThislessVariableLikeDeclaration(node) {
42832             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
42833             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
42834         }
42835         /**
42836          * A function-like declaration is considered free of `this` references if it has a return type
42837          * annotation that is free of this references and if each parameter is thisless and if
42838          * each type parameter (if present) is thisless.
42839          */
42840         function isThislessFunctionLikeDeclaration(node) {
42841             var returnType = ts.getEffectiveReturnTypeNode(node);
42842             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
42843             return (node.kind === 162 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
42844                 node.parameters.every(isThislessVariableLikeDeclaration) &&
42845                 typeParameters.every(isThislessTypeParameter);
42846         }
42847         /**
42848          * Returns true if the class or interface member given by the symbol is free of "this" references. The
42849          * function may return false for symbols that are actually free of "this" references because it is not
42850          * feasible to perform a complete analysis in all cases. In particular, property members with types
42851          * inferred from their initializers and function members with inferred return types are conservatively
42852          * assumed not to be free of "this" references.
42853          */
42854         function isThisless(symbol) {
42855             if (symbol.declarations && symbol.declarations.length === 1) {
42856                 var declaration = symbol.declarations[0];
42857                 if (declaration) {
42858                     switch (declaration.kind) {
42859                         case 159 /* PropertyDeclaration */:
42860                         case 158 /* PropertySignature */:
42861                             return isThislessVariableLikeDeclaration(declaration);
42862                         case 161 /* MethodDeclaration */:
42863                         case 160 /* MethodSignature */:
42864                         case 162 /* Constructor */:
42865                         case 163 /* GetAccessor */:
42866                         case 164 /* SetAccessor */:
42867                             return isThislessFunctionLikeDeclaration(declaration);
42868                     }
42869                 }
42870             }
42871             return false;
42872         }
42873         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
42874         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
42875         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
42876             var result = ts.createSymbolTable();
42877             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
42878                 var symbol = symbols_2[_i];
42879                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
42880             }
42881             return result;
42882         }
42883         function addInheritedMembers(symbols, baseSymbols) {
42884             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
42885                 var s = baseSymbols_1[_i];
42886                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
42887                     symbols.set(s.escapedName, s);
42888                 }
42889             }
42890         }
42891         function isStaticPrivateIdentifierProperty(s) {
42892             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasModifier(s.valueDeclaration, 32 /* Static */);
42893         }
42894         function resolveDeclaredMembers(type) {
42895             if (!type.declaredProperties) {
42896                 var symbol = type.symbol;
42897                 var members = getMembersOfSymbol(symbol);
42898                 type.declaredProperties = getNamedMembers(members);
42899                 // Start with signatures at empty array in case of recursive types
42900                 type.declaredCallSignatures = ts.emptyArray;
42901                 type.declaredConstructSignatures = ts.emptyArray;
42902                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
42903                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
42904                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
42905                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
42906             }
42907             return type;
42908         }
42909         /**
42910          * Indicates whether a type can be used as a property name.
42911          */
42912         function isTypeUsableAsPropertyName(type) {
42913             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
42914         }
42915         /**
42916          * Indicates whether a declaration name is definitely late-bindable.
42917          * A declaration name is only late-bindable if:
42918          * - It is a `ComputedPropertyName`.
42919          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
42920          * `ElementAccessExpression` consisting only of these same three types of nodes.
42921          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
42922          */
42923         function isLateBindableName(node) {
42924             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
42925                 return false;
42926             }
42927             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
42928             return ts.isEntityNameExpression(expr)
42929                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
42930         }
42931         function isLateBoundName(name) {
42932             return name.charCodeAt(0) === 95 /* _ */ &&
42933                 name.charCodeAt(1) === 95 /* _ */ &&
42934                 name.charCodeAt(2) === 64 /* at */;
42935         }
42936         /**
42937          * Indicates whether a declaration has a late-bindable dynamic name.
42938          */
42939         function hasLateBindableName(node) {
42940             var name = ts.getNameOfDeclaration(node);
42941             return !!name && isLateBindableName(name);
42942         }
42943         /**
42944          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
42945          */
42946         function hasNonBindableDynamicName(node) {
42947             return ts.hasDynamicName(node) && !hasLateBindableName(node);
42948         }
42949         /**
42950          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
42951          */
42952         function isNonBindableDynamicName(node) {
42953             return ts.isDynamicName(node) && !isLateBindableName(node);
42954         }
42955         /**
42956          * Gets the symbolic name for a member from its type.
42957          */
42958         function getPropertyNameFromType(type) {
42959             if (type.flags & 8192 /* UniqueESSymbol */) {
42960                 return type.escapedName;
42961             }
42962             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
42963                 return ts.escapeLeadingUnderscores("" + type.value);
42964             }
42965             return ts.Debug.fail();
42966         }
42967         /**
42968          * Adds a declaration to a late-bound dynamic member. This performs the same function for
42969          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
42970          * members.
42971          */
42972         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
42973             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
42974             symbol.flags |= symbolFlags;
42975             getSymbolLinks(member.symbol).lateSymbol = symbol;
42976             if (!symbol.declarations) {
42977                 symbol.declarations = [member];
42978             }
42979             else {
42980                 symbol.declarations.push(member);
42981             }
42982             if (symbolFlags & 111551 /* Value */) {
42983                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
42984                     symbol.valueDeclaration = member;
42985                 }
42986             }
42987         }
42988         /**
42989          * Performs late-binding of a dynamic member. This performs the same function for
42990          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
42991          * members.
42992          *
42993          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
42994          * binding phase to attempt to resolve the name for the symbol from the type of the computed
42995          * property's expression. If the type of the expression is a string-literal, numeric-literal,
42996          * or unique symbol type, we can use that type as the name of the symbol.
42997          *
42998          * For example, given:
42999          *
43000          *   const x = Symbol();
43001          *
43002          *   interface I {
43003          *     [x]: number;
43004          *   }
43005          *
43006          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
43007          * In the late-binding phase we can type-check the expression `x` and see that it has a
43008          * unique symbol type which we can then use as the name of the member. This allows users
43009          * to define custom symbols that can be used in the members of an object type.
43010          *
43011          * @param parent The containing symbol for the member.
43012          * @param earlySymbols The early-bound symbols of the parent.
43013          * @param lateSymbols The late-bound symbols of the parent.
43014          * @param decl The member to bind.
43015          */
43016         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
43017             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
43018             var links = getNodeLinks(decl);
43019             if (!links.resolvedSymbol) {
43020                 // In the event we attempt to resolve the late-bound name of this member recursively,
43021                 // fall back to the early-bound name of this member.
43022                 links.resolvedSymbol = decl.symbol;
43023                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
43024                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
43025                 if (isTypeUsableAsPropertyName(type)) {
43026                     var memberName = getPropertyNameFromType(type);
43027                     var symbolFlags = decl.symbol.flags;
43028                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
43029                     var lateSymbol = lateSymbols.get(memberName);
43030                     if (!lateSymbol)
43031                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
43032                     // Report an error if a late-bound member has the same name as an early-bound member,
43033                     // or if we have another early-bound symbol declaration with the same name and
43034                     // conflicting flags.
43035                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
43036                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
43037                         // If we have an existing early-bound member, combine its declarations so that we can
43038                         // report an error at each declaration.
43039                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
43040                         var name_3 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
43041                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_3); });
43042                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_3);
43043                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
43044                     }
43045                     lateSymbol.nameType = type;
43046                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
43047                     if (lateSymbol.parent) {
43048                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
43049                     }
43050                     else {
43051                         lateSymbol.parent = parent;
43052                     }
43053                     return links.resolvedSymbol = lateSymbol;
43054                 }
43055             }
43056             return links.resolvedSymbol;
43057         }
43058         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
43059             var links = getSymbolLinks(symbol);
43060             if (!links[resolutionKind]) {
43061                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
43062                 var earlySymbols = !isStatic ? symbol.members :
43063                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
43064                         symbol.exports;
43065                 // In the event we recursively resolve the members/exports of the symbol, we
43066                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
43067                 // members/exports of the symbol.
43068                 links[resolutionKind] = earlySymbols || emptySymbols;
43069                 // fill in any as-yet-unresolved late-bound members.
43070                 var lateSymbols = ts.createSymbolTable();
43071                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
43072                     var decl = _a[_i];
43073                     var members = ts.getMembersOfDeclaration(decl);
43074                     if (members) {
43075                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
43076                             var member = members_5[_b];
43077                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
43078                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
43079                             }
43080                         }
43081                     }
43082                 }
43083                 var assignments = symbol.assignmentDeclarationMembers;
43084                 if (assignments) {
43085                     var decls = ts.arrayFrom(assignments.values());
43086                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
43087                         var member = decls_1[_c];
43088                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
43089                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
43090                             || assignmentKind === 4 /* ThisProperty */
43091                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
43092                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
43093                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
43094                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
43095                         }
43096                     }
43097                 }
43098                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
43099             }
43100             return links[resolutionKind];
43101         }
43102         /**
43103          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
43104          *
43105          * For a description of late-binding, see `lateBindMember`.
43106          */
43107         function getMembersOfSymbol(symbol) {
43108             return symbol.flags & 6256 /* LateBindingContainer */
43109                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
43110                 : symbol.members || emptySymbols;
43111         }
43112         /**
43113          * If a symbol is the dynamic name of the member of an object type, get the late-bound
43114          * symbol of the member.
43115          *
43116          * For a description of late-binding, see `lateBindMember`.
43117          */
43118         function getLateBoundSymbol(symbol) {
43119             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
43120                 var links = getSymbolLinks(symbol);
43121                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
43122                     // force late binding of members/exports. This will set the late-bound symbol
43123                     var parent = getMergedSymbol(symbol.parent);
43124                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
43125                         getExportsOfSymbol(parent);
43126                     }
43127                     else {
43128                         getMembersOfSymbol(parent);
43129                     }
43130                 }
43131                 return links.lateSymbol || (links.lateSymbol = symbol);
43132             }
43133             return symbol;
43134         }
43135         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
43136             if (ts.getObjectFlags(type) & 4 /* Reference */) {
43137                 var target = type.target;
43138                 var typeArguments = getTypeArguments(type);
43139                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
43140                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
43141                     return needApparentType ? getApparentType(ref) : ref;
43142                 }
43143             }
43144             else if (type.flags & 2097152 /* Intersection */) {
43145                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
43146             }
43147             return needApparentType ? getApparentType(type) : type;
43148         }
43149         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
43150             var mapper;
43151             var members;
43152             var callSignatures;
43153             var constructSignatures;
43154             var stringIndexInfo;
43155             var numberIndexInfo;
43156             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
43157                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
43158                 callSignatures = source.declaredCallSignatures;
43159                 constructSignatures = source.declaredConstructSignatures;
43160                 stringIndexInfo = source.declaredStringIndexInfo;
43161                 numberIndexInfo = source.declaredNumberIndexInfo;
43162             }
43163             else {
43164                 mapper = createTypeMapper(typeParameters, typeArguments);
43165                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
43166                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
43167                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
43168                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
43169                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
43170             }
43171             var baseTypes = getBaseTypes(source);
43172             if (baseTypes.length) {
43173                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
43174                     members = ts.createSymbolTable(source.declaredProperties);
43175                 }
43176                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43177                 var thisArgument = ts.lastOrUndefined(typeArguments);
43178                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
43179                     var baseType = baseTypes_1[_i];
43180                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
43181                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
43182                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
43183                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
43184                     if (!stringIndexInfo) {
43185                         stringIndexInfo = instantiatedBaseType === anyType ?
43186                             createIndexInfo(anyType, /*isReadonly*/ false) :
43187                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
43188                     }
43189                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
43190                 }
43191             }
43192             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43193         }
43194         function resolveClassOrInterfaceMembers(type) {
43195             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
43196         }
43197         function resolveTypeReferenceMembers(type) {
43198             var source = resolveDeclaredMembers(type.target);
43199             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
43200             var typeArguments = getTypeArguments(type);
43201             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
43202             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
43203         }
43204         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
43205             var sig = new Signature(checker, flags);
43206             sig.declaration = declaration;
43207             sig.typeParameters = typeParameters;
43208             sig.parameters = parameters;
43209             sig.thisParameter = thisParameter;
43210             sig.resolvedReturnType = resolvedReturnType;
43211             sig.resolvedTypePredicate = resolvedTypePredicate;
43212             sig.minArgumentCount = minArgumentCount;
43213             sig.target = undefined;
43214             sig.mapper = undefined;
43215             sig.unionSignatures = undefined;
43216             return sig;
43217         }
43218         function cloneSignature(sig) {
43219             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
43220             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */);
43221             result.target = sig.target;
43222             result.mapper = sig.mapper;
43223             result.unionSignatures = sig.unionSignatures;
43224             return result;
43225         }
43226         function createUnionSignature(signature, unionSignatures) {
43227             var result = cloneSignature(signature);
43228             result.unionSignatures = unionSignatures;
43229             result.target = undefined;
43230             result.mapper = undefined;
43231             return result;
43232         }
43233         function getOptionalCallSignature(signature, callChainFlags) {
43234             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
43235                 return signature;
43236             }
43237             if (!signature.optionalCallSignatureCache) {
43238                 signature.optionalCallSignatureCache = {};
43239             }
43240             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
43241             return signature.optionalCallSignatureCache[key]
43242                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
43243         }
43244         function createOptionalCallSignature(signature, callChainFlags) {
43245             ts.Debug.assert(callChainFlags === 4 /* IsInnerCallChain */ || callChainFlags === 8 /* IsOuterCallChain */, "An optional call signature can either be for an inner call chain or an outer call chain, but not both.");
43246             var result = cloneSignature(signature);
43247             result.flags |= callChainFlags;
43248             return result;
43249         }
43250         function getExpandedParameters(sig) {
43251             if (signatureHasRestParameter(sig)) {
43252                 var restIndex_1 = sig.parameters.length - 1;
43253                 var restParameter = sig.parameters[restIndex_1];
43254                 var restType = getTypeOfSymbol(restParameter);
43255                 if (isTupleType(restType)) {
43256                     var elementTypes = getTypeArguments(restType);
43257                     var minLength_1 = restType.target.minLength;
43258                     var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1;
43259                     var restParams = ts.map(elementTypes, function (t, i) {
43260                         var name = getParameterNameAtPosition(sig, restIndex_1 + i);
43261                         var checkFlags = i === tupleRestIndex_1 ? 32768 /* RestParameter */ :
43262                             i >= minLength_1 ? 16384 /* OptionalParameter */ : 0;
43263                         var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
43264                         symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t;
43265                         return symbol;
43266                     });
43267                     return ts.concatenate(sig.parameters.slice(0, restIndex_1), restParams);
43268                 }
43269             }
43270             return sig.parameters;
43271         }
43272         function getDefaultConstructSignatures(classType) {
43273             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43274             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
43275             if (baseSignatures.length === 0) {
43276                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
43277             }
43278             var baseTypeNode = getBaseTypeNodeOfClass(classType);
43279             var isJavaScript = ts.isInJSFile(baseTypeNode);
43280             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
43281             var typeArgCount = ts.length(typeArguments);
43282             var result = [];
43283             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
43284                 var baseSig = baseSignatures_1[_i];
43285                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
43286                 var typeParamCount = ts.length(baseSig.typeParameters);
43287                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
43288                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
43289                     sig.typeParameters = classType.localTypeParameters;
43290                     sig.resolvedReturnType = classType;
43291                     result.push(sig);
43292                 }
43293             }
43294             return result;
43295         }
43296         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
43297             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
43298                 var s = signatureList_1[_i];
43299                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
43300                     return s;
43301                 }
43302             }
43303         }
43304         function findMatchingSignatures(signatureLists, signature, listIndex) {
43305             if (signature.typeParameters) {
43306                 // We require an exact match for generic signatures, so we only return signatures from the first
43307                 // signature list and only if they have exact matches in the other signature lists.
43308                 if (listIndex > 0) {
43309                     return undefined;
43310                 }
43311                 for (var i = 1; i < signatureLists.length; i++) {
43312                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
43313                         return undefined;
43314                     }
43315                 }
43316                 return [signature];
43317             }
43318             var result;
43319             for (var i = 0; i < signatureLists.length; i++) {
43320                 // Allow matching non-generic signatures to have excess parameters and different return types.
43321                 // Prefer matching this types if possible.
43322                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
43323                 if (!match) {
43324                     return undefined;
43325                 }
43326                 result = ts.appendIfUnique(result, match);
43327             }
43328             return result;
43329         }
43330         // The signatures of a union type are those signatures that are present in each of the constituent types.
43331         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
43332         // parameters and may differ in return types. When signatures differ in return types, the resulting return
43333         // type is the union of the constituent return types.
43334         function getUnionSignatures(signatureLists) {
43335             var result;
43336             var indexWithLengthOverOne;
43337             for (var i = 0; i < signatureLists.length; i++) {
43338                 if (signatureLists[i].length === 0)
43339                     return ts.emptyArray;
43340                 if (signatureLists[i].length > 1) {
43341                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
43342                 }
43343                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
43344                     var signature = _a[_i];
43345                     // Only process signatures with parameter lists that aren't already in the result list
43346                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
43347                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
43348                         if (unionSignatures) {
43349                             var s = signature;
43350                             // Union the result types when more than one signature matches
43351                             if (unionSignatures.length > 1) {
43352                                 var thisParameter = signature.thisParameter;
43353                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
43354                                 if (firstThisParameterOfUnionSignatures) {
43355                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
43356                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
43357                                 }
43358                                 s = createUnionSignature(signature, unionSignatures);
43359                                 s.thisParameter = thisParameter;
43360                             }
43361                             (result || (result = [])).push(s);
43362                         }
43363                     }
43364                 }
43365             }
43366             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
43367                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
43368                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
43369                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
43370                 // signatures from the type, whose ordering would be non-obvious)
43371                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
43372                 var results = masterList.slice();
43373                 var _loop_9 = function (signatures) {
43374                     if (signatures !== masterList) {
43375                         var signature_1 = signatures[0];
43376                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
43377                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
43378                         if (!results) {
43379                             return "break";
43380                         }
43381                     }
43382                 };
43383                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
43384                     var signatures = signatureLists_1[_b];
43385                     var state_3 = _loop_9(signatures);
43386                     if (state_3 === "break")
43387                         break;
43388                 }
43389                 result = results;
43390             }
43391             return result || ts.emptyArray;
43392         }
43393         function combineUnionThisParam(left, right) {
43394             if (!left || !right) {
43395                 return left || right;
43396             }
43397             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
43398             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
43399             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
43400             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
43401             return createSymbolWithType(left, thisType);
43402         }
43403         function combineUnionParameters(left, right) {
43404             var leftCount = getParameterCount(left);
43405             var rightCount = getParameterCount(right);
43406             var longest = leftCount >= rightCount ? left : right;
43407             var shorter = longest === left ? right : left;
43408             var longestCount = longest === left ? leftCount : rightCount;
43409             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
43410             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
43411             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
43412             for (var i = 0; i < longestCount; i++) {
43413                 var longestParamType = tryGetTypeAtPosition(longest, i);
43414                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
43415                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
43416                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
43417                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
43418                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
43419                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
43420                 var paramName = leftName === rightName ? leftName :
43421                     !leftName ? rightName :
43422                         !rightName ? leftName :
43423                             undefined;
43424                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
43425                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
43426                 params[i] = paramSymbol;
43427             }
43428             if (needsExtraRestElement) {
43429                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
43430                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
43431                 params[longestCount] = restParamSymbol;
43432             }
43433             return params;
43434         }
43435         function combineSignaturesOfUnionMembers(left, right) {
43436             var declaration = left.declaration;
43437             var params = combineUnionParameters(left, right);
43438             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
43439             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
43440             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
43441             /*resolvedReturnType*/ undefined, 
43442             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */);
43443             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
43444             return result;
43445         }
43446         function getUnionIndexInfo(types, kind) {
43447             var indexTypes = [];
43448             var isAnyReadonly = false;
43449             for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
43450                 var type = types_3[_i];
43451                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
43452                 if (!indexInfo) {
43453                     return undefined;
43454                 }
43455                 indexTypes.push(indexInfo.type);
43456                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
43457             }
43458             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
43459         }
43460         function resolveUnionTypeMembers(type) {
43461             // The members and properties collections are empty for union types. To get all properties of a union
43462             // type use getPropertiesOfType (only the language service uses this).
43463             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
43464             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
43465             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
43466             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
43467             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43468         }
43469         function intersectTypes(type1, type2) {
43470             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
43471         }
43472         function intersectIndexInfos(info1, info2) {
43473             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
43474         }
43475         function unionSpreadIndexInfos(info1, info2) {
43476             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
43477         }
43478         function findMixins(types) {
43479             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
43480             var mixinFlags = ts.map(types, isMixinConstructorType);
43481             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
43482                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
43483                 mixinFlags[firstMixinIndex] = false;
43484             }
43485             return mixinFlags;
43486         }
43487         function includeMixinType(type, types, mixinFlags, index) {
43488             var mixedTypes = [];
43489             for (var i = 0; i < types.length; i++) {
43490                 if (i === index) {
43491                     mixedTypes.push(type);
43492                 }
43493                 else if (mixinFlags[i]) {
43494                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
43495                 }
43496             }
43497             return getIntersectionType(mixedTypes);
43498         }
43499         function resolveIntersectionTypeMembers(type) {
43500             // The members and properties collections are empty for intersection types. To get all properties of an
43501             // intersection type use getPropertiesOfType (only the language service uses this).
43502             var callSignatures;
43503             var constructSignatures;
43504             var stringIndexInfo;
43505             var numberIndexInfo;
43506             var types = type.types;
43507             var mixinFlags = findMixins(types);
43508             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
43509             var _loop_10 = function (i) {
43510                 var t = type.types[i];
43511                 // When an intersection type contains mixin constructor types, the construct signatures from
43512                 // those types are discarded and their return types are mixed into the return types of all
43513                 // other construct signatures in the intersection type. For example, the intersection type
43514                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
43515                 // 'new(s: string) => A & B'.
43516                 if (!mixinFlags[i]) {
43517                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
43518                     if (signatures.length && mixinCount > 0) {
43519                         signatures = ts.map(signatures, function (s) {
43520                             var clone = cloneSignature(s);
43521                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
43522                             return clone;
43523                         });
43524                     }
43525                     constructSignatures = appendSignatures(constructSignatures, signatures);
43526                 }
43527                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
43528                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
43529                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
43530             };
43531             for (var i = 0; i < types.length; i++) {
43532                 _loop_10(i);
43533             }
43534             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
43535         }
43536         function appendSignatures(signatures, newSignatures) {
43537             var _loop_11 = function (sig) {
43538                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
43539                     signatures = ts.append(signatures, sig);
43540                 }
43541             };
43542             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
43543                 var sig = newSignatures_1[_i];
43544                 _loop_11(sig);
43545             }
43546             return signatures;
43547         }
43548         /**
43549          * Converts an AnonymousType to a ResolvedType.
43550          */
43551         function resolveAnonymousTypeMembers(type) {
43552             var symbol = getMergedSymbol(type.symbol);
43553             if (type.target) {
43554                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43555                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
43556                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
43557                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
43558                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
43559                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
43560                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43561             }
43562             else if (symbol.flags & 2048 /* TypeLiteral */) {
43563                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43564                 var members = getMembersOfSymbol(symbol);
43565                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
43566                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
43567                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
43568                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
43569                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
43570             }
43571             else {
43572                 // Combinations of function, class, enum and module
43573                 var members = emptySymbols;
43574                 var stringIndexInfo = void 0;
43575                 if (symbol.exports) {
43576                     members = getExportsOfSymbol(symbol);
43577                     if (symbol === globalThisSymbol) {
43578                         var varsOnly_1 = ts.createMap();
43579                         members.forEach(function (p) {
43580                             if (!(p.flags & 418 /* BlockScoped */)) {
43581                                 varsOnly_1.set(p.escapedName, p);
43582                             }
43583                         });
43584                         members = varsOnly_1;
43585                     }
43586                 }
43587                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
43588                 if (symbol.flags & 32 /* Class */) {
43589                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
43590                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
43591                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
43592                         members = ts.createSymbolTable(getNamedMembers(members));
43593                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
43594                     }
43595                     else if (baseConstructorType === anyType) {
43596                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
43597                     }
43598                 }
43599                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
43600                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
43601                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43602                 // We resolve the members before computing the signatures because a signature may use
43603                 // typeof with a qualified name expression that circularly references the type we are
43604                 // in the process of resolving (see issue #6072). The temporarily empty signature list
43605                 // will never be observed because a qualified name can't reference signatures.
43606                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
43607                     type.callSignatures = getSignaturesOfSymbol(symbol);
43608                 }
43609                 // And likewise for construct signatures for classes
43610                 if (symbol.flags & 32 /* Class */) {
43611                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
43612                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
43613                     if (symbol.flags & 16 /* Function */) {
43614                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
43615                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) :
43616                             undefined; }));
43617                     }
43618                     if (!constructSignatures.length) {
43619                         constructSignatures = getDefaultConstructSignatures(classType_1);
43620                     }
43621                     type.constructSignatures = constructSignatures;
43622                 }
43623             }
43624         }
43625         function resolveReverseMappedTypeMembers(type) {
43626             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
43627             var modifiers = getMappedTypeModifiers(type.mappedType);
43628             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
43629             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
43630             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
43631             var members = ts.createSymbolTable();
43632             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
43633                 var prop = _a[_i];
43634                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
43635                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
43636                 inferredProp.declarations = prop.declarations;
43637                 inferredProp.nameType = getSymbolLinks(prop).nameType;
43638                 inferredProp.propertyType = getTypeOfSymbol(prop);
43639                 inferredProp.mappedType = type.mappedType;
43640                 inferredProp.constraintType = type.constraintType;
43641                 members.set(prop.escapedName, inferredProp);
43642             }
43643             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
43644         }
43645         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
43646         // bound includes those keys that are known to always be present, for example because
43647         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
43648         function getLowerBoundOfKeyType(type) {
43649             if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) {
43650                 return type;
43651             }
43652             if (type.flags & 4194304 /* Index */) {
43653                 return getIndexType(getApparentType(type.type));
43654             }
43655             if (type.flags & 16777216 /* Conditional */) {
43656                 if (type.root.isDistributive) {
43657                     var checkType = type.checkType;
43658                     var constraint = getLowerBoundOfKeyType(checkType);
43659                     if (constraint !== checkType) {
43660                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43661                     }
43662                 }
43663                 return type;
43664             }
43665             if (type.flags & 1048576 /* Union */) {
43666                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43667             }
43668             if (type.flags & 2097152 /* Intersection */) {
43669                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
43670             }
43671             return neverType;
43672         }
43673         /** Resolve the members of a mapped type { [P in K]: T } */
43674         function resolveMappedTypeMembers(type) {
43675             var members = ts.createSymbolTable();
43676             var stringIndexInfo;
43677             var numberIndexInfo;
43678             // Resolve upfront such that recursive references see an empty object type.
43679             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43680             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
43681             // and T as the template type.
43682             var typeParameter = getTypeParameterFromMappedType(type);
43683             var constraintType = getConstraintTypeFromMappedType(type);
43684             var templateType = getTemplateTypeFromMappedType(type.target || type);
43685             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
43686             var templateModifiers = getMappedTypeModifiers(type);
43687             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
43688             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43689                 // We have a { [P in keyof T]: X }
43690                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
43691                     var prop = _a[_i];
43692                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
43693                 }
43694                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
43695                     addMemberForKeyType(stringType);
43696                 }
43697                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
43698                     addMemberForKeyType(numberType);
43699                 }
43700             }
43701             else {
43702                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
43703             }
43704             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
43705             function addMemberForKeyType(t) {
43706                 // Create a mapper from T to the current iteration type constituent. Then, if the
43707                 // mapped type is itself an instantiated type, combine the iteration mapper with the
43708                 // instantiation mapper.
43709                 var templateMapper = appendTypeMapping(type.mapper, typeParameter, t);
43710                 // If the current iteration type constituent is a string literal type, create a property.
43711                 // Otherwise, for type string create a string index signature.
43712                 if (isTypeUsableAsPropertyName(t)) {
43713                     var propName = getPropertyNameFromType(t);
43714                     var modifiersProp = getPropertyOfType(modifiersType, propName);
43715                     var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
43716                         !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
43717                     var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
43718                         !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
43719                     var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
43720                     var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
43721                     prop.mappedType = type;
43722                     prop.mapper = templateMapper;
43723                     if (modifiersProp) {
43724                         prop.syntheticOrigin = modifiersProp;
43725                         prop.declarations = modifiersProp.declarations;
43726                     }
43727                     prop.nameType = t;
43728                     members.set(propName, prop);
43729                 }
43730                 else if (t.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
43731                     var propType = instantiateType(templateType, templateMapper);
43732                     if (t.flags & (1 /* Any */ | 4 /* String */)) {
43733                         stringIndexInfo = createIndexInfo(propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43734                     }
43735                     else {
43736                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
43737                     }
43738                 }
43739             }
43740         }
43741         function getTypeOfMappedSymbol(symbol) {
43742             if (!symbol.type) {
43743                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
43744                     return errorType;
43745                 }
43746                 var templateType = getTemplateTypeFromMappedType(symbol.mappedType.target || symbol.mappedType);
43747                 var propType = instantiateType(templateType, symbol.mapper);
43748                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
43749                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
43750                 // mode, if the underlying property is optional we remove 'undefined' from the type.
43751                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
43752                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
43753                         propType;
43754                 if (!popTypeResolution()) {
43755                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(symbol.mappedType));
43756                     type = errorType;
43757                 }
43758                 symbol.type = type;
43759                 symbol.mapper = undefined;
43760             }
43761             return symbol.type;
43762         }
43763         function getTypeParameterFromMappedType(type) {
43764             return type.typeParameter ||
43765                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
43766         }
43767         function getConstraintTypeFromMappedType(type) {
43768             return type.constraintType ||
43769                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
43770         }
43771         function getTemplateTypeFromMappedType(type) {
43772             return type.templateType ||
43773                 (type.templateType = type.declaration.type ?
43774                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
43775                     errorType);
43776         }
43777         function getConstraintDeclarationForMappedType(type) {
43778             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
43779         }
43780         function isMappedTypeWithKeyofConstraintDeclaration(type) {
43781             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
43782             return constraintDeclaration.kind === 184 /* TypeOperator */ &&
43783                 constraintDeclaration.operator === 134 /* KeyOfKeyword */;
43784         }
43785         function getModifiersTypeFromMappedType(type) {
43786             if (!type.modifiersType) {
43787                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
43788                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
43789                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
43790                     // 'keyof T' to a literal union type and we can't recover T from that type.
43791                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
43792                 }
43793                 else {
43794                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
43795                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
43796                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
43797                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
43798                     var constraint = getConstraintTypeFromMappedType(declaredType);
43799                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
43800                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
43801                 }
43802             }
43803             return type.modifiersType;
43804         }
43805         function getMappedTypeModifiers(type) {
43806             var declaration = type.declaration;
43807             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
43808                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
43809         }
43810         function getMappedTypeOptionality(type) {
43811             var modifiers = getMappedTypeModifiers(type);
43812             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
43813         }
43814         function getCombinedMappedTypeOptionality(type) {
43815             var optionality = getMappedTypeOptionality(type);
43816             var modifiersType = getModifiersTypeFromMappedType(type);
43817             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
43818         }
43819         function isPartialMappedType(type) {
43820             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
43821         }
43822         function isGenericMappedType(type) {
43823             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
43824         }
43825         function resolveStructuredTypeMembers(type) {
43826             if (!type.members) {
43827                 if (type.flags & 524288 /* Object */) {
43828                     if (type.objectFlags & 4 /* Reference */) {
43829                         resolveTypeReferenceMembers(type);
43830                     }
43831                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
43832                         resolveClassOrInterfaceMembers(type);
43833                     }
43834                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
43835                         resolveReverseMappedTypeMembers(type);
43836                     }
43837                     else if (type.objectFlags & 16 /* Anonymous */) {
43838                         resolveAnonymousTypeMembers(type);
43839                     }
43840                     else if (type.objectFlags & 32 /* Mapped */) {
43841                         resolveMappedTypeMembers(type);
43842                     }
43843                 }
43844                 else if (type.flags & 1048576 /* Union */) {
43845                     resolveUnionTypeMembers(type);
43846                 }
43847                 else if (type.flags & 2097152 /* Intersection */) {
43848                     resolveIntersectionTypeMembers(type);
43849                 }
43850             }
43851             return type;
43852         }
43853         /** Return properties of an object type or an empty array for other types */
43854         function getPropertiesOfObjectType(type) {
43855             if (type.flags & 524288 /* Object */) {
43856                 return resolveStructuredTypeMembers(type).properties;
43857             }
43858             return ts.emptyArray;
43859         }
43860         /** If the given type is an object type and that type has a property by the given name,
43861          * return the symbol for that property. Otherwise return undefined.
43862          */
43863         function getPropertyOfObjectType(type, name) {
43864             if (type.flags & 524288 /* Object */) {
43865                 var resolved = resolveStructuredTypeMembers(type);
43866                 var symbol = resolved.members.get(name);
43867                 if (symbol && symbolIsValue(symbol)) {
43868                     return symbol;
43869                 }
43870             }
43871         }
43872         function getPropertiesOfUnionOrIntersectionType(type) {
43873             if (!type.resolvedProperties) {
43874                 var members = ts.createSymbolTable();
43875                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
43876                     var current = _a[_i];
43877                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
43878                         var prop = _c[_b];
43879                         if (!members.has(prop.escapedName)) {
43880                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
43881                             if (combinedProp) {
43882                                 members.set(prop.escapedName, combinedProp);
43883                             }
43884                         }
43885                     }
43886                     // The properties of a union type are those that are present in all constituent types, so
43887                     // we only need to check the properties of the first type without index signature
43888                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
43889                         break;
43890                     }
43891                 }
43892                 type.resolvedProperties = getNamedMembers(members);
43893             }
43894             return type.resolvedProperties;
43895         }
43896         function getPropertiesOfType(type) {
43897             type = getReducedApparentType(type);
43898             return type.flags & 3145728 /* UnionOrIntersection */ ?
43899                 getPropertiesOfUnionOrIntersectionType(type) :
43900                 getPropertiesOfObjectType(type);
43901         }
43902         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
43903             var list = obj.properties;
43904             return list.some(function (property) {
43905                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
43906                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
43907                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
43908                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
43909             });
43910         }
43911         function getAllPossiblePropertiesOfTypes(types) {
43912             var unionType = getUnionType(types);
43913             if (!(unionType.flags & 1048576 /* Union */)) {
43914                 return getAugmentedPropertiesOfType(unionType);
43915             }
43916             var props = ts.createSymbolTable();
43917             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
43918                 var memberType = types_4[_i];
43919                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
43920                     var escapedName = _b[_a].escapedName;
43921                     if (!props.has(escapedName)) {
43922                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
43923                         // May be undefined if the property is private
43924                         if (prop)
43925                             props.set(escapedName, prop);
43926                     }
43927                 }
43928             }
43929             return ts.arrayFrom(props.values());
43930         }
43931         function getConstraintOfType(type) {
43932             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
43933                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
43934                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
43935                         getBaseConstraintOfType(type);
43936         }
43937         function getConstraintOfTypeParameter(typeParameter) {
43938             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
43939         }
43940         function getConstraintOfIndexedAccess(type) {
43941             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
43942         }
43943         function getSimplifiedTypeOrConstraint(type) {
43944             var simplified = getSimplifiedType(type, /*writing*/ false);
43945             return simplified !== type ? simplified : getConstraintOfType(type);
43946         }
43947         function getConstraintFromIndexedAccess(type) {
43948             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
43949             if (indexConstraint && indexConstraint !== type.indexType) {
43950                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint);
43951                 if (indexedAccess) {
43952                     return indexedAccess;
43953                 }
43954             }
43955             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
43956             if (objectConstraint && objectConstraint !== type.objectType) {
43957                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType);
43958             }
43959             return undefined;
43960         }
43961         function getDefaultConstraintOfConditionalType(type) {
43962             if (!type.resolvedDefaultConstraint) {
43963                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
43964                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
43965                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
43966                 // in effect treating `any` like `never` rather than `unknown` in this location.
43967                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
43968                 var falseConstraint = getFalseTypeFromConditionalType(type);
43969                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
43970             }
43971             return type.resolvedDefaultConstraint;
43972         }
43973         function getConstraintOfDistributiveConditionalType(type) {
43974             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
43975             // type parameter. If so, create an instantiation of the conditional type where T is replaced
43976             // with its constraint. We do this because if the constraint is a union type it will be distributed
43977             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
43978             // removes 'undefined' from T.
43979             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
43980             // as the constraint for all type params (check type included) have been replace with `unknown`, which
43981             // is going to produce even more false positive/negative results than the distribute constraint already does.
43982             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
43983             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
43984             // likely doesn't need to exist.
43985             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
43986                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
43987                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
43988                 if (constraint && constraint !== type.checkType) {
43989                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
43990                     if (!(instantiated.flags & 131072 /* Never */)) {
43991                         return instantiated;
43992                     }
43993                 }
43994             }
43995             return undefined;
43996         }
43997         function getConstraintFromConditionalType(type) {
43998             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
43999         }
44000         function getConstraintOfConditionalType(type) {
44001             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
44002         }
44003         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
44004             var constraints;
44005             var hasDisjointDomainType = false;
44006             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
44007                 var t = types_5[_i];
44008                 if (t.flags & 63176704 /* Instantiable */) {
44009                     // We keep following constraints as long as we have an instantiable type that is known
44010                     // not to be circular or infinite (hence we stop on index access types).
44011                     var constraint = getConstraintOfType(t);
44012                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
44013                         constraint = getConstraintOfType(constraint);
44014                     }
44015                     if (constraint) {
44016                         constraints = ts.append(constraints, constraint);
44017                         if (targetIsUnion) {
44018                             constraints = ts.append(constraints, t);
44019                         }
44020                     }
44021                 }
44022                 else if (t.flags & 67238908 /* DisjointDomains */) {
44023                     hasDisjointDomainType = true;
44024                 }
44025             }
44026             // If the target is a union type or if we are intersecting with types belonging to one of the
44027             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
44028             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
44029                 if (hasDisjointDomainType) {
44030                     // We add any types belong to one of the disjoint domains because they might cause the final
44031                     // intersection operation to reduce the union constraints.
44032                     for (var _a = 0, types_6 = types; _a < types_6.length; _a++) {
44033                         var t = types_6[_a];
44034                         if (t.flags & 67238908 /* DisjointDomains */) {
44035                             constraints = ts.append(constraints, t);
44036                         }
44037                     }
44038                 }
44039                 return getIntersectionType(constraints);
44040             }
44041             return undefined;
44042         }
44043         function getBaseConstraintOfType(type) {
44044             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */)) {
44045                 var constraint = getResolvedBaseConstraint(type);
44046                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
44047             }
44048             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
44049         }
44050         /**
44051          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
44052          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
44053          */
44054         function getBaseConstraintOrType(type) {
44055             return getBaseConstraintOfType(type) || type;
44056         }
44057         function hasNonCircularBaseConstraint(type) {
44058             return getResolvedBaseConstraint(type) !== circularConstraintType;
44059         }
44060         /**
44061          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
44062          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
44063          * circularly references the type variable.
44064          */
44065         function getResolvedBaseConstraint(type) {
44066             var nonTerminating = false;
44067             return type.resolvedBaseConstraint ||
44068                 (type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type));
44069             function getImmediateBaseConstraint(t) {
44070                 if (!t.immediateBaseConstraint) {
44071                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
44072                         return circularConstraintType;
44073                     }
44074                     if (constraintDepth >= 50) {
44075                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
44076                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
44077                         // new type identities as we descend into it. We stop the recursion here and mark this type
44078                         // and the outer types as having circular constraints.
44079                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
44080                         nonTerminating = true;
44081                         return t.immediateBaseConstraint = noConstraintType;
44082                     }
44083                     constraintDepth++;
44084                     var result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
44085                     constraintDepth--;
44086                     if (!popTypeResolution()) {
44087                         if (t.flags & 262144 /* TypeParameter */) {
44088                             var errorNode = getConstraintDeclaration(t);
44089                             if (errorNode) {
44090                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
44091                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
44092                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
44093                                 }
44094                             }
44095                         }
44096                         result = circularConstraintType;
44097                     }
44098                     if (nonTerminating) {
44099                         result = circularConstraintType;
44100                     }
44101                     t.immediateBaseConstraint = result || noConstraintType;
44102                 }
44103                 return t.immediateBaseConstraint;
44104             }
44105             function getBaseConstraint(t) {
44106                 var c = getImmediateBaseConstraint(t);
44107                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
44108             }
44109             function computeBaseConstraint(t) {
44110                 if (t.flags & 262144 /* TypeParameter */) {
44111                     var constraint = getConstraintFromTypeParameter(t);
44112                     return t.isThisType || !constraint ?
44113                         constraint :
44114                         getBaseConstraint(constraint);
44115                 }
44116                 if (t.flags & 3145728 /* UnionOrIntersection */) {
44117                     var types = t.types;
44118                     var baseTypes = [];
44119                     for (var _i = 0, types_7 = types; _i < types_7.length; _i++) {
44120                         var type_2 = types_7[_i];
44121                         var baseType = getBaseConstraint(type_2);
44122                         if (baseType) {
44123                             baseTypes.push(baseType);
44124                         }
44125                     }
44126                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
44127                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
44128                             undefined;
44129                 }
44130                 if (t.flags & 4194304 /* Index */) {
44131                     return keyofConstraintType;
44132                 }
44133                 if (t.flags & 8388608 /* IndexedAccess */) {
44134                     var baseObjectType = getBaseConstraint(t.objectType);
44135                     var baseIndexType = getBaseConstraint(t.indexType);
44136                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType);
44137                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
44138                 }
44139                 if (t.flags & 16777216 /* Conditional */) {
44140                     var constraint = getConstraintFromConditionalType(t);
44141                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
44142                     var result = constraint && getBaseConstraint(constraint);
44143                     constraintDepth--;
44144                     return result;
44145                 }
44146                 if (t.flags & 33554432 /* Substitution */) {
44147                     return getBaseConstraint(t.substitute);
44148                 }
44149                 return t;
44150             }
44151         }
44152         function getApparentTypeOfIntersectionType(type) {
44153             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
44154         }
44155         function getResolvedTypeParameterDefault(typeParameter) {
44156             if (!typeParameter.default) {
44157                 if (typeParameter.target) {
44158                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
44159                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
44160                 }
44161                 else {
44162                     // To block recursion, set the initial value to the resolvingDefaultType.
44163                     typeParameter.default = resolvingDefaultType;
44164                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
44165                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
44166                     if (typeParameter.default === resolvingDefaultType) {
44167                         // If we have not been called recursively, set the correct default type.
44168                         typeParameter.default = defaultType;
44169                     }
44170                 }
44171             }
44172             else if (typeParameter.default === resolvingDefaultType) {
44173                 // If we are called recursively for this type parameter, mark the default as circular.
44174                 typeParameter.default = circularConstraintType;
44175             }
44176             return typeParameter.default;
44177         }
44178         /**
44179          * Gets the default type for a type parameter.
44180          *
44181          * If the type parameter is the result of an instantiation, this gets the instantiated
44182          * default type of its target. If the type parameter has no default type or the default is
44183          * circular, `undefined` is returned.
44184          */
44185         function getDefaultFromTypeParameter(typeParameter) {
44186             var defaultType = getResolvedTypeParameterDefault(typeParameter);
44187             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
44188         }
44189         function hasNonCircularTypeParameterDefault(typeParameter) {
44190             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
44191         }
44192         /**
44193          * Indicates whether the declaration of a typeParameter has a default type.
44194          */
44195         function hasTypeParameterDefault(typeParameter) {
44196             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
44197         }
44198         function getApparentTypeOfMappedType(type) {
44199             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
44200         }
44201         function getResolvedApparentTypeOfMappedType(type) {
44202             var typeVariable = getHomomorphicTypeVariable(type);
44203             if (typeVariable) {
44204                 var constraint = getConstraintOfTypeParameter(typeVariable);
44205                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
44206                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
44207                 }
44208             }
44209             return type;
44210         }
44211         /**
44212          * For a type parameter, return the base constraint of the type parameter. For the string, number,
44213          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
44214          * type itself.
44215          */
44216         function getApparentType(type) {
44217             var t = type.flags & 63176704 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
44218             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
44219                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
44220                     t.flags & 132 /* StringLike */ ? globalStringType :
44221                         t.flags & 296 /* NumberLike */ ? globalNumberType :
44222                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
44223                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
44224                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
44225                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
44226                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
44227                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
44228                                                     t;
44229         }
44230         function getReducedApparentType(type) {
44231             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
44232             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
44233             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
44234             // that type may need futher reduction to remove empty intersections.
44235             return getReducedType(getApparentType(getReducedType(type)));
44236         }
44237         function createUnionOrIntersectionProperty(containingType, name) {
44238             var singleProp;
44239             var propSet;
44240             var indexTypes;
44241             var isUnion = containingType.flags & 1048576 /* Union */;
44242             // Flags we want to propagate to the result if they exist in all source symbols
44243             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
44244             var syntheticFlag = 4 /* SyntheticMethod */;
44245             var checkFlags = 0;
44246             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
44247                 var current = _a[_i];
44248                 var type = getApparentType(current);
44249                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
44250                     var prop = getPropertyOfType(type, name);
44251                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
44252                     if (prop) {
44253                         if (isUnion) {
44254                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
44255                         }
44256                         else {
44257                             optionalFlag &= prop.flags;
44258                         }
44259                         if (!singleProp) {
44260                             singleProp = prop;
44261                         }
44262                         else if (prop !== singleProp) {
44263                             if (!propSet) {
44264                                 propSet = ts.createMap();
44265                                 propSet.set("" + getSymbolId(singleProp), singleProp);
44266                             }
44267                             var id = "" + getSymbolId(prop);
44268                             if (!propSet.has(id)) {
44269                                 propSet.set(id, prop);
44270                             }
44271                         }
44272                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
44273                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
44274                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
44275                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
44276                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
44277                         if (!isPrototypeProperty(prop)) {
44278                             syntheticFlag = 2 /* SyntheticProperty */;
44279                         }
44280                     }
44281                     else if (isUnion) {
44282                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
44283                         if (indexInfo) {
44284                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
44285                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
44286                         }
44287                         else if (isObjectLiteralType(type)) {
44288                             checkFlags |= 32 /* WritePartial */;
44289                             indexTypes = ts.append(indexTypes, undefinedType);
44290                         }
44291                         else {
44292                             checkFlags |= 16 /* ReadPartial */;
44293                         }
44294                     }
44295                 }
44296             }
44297             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
44298                 // No property was found, or, in a union, a property has a private or protected declaration in one
44299                 // constituent, but is missing or has a different declaration in another constituent.
44300                 return undefined;
44301             }
44302             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
44303                 return singleProp;
44304             }
44305             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
44306             var declarations;
44307             var firstType;
44308             var nameType;
44309             var propTypes = [];
44310             var firstValueDeclaration;
44311             var hasNonUniformValueDeclaration = false;
44312             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
44313                 var prop = props_1[_b];
44314                 if (!firstValueDeclaration) {
44315                     firstValueDeclaration = prop.valueDeclaration;
44316                 }
44317                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
44318                     hasNonUniformValueDeclaration = true;
44319                 }
44320                 declarations = ts.addRange(declarations, prop.declarations);
44321                 var type = getTypeOfSymbol(prop);
44322                 if (!firstType) {
44323                     firstType = type;
44324                     nameType = getSymbolLinks(prop).nameType;
44325                 }
44326                 else if (type !== firstType) {
44327                     checkFlags |= 64 /* HasNonUniformType */;
44328                 }
44329                 if (isLiteralType(type)) {
44330                     checkFlags |= 128 /* HasLiteralType */;
44331                 }
44332                 if (type.flags & 131072 /* Never */) {
44333                     checkFlags |= 131072 /* HasNeverType */;
44334                 }
44335                 propTypes.push(type);
44336             }
44337             ts.addRange(propTypes, indexTypes);
44338             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
44339             result.containingType = containingType;
44340             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
44341                 result.valueDeclaration = firstValueDeclaration;
44342                 // Inherit information about parent type.
44343                 if (firstValueDeclaration.symbol.parent) {
44344                     result.parent = firstValueDeclaration.symbol.parent;
44345                 }
44346             }
44347             result.declarations = declarations;
44348             result.nameType = nameType;
44349             if (propTypes.length > 2) {
44350                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
44351                 result.checkFlags |= 65536 /* DeferredType */;
44352                 result.deferralParent = containingType;
44353                 result.deferralConstituents = propTypes;
44354             }
44355             else {
44356                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
44357             }
44358             return result;
44359         }
44360         // Return the symbol for a given property in a union or intersection type, or undefined if the property
44361         // does not exist in any constituent type. Note that the returned property may only be present in some
44362         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
44363         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
44364         // and do not appear to be present in the union type.
44365         function getUnionOrIntersectionProperty(type, name) {
44366             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
44367             var property = properties.get(name);
44368             if (!property) {
44369                 property = createUnionOrIntersectionProperty(type, name);
44370                 if (property) {
44371                     properties.set(name, property);
44372                 }
44373             }
44374             return property;
44375         }
44376         function getPropertyOfUnionOrIntersectionType(type, name) {
44377             var property = getUnionOrIntersectionProperty(type, name);
44378             // We need to filter out partial properties in union types
44379             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
44380         }
44381         /**
44382          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
44383          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
44384          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
44385          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
44386          */
44387         function getReducedType(type) {
44388             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
44389                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
44390             }
44391             else if (type.flags & 2097152 /* Intersection */) {
44392                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
44393                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
44394                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
44395                 }
44396                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
44397             }
44398             return type;
44399         }
44400         function getReducedUnionType(unionType) {
44401             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
44402             if (reducedTypes === unionType.types) {
44403                 return unionType;
44404             }
44405             var reduced = getUnionType(reducedTypes);
44406             if (reduced.flags & 1048576 /* Union */) {
44407                 reduced.resolvedReducedType = reduced;
44408             }
44409             return reduced;
44410         }
44411         function isNeverReducedProperty(prop) {
44412             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
44413         }
44414         function isDiscriminantWithNeverType(prop) {
44415             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
44416             // a literal type and none is never, that reduces to never.
44417             return !(prop.flags & 16777216 /* Optional */) &&
44418                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
44419                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
44420         }
44421         function isConflictingPrivateProperty(prop) {
44422             // Return true for a synthetic property with multiple declarations, at least one of which is private.
44423             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
44424         }
44425         function elaborateNeverIntersection(errorInfo, type) {
44426             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
44427                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
44428                 if (neverProp) {
44429                     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));
44430                 }
44431                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
44432                 if (privateProp) {
44433                     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));
44434                 }
44435             }
44436             return errorInfo;
44437         }
44438         /**
44439          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
44440          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
44441          * Object and Function as appropriate.
44442          *
44443          * @param type a type to look up property from
44444          * @param name a name of property to look up in a given type
44445          */
44446         function getPropertyOfType(type, name) {
44447             type = getReducedApparentType(type);
44448             if (type.flags & 524288 /* Object */) {
44449                 var resolved = resolveStructuredTypeMembers(type);
44450                 var symbol = resolved.members.get(name);
44451                 if (symbol && symbolIsValue(symbol)) {
44452                     return symbol;
44453                 }
44454                 var functionType = resolved === anyFunctionType ? globalFunctionType :
44455                     resolved.callSignatures.length ? globalCallableFunctionType :
44456                         resolved.constructSignatures.length ? globalNewableFunctionType :
44457                             undefined;
44458                 if (functionType) {
44459                     var symbol_1 = getPropertyOfObjectType(functionType, name);
44460                     if (symbol_1) {
44461                         return symbol_1;
44462                     }
44463                 }
44464                 return getPropertyOfObjectType(globalObjectType, name);
44465             }
44466             if (type.flags & 3145728 /* UnionOrIntersection */) {
44467                 return getPropertyOfUnionOrIntersectionType(type, name);
44468             }
44469             return undefined;
44470         }
44471         function getSignaturesOfStructuredType(type, kind) {
44472             if (type.flags & 3670016 /* StructuredType */) {
44473                 var resolved = resolveStructuredTypeMembers(type);
44474                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
44475             }
44476             return ts.emptyArray;
44477         }
44478         /**
44479          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
44480          * maps primitive types and type parameters are to their apparent types.
44481          */
44482         function getSignaturesOfType(type, kind) {
44483             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
44484         }
44485         function getIndexInfoOfStructuredType(type, kind) {
44486             if (type.flags & 3670016 /* StructuredType */) {
44487                 var resolved = resolveStructuredTypeMembers(type);
44488                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
44489             }
44490         }
44491         function getIndexTypeOfStructuredType(type, kind) {
44492             var info = getIndexInfoOfStructuredType(type, kind);
44493             return info && info.type;
44494         }
44495         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
44496         // maps primitive types and type parameters are to their apparent types.
44497         function getIndexInfoOfType(type, kind) {
44498             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
44499         }
44500         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
44501         // maps primitive types and type parameters are to their apparent types.
44502         function getIndexTypeOfType(type, kind) {
44503             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
44504         }
44505         function getImplicitIndexTypeOfType(type, kind) {
44506             if (isObjectTypeWithInferableIndex(type)) {
44507                 var propTypes = [];
44508                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
44509                     var prop = _a[_i];
44510                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
44511                         propTypes.push(getTypeOfSymbol(prop));
44512                     }
44513                 }
44514                 if (kind === 0 /* String */) {
44515                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
44516                 }
44517                 if (propTypes.length) {
44518                     return getUnionType(propTypes);
44519                 }
44520             }
44521             return undefined;
44522         }
44523         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
44524         // type checking functions).
44525         function getTypeParametersFromDeclaration(declaration) {
44526             var result;
44527             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
44528                 var node = _a[_i];
44529                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
44530             }
44531             return result;
44532         }
44533         function symbolsToArray(symbols) {
44534             var result = [];
44535             symbols.forEach(function (symbol, id) {
44536                 if (!isReservedMemberName(id)) {
44537                     result.push(symbol);
44538                 }
44539             });
44540             return result;
44541         }
44542         function isJSDocOptionalParameter(node) {
44543             return ts.isInJSFile(node) && (
44544             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
44545             node.type && node.type.kind === 299 /* JSDocOptionalType */
44546                 || ts.getJSDocParameterTags(node).some(function (_a) {
44547                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
44548                     return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44549                 }));
44550         }
44551         function tryFindAmbientModule(moduleName, withAugmentations) {
44552             if (ts.isExternalModuleNameRelative(moduleName)) {
44553                 return undefined;
44554             }
44555             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
44556             // merged symbol is module declaration symbol combined with all augmentations
44557             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
44558         }
44559         function isOptionalParameter(node) {
44560             if (ts.hasQuestionToken(node) || isOptionalJSDocParameterTag(node) || isJSDocOptionalParameter(node)) {
44561                 return true;
44562             }
44563             if (node.initializer) {
44564                 var signature = getSignatureFromDeclaration(node.parent);
44565                 var parameterIndex = node.parent.parameters.indexOf(node);
44566                 ts.Debug.assert(parameterIndex >= 0);
44567                 return parameterIndex >= getMinArgumentCount(signature, /*strongArityForUntypedJS*/ true);
44568             }
44569             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
44570             if (iife) {
44571                 return !node.type &&
44572                     !node.dotDotDotToken &&
44573                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
44574             }
44575             return false;
44576         }
44577         function isOptionalJSDocParameterTag(node) {
44578             if (!ts.isJSDocParameterTag(node)) {
44579                 return false;
44580             }
44581             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
44582             return isBracketed || !!typeExpression && typeExpression.type.kind === 299 /* JSDocOptionalType */;
44583         }
44584         function createTypePredicate(kind, parameterName, parameterIndex, type) {
44585             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
44586         }
44587         /**
44588          * Gets the minimum number of type arguments needed to satisfy all non-optional type
44589          * parameters.
44590          */
44591         function getMinTypeArgumentCount(typeParameters) {
44592             var minTypeArgumentCount = 0;
44593             if (typeParameters) {
44594                 for (var i = 0; i < typeParameters.length; i++) {
44595                     if (!hasTypeParameterDefault(typeParameters[i])) {
44596                         minTypeArgumentCount = i + 1;
44597                     }
44598                 }
44599             }
44600             return minTypeArgumentCount;
44601         }
44602         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
44603             var numTypeParameters = ts.length(typeParameters);
44604             if (!numTypeParameters) {
44605                 return [];
44606             }
44607             var numTypeArguments = ts.length(typeArguments);
44608             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
44609                 var result = typeArguments ? typeArguments.slice() : [];
44610                 // Map invalid forward references in default types to the error type
44611                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44612                     result[i] = errorType;
44613                 }
44614                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
44615                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
44616                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
44617                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
44618                         defaultType = anyType;
44619                     }
44620                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
44621                 }
44622                 result.length = typeParameters.length;
44623                 return result;
44624             }
44625             return typeArguments && typeArguments.slice();
44626         }
44627         function getSignatureFromDeclaration(declaration) {
44628             var links = getNodeLinks(declaration);
44629             if (!links.resolvedSignature) {
44630                 var parameters = [];
44631                 var flags = 0 /* None */;
44632                 var minArgumentCount = 0;
44633                 var thisParameter = void 0;
44634                 var hasThisParameter = false;
44635                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
44636                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
44637                 var isUntypedSignatureInJSFile = !iife &&
44638                     ts.isInJSFile(declaration) &&
44639                     ts.isValueSignatureDeclaration(declaration) &&
44640                     !ts.hasJSDocParameterTags(declaration) &&
44641                     !ts.getJSDocType(declaration);
44642                 if (isUntypedSignatureInJSFile) {
44643                     flags |= 16 /* IsUntypedSignatureInJSFile */;
44644                 }
44645                 // If this is a JSDoc construct signature, then skip the first parameter in the
44646                 // parameter list.  The first parameter represents the return type of the construct
44647                 // signature.
44648                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
44649                     var param = declaration.parameters[i];
44650                     var paramSymbol = param.symbol;
44651                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
44652                     // Include parameter symbol instead of property symbol in the signature
44653                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
44654                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
44655                         paramSymbol = resolvedSymbol;
44656                     }
44657                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
44658                         hasThisParameter = true;
44659                         thisParameter = param.symbol;
44660                     }
44661                     else {
44662                         parameters.push(paramSymbol);
44663                     }
44664                     if (type && type.kind === 187 /* LiteralType */) {
44665                         flags |= 2 /* HasLiteralTypes */;
44666                     }
44667                     // Record a new minimum argument count if this is not an optional parameter
44668                     var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) ||
44669                         param.initializer || param.questionToken || param.dotDotDotToken ||
44670                         iife && parameters.length > iife.arguments.length && !type ||
44671                         isJSDocOptionalParameter(param);
44672                     if (!isOptionalParameter_1) {
44673                         minArgumentCount = parameters.length;
44674                     }
44675                 }
44676                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
44677                 if ((declaration.kind === 163 /* GetAccessor */ || declaration.kind === 164 /* SetAccessor */) &&
44678                     !hasNonBindableDynamicName(declaration) &&
44679                     (!hasThisParameter || !thisParameter)) {
44680                     var otherKind = declaration.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
44681                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
44682                     if (other) {
44683                         thisParameter = getAnnotatedAccessorThisParameter(other);
44684                     }
44685                 }
44686                 var classType = declaration.kind === 162 /* Constructor */ ?
44687                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
44688                     : undefined;
44689                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
44690                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
44691                     flags |= 1 /* HasRestParameter */;
44692                 }
44693                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
44694                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
44695             }
44696             return links.resolvedSignature;
44697         }
44698         /**
44699          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
44700          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
44701          * OR
44702          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
44703          */
44704         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
44705             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
44706                 return false;
44707             }
44708             var lastParam = ts.lastOrUndefined(declaration.parameters);
44709             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
44710             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
44711                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
44712             });
44713             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
44714             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
44715             if (lastParamVariadicType) {
44716                 // Replace the last parameter with a rest parameter.
44717                 parameters.pop();
44718             }
44719             parameters.push(syntheticArgsSymbol);
44720             return true;
44721         }
44722         function getSignatureOfTypeTag(node) {
44723             // should be attached to a function declaration or expression
44724             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
44725                 return undefined;
44726             var typeTag = ts.getJSDocTypeTag(node);
44727             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
44728             return signature && getErasedSignature(signature);
44729         }
44730         function getReturnTypeOfTypeTag(node) {
44731             var signature = getSignatureOfTypeTag(node);
44732             return signature && getReturnTypeOfSignature(signature);
44733         }
44734         function containsArgumentsReference(declaration) {
44735             var links = getNodeLinks(declaration);
44736             if (links.containsArgumentsReference === undefined) {
44737                 if (links.flags & 8192 /* CaptureArguments */) {
44738                     links.containsArgumentsReference = true;
44739                 }
44740                 else {
44741                     links.containsArgumentsReference = traverse(declaration.body);
44742                 }
44743             }
44744             return links.containsArgumentsReference;
44745             function traverse(node) {
44746                 if (!node)
44747                     return false;
44748                 switch (node.kind) {
44749                     case 75 /* Identifier */:
44750                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
44751                     case 159 /* PropertyDeclaration */:
44752                     case 161 /* MethodDeclaration */:
44753                     case 163 /* GetAccessor */:
44754                     case 164 /* SetAccessor */:
44755                         return node.name.kind === 154 /* ComputedPropertyName */
44756                             && traverse(node.name);
44757                     default:
44758                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
44759                 }
44760             }
44761         }
44762         function getSignaturesOfSymbol(symbol) {
44763             if (!symbol)
44764                 return ts.emptyArray;
44765             var result = [];
44766             for (var i = 0; i < symbol.declarations.length; i++) {
44767                 var decl = symbol.declarations[i];
44768                 if (!ts.isFunctionLike(decl))
44769                     continue;
44770                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
44771                 // an implementation node if it has a body and the previous node is of the same kind and immediately
44772                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
44773                 if (i > 0 && decl.body) {
44774                     var previous = symbol.declarations[i - 1];
44775                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
44776                         continue;
44777                     }
44778                 }
44779                 result.push(getSignatureFromDeclaration(decl));
44780             }
44781             return result;
44782         }
44783         function resolveExternalModuleTypeByLiteral(name) {
44784             var moduleSym = resolveExternalModuleName(name, name);
44785             if (moduleSym) {
44786                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
44787                 if (resolvedModuleSymbol) {
44788                     return getTypeOfSymbol(resolvedModuleSymbol);
44789                 }
44790             }
44791             return anyType;
44792         }
44793         function getThisTypeOfSignature(signature) {
44794             if (signature.thisParameter) {
44795                 return getTypeOfSymbol(signature.thisParameter);
44796             }
44797         }
44798         function getTypePredicateOfSignature(signature) {
44799             if (!signature.resolvedTypePredicate) {
44800                 if (signature.target) {
44801                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
44802                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
44803                 }
44804                 else if (signature.unionSignatures) {
44805                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
44806                 }
44807                 else {
44808                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
44809                     var jsdocPredicate = void 0;
44810                     if (!type && ts.isInJSFile(signature.declaration)) {
44811                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
44812                         if (jsdocSignature && signature !== jsdocSignature) {
44813                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
44814                         }
44815                     }
44816                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
44817                         createTypePredicateFromTypePredicateNode(type, signature) :
44818                         jsdocPredicate || noTypePredicate;
44819                 }
44820                 ts.Debug.assert(!!signature.resolvedTypePredicate);
44821             }
44822             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
44823         }
44824         function createTypePredicateFromTypePredicateNode(node, signature) {
44825             var parameterName = node.parameterName;
44826             var type = node.type && getTypeFromTypeNode(node.type);
44827             return parameterName.kind === 183 /* ThisType */ ?
44828                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
44829                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
44830         }
44831         function getReturnTypeOfSignature(signature) {
44832             if (!signature.resolvedReturnType) {
44833                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
44834                     return errorType;
44835                 }
44836                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
44837                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
44838                         getReturnTypeFromAnnotation(signature.declaration) ||
44839                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
44840                 if (signature.flags & 4 /* IsInnerCallChain */) {
44841                     type = addOptionalTypeMarker(type);
44842                 }
44843                 else if (signature.flags & 8 /* IsOuterCallChain */) {
44844                     type = getOptionalType(type);
44845                 }
44846                 if (!popTypeResolution()) {
44847                     if (signature.declaration) {
44848                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
44849                         if (typeNode) {
44850                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
44851                         }
44852                         else if (noImplicitAny) {
44853                             var declaration = signature.declaration;
44854                             var name = ts.getNameOfDeclaration(declaration);
44855                             if (name) {
44856                                 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));
44857                             }
44858                             else {
44859                                 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);
44860                             }
44861                         }
44862                     }
44863                     type = anyType;
44864                 }
44865                 signature.resolvedReturnType = type;
44866             }
44867             return signature.resolvedReturnType;
44868         }
44869         function getReturnTypeFromAnnotation(declaration) {
44870             if (declaration.kind === 162 /* Constructor */) {
44871                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
44872             }
44873             if (ts.isJSDocConstructSignature(declaration)) {
44874                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
44875             }
44876             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
44877             if (typeNode) {
44878                 return getTypeFromTypeNode(typeNode);
44879             }
44880             if (declaration.kind === 163 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
44881                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
44882                 if (jsDocType) {
44883                     return jsDocType;
44884                 }
44885                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 164 /* SetAccessor */);
44886                 var setterType = getAnnotatedAccessorType(setter);
44887                 if (setterType) {
44888                     return setterType;
44889                 }
44890             }
44891             return getReturnTypeOfTypeTag(declaration);
44892         }
44893         function isResolvingReturnTypeOfSignature(signature) {
44894             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
44895         }
44896         function getRestTypeOfSignature(signature) {
44897             return tryGetRestTypeOfSignature(signature) || anyType;
44898         }
44899         function tryGetRestTypeOfSignature(signature) {
44900             if (signatureHasRestParameter(signature)) {
44901                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
44902                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
44903                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
44904             }
44905             return undefined;
44906         }
44907         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
44908             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
44909             if (inferredTypeParameters) {
44910                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
44911                 if (returnSignature) {
44912                     var newReturnSignature = cloneSignature(returnSignature);
44913                     newReturnSignature.typeParameters = inferredTypeParameters;
44914                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
44915                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
44916                     return newInstantiatedSignature;
44917                 }
44918             }
44919             return instantiatedSignature;
44920         }
44921         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
44922             var instantiations = signature.instantiations || (signature.instantiations = ts.createMap());
44923             var id = getTypeListId(typeArguments);
44924             var instantiation = instantiations.get(id);
44925             if (!instantiation) {
44926                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
44927             }
44928             return instantiation;
44929         }
44930         function createSignatureInstantiation(signature, typeArguments) {
44931             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
44932         }
44933         function createSignatureTypeMapper(signature, typeArguments) {
44934             return createTypeMapper(signature.typeParameters, typeArguments);
44935         }
44936         function getErasedSignature(signature) {
44937             return signature.typeParameters ?
44938                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
44939                 signature;
44940         }
44941         function createErasedSignature(signature) {
44942             // Create an instantiation of the signature where all type arguments are the any type.
44943             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
44944         }
44945         function getCanonicalSignature(signature) {
44946             return signature.typeParameters ?
44947                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
44948                 signature;
44949         }
44950         function createCanonicalSignature(signature) {
44951             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
44952             // its original. When a generic class or interface is instantiated, each generic method in the class or
44953             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
44954             // where different generations of the same type parameter are in scope). This leads to a lot of new type
44955             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
44956             // that uses the original type identities for all unconstrained type parameters.
44957             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
44958         }
44959         function getBaseSignature(signature) {
44960             var typeParameters = signature.typeParameters;
44961             if (typeParameters) {
44962                 var typeEraser_1 = createTypeEraser(typeParameters);
44963                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
44964                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
44965             }
44966             return signature;
44967         }
44968         function getOrCreateTypeFromSignature(signature) {
44969             // There are two ways to declare a construct signature, one is by declaring a class constructor
44970             // using the constructor keyword, and the other is declaring a bare construct signature in an
44971             // object type literal or interface (using the new keyword). Each way of declaring a constructor
44972             // will result in a different declaration kind.
44973             if (!signature.isolatedSignatureType) {
44974                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
44975                 var isConstructor = kind === 162 /* Constructor */ || kind === 166 /* ConstructSignature */ || kind === 171 /* ConstructorType */;
44976                 var type = createObjectType(16 /* Anonymous */);
44977                 type.members = emptySymbols;
44978                 type.properties = ts.emptyArray;
44979                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
44980                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
44981                 signature.isolatedSignatureType = type;
44982             }
44983             return signature.isolatedSignatureType;
44984         }
44985         function getIndexSymbol(symbol) {
44986             return symbol.members.get("__index" /* Index */);
44987         }
44988         function getIndexDeclarationOfSymbol(symbol, kind) {
44989             var syntaxKind = kind === 1 /* Number */ ? 140 /* NumberKeyword */ : 143 /* StringKeyword */;
44990             var indexSymbol = getIndexSymbol(symbol);
44991             if (indexSymbol) {
44992                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
44993                     var decl = _a[_i];
44994                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
44995                     if (node.parameters.length === 1) {
44996                         var parameter = node.parameters[0];
44997                         if (parameter.type && parameter.type.kind === syntaxKind) {
44998                             return node;
44999                         }
45000                     }
45001                 }
45002             }
45003             return undefined;
45004         }
45005         function createIndexInfo(type, isReadonly, declaration) {
45006             return { type: type, isReadonly: isReadonly, declaration: declaration };
45007         }
45008         function getIndexInfoOfSymbol(symbol, kind) {
45009             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
45010             if (declaration) {
45011                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasModifier(declaration, 64 /* Readonly */), declaration);
45012             }
45013             return undefined;
45014         }
45015         function getConstraintDeclaration(type) {
45016             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
45017         }
45018         function getInferredTypeParameterConstraint(typeParameter) {
45019             var inferences;
45020             if (typeParameter.symbol) {
45021                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
45022                     var declaration = _a[_i];
45023                     if (declaration.parent.kind === 181 /* InferType */) {
45024                         // When an 'infer T' declaration is immediately contained in a type reference node
45025                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
45026                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
45027                         // present, we form an intersection of the inferred constraint types.
45028                         var grandParent = declaration.parent.parent;
45029                         if (grandParent.kind === 169 /* TypeReference */) {
45030                             var typeReference = grandParent;
45031                             var typeParameters = getTypeParametersForTypeReference(typeReference);
45032                             if (typeParameters) {
45033                                 var index = typeReference.typeArguments.indexOf(declaration.parent);
45034                                 if (index < typeParameters.length) {
45035                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
45036                                     if (declaredConstraint) {
45037                                         // Type parameter constraints can reference other type parameters so
45038                                         // constraints need to be instantiated. If instantiation produces the
45039                                         // type parameter itself, we discard that inference. For example, in
45040                                         //   type Foo<T extends string, U extends T> = [T, U];
45041                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
45042                                         // the instantiated constraint for U is X, so we discard that inference.
45043                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
45044                                         var constraint = instantiateType(declaredConstraint, mapper);
45045                                         if (constraint !== typeParameter) {
45046                                             inferences = ts.append(inferences, constraint);
45047                                         }
45048                                     }
45049                                 }
45050                             }
45051                         }
45052                         // When an 'infer T' declaration is immediately contained in a rest parameter
45053                         // declaration, we infer an 'unknown[]' constraint.
45054                         else if (grandParent.kind === 156 /* Parameter */ && grandParent.dotDotDotToken) {
45055                             inferences = ts.append(inferences, createArrayType(unknownType));
45056                         }
45057                     }
45058                 }
45059             }
45060             return inferences && getIntersectionType(inferences);
45061         }
45062         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
45063         function getConstraintFromTypeParameter(typeParameter) {
45064             if (!typeParameter.constraint) {
45065                 if (typeParameter.target) {
45066                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
45067                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
45068                 }
45069                 else {
45070                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
45071                     if (!constraintDeclaration) {
45072                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
45073                     }
45074                     else {
45075                         var type = getTypeFromTypeNode(constraintDeclaration);
45076                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
45077                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
45078                             // use unknown otherwise
45079                             type = constraintDeclaration.parent.parent.kind === 186 /* MappedType */ ? keyofConstraintType : unknownType;
45080                         }
45081                         typeParameter.constraint = type;
45082                     }
45083                 }
45084             }
45085             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
45086         }
45087         function getParentSymbolOfTypeParameter(typeParameter) {
45088             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 155 /* TypeParameter */);
45089             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
45090             return host && getSymbolOfNode(host);
45091         }
45092         function getTypeListId(types) {
45093             var result = "";
45094             if (types) {
45095                 var length_4 = types.length;
45096                 var i = 0;
45097                 while (i < length_4) {
45098                     var startId = types[i].id;
45099                     var count = 1;
45100                     while (i + count < length_4 && types[i + count].id === startId + count) {
45101                         count++;
45102                     }
45103                     if (result.length) {
45104                         result += ",";
45105                     }
45106                     result += startId;
45107                     if (count > 1) {
45108                         result += ":" + count;
45109                     }
45110                     i += count;
45111                 }
45112             }
45113             return result;
45114         }
45115         // This function is used to propagate certain flags when creating new object type references and union types.
45116         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
45117         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
45118         // that care about the presence of such types at arbitrary depth in a containing type.
45119         function getPropagatingFlagsOfTypes(types, excludeKinds) {
45120             var result = 0;
45121             for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
45122                 var type = types_8[_i];
45123                 if (!(type.flags & excludeKinds)) {
45124                     result |= ts.getObjectFlags(type);
45125                 }
45126             }
45127             return result & 3670016 /* PropagatingFlags */;
45128         }
45129         function createTypeReference(target, typeArguments) {
45130             var id = getTypeListId(typeArguments);
45131             var type = target.instantiations.get(id);
45132             if (!type) {
45133                 type = createObjectType(4 /* Reference */, target.symbol);
45134                 target.instantiations.set(id, type);
45135                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
45136                 type.target = target;
45137                 type.resolvedTypeArguments = typeArguments;
45138             }
45139             return type;
45140         }
45141         function cloneTypeReference(source) {
45142             var type = createType(source.flags);
45143             type.symbol = source.symbol;
45144             type.objectFlags = source.objectFlags;
45145             type.target = source.target;
45146             type.resolvedTypeArguments = source.resolvedTypeArguments;
45147             return type;
45148         }
45149         function createDeferredTypeReference(target, node, mapper) {
45150             var aliasSymbol = getAliasSymbolForTypeNode(node);
45151             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
45152             var type = createObjectType(4 /* Reference */, target.symbol);
45153             type.target = target;
45154             type.node = node;
45155             type.mapper = mapper;
45156             type.aliasSymbol = aliasSymbol;
45157             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
45158             return type;
45159         }
45160         function getTypeArguments(type) {
45161             var _a, _b;
45162             if (!type.resolvedTypeArguments) {
45163                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
45164                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
45165                 }
45166                 var node = type.node;
45167                 var typeArguments = !node ? ts.emptyArray :
45168                     node.kind === 169 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
45169                         node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
45170                             ts.map(node.elementTypes, getTypeFromTypeNode);
45171                 if (popTypeResolution()) {
45172                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
45173                 }
45174                 else {
45175                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
45176                     error(type.node || currentNode, type.target.symbol
45177                         ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves
45178                         : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
45179                 }
45180             }
45181             return type.resolvedTypeArguments;
45182         }
45183         function getTypeReferenceArity(type) {
45184             return ts.length(type.target.typeParameters);
45185         }
45186         /**
45187          * Get type from type-reference that reference to class or interface
45188          */
45189         function getTypeFromClassOrInterfaceReference(node, symbol) {
45190             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
45191             var typeParameters = type.localTypeParameters;
45192             if (typeParameters) {
45193                 var numTypeArguments = ts.length(node.typeArguments);
45194                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45195                 var isJs = ts.isInJSFile(node);
45196                 var isJsImplicitAny = !noImplicitAny && isJs;
45197                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
45198                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
45199                     var diag = minTypeArgumentCount === typeParameters.length ?
45200                         missingAugmentsTag ?
45201                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
45202                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45203                         missingAugmentsTag ?
45204                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
45205                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
45206                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
45207                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
45208                     if (!isJs) {
45209                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
45210                         return errorType;
45211                     }
45212                 }
45213                 if (node.kind === 169 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
45214                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
45215                 }
45216                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
45217                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
45218                 // of the class or interface.
45219                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
45220                 return createTypeReference(type, typeArguments);
45221             }
45222             return checkNoTypeArguments(node, symbol) ? type : errorType;
45223         }
45224         function getTypeAliasInstantiation(symbol, typeArguments) {
45225             var type = getDeclaredTypeOfSymbol(symbol);
45226             var links = getSymbolLinks(symbol);
45227             var typeParameters = links.typeParameters;
45228             var id = getTypeListId(typeArguments);
45229             var instantiation = links.instantiations.get(id);
45230             if (!instantiation) {
45231                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
45232             }
45233             return instantiation;
45234         }
45235         /**
45236          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
45237          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
45238          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
45239          */
45240         function getTypeFromTypeAliasReference(node, symbol) {
45241             var type = getDeclaredTypeOfSymbol(symbol);
45242             var typeParameters = getSymbolLinks(symbol).typeParameters;
45243             if (typeParameters) {
45244                 var numTypeArguments = ts.length(node.typeArguments);
45245                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
45246                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
45247                     error(node, minTypeArgumentCount === typeParameters.length ?
45248                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
45249                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
45250                     return errorType;
45251                 }
45252                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
45253             }
45254             return checkNoTypeArguments(node, symbol) ? type : errorType;
45255         }
45256         function getTypeReferenceName(node) {
45257             switch (node.kind) {
45258                 case 169 /* TypeReference */:
45259                     return node.typeName;
45260                 case 216 /* ExpressionWithTypeArguments */:
45261                     // We only support expressions that are simple qualified names. For other
45262                     // expressions this produces undefined.
45263                     var expr = node.expression;
45264                     if (ts.isEntityNameExpression(expr)) {
45265                         return expr;
45266                     }
45267                 // fall through;
45268             }
45269             return undefined;
45270         }
45271         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
45272             if (!typeReferenceName) {
45273                 return unknownSymbol;
45274             }
45275             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
45276         }
45277         function getTypeReferenceType(node, symbol) {
45278             if (symbol === unknownSymbol) {
45279                 return errorType;
45280             }
45281             symbol = getExpandoSymbol(symbol) || symbol;
45282             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
45283                 return getTypeFromClassOrInterfaceReference(node, symbol);
45284             }
45285             if (symbol.flags & 524288 /* TypeAlias */) {
45286                 return getTypeFromTypeAliasReference(node, symbol);
45287             }
45288             // Get type from reference to named type that cannot be generic (enum or type parameter)
45289             var res = tryGetDeclaredTypeOfSymbol(symbol);
45290             if (res) {
45291                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
45292             }
45293             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
45294                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
45295                 if (jsdocType) {
45296                     return jsdocType;
45297                 }
45298                 else {
45299                     // Resolve the type reference as a Type for the purpose of reporting errors.
45300                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
45301                     return getTypeOfSymbol(symbol);
45302                 }
45303             }
45304             return errorType;
45305         }
45306         /**
45307          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
45308          * Note: If the value is imported from commonjs, it should really be an alias,
45309          * but this function's special-case code fakes alias resolution as well.
45310          */
45311         function getTypeFromJSDocValueReference(node, symbol) {
45312             var links = getNodeLinks(node);
45313             if (!links.resolvedJSDocType) {
45314                 var valueType = getTypeOfSymbol(symbol);
45315                 var typeType = valueType;
45316                 if (symbol.valueDeclaration) {
45317                     var decl = ts.getRootDeclaration(symbol.valueDeclaration);
45318                     var isRequireAlias = false;
45319                     if (ts.isVariableDeclaration(decl) && decl.initializer) {
45320                         var expr = decl.initializer;
45321                         // skip past entity names, eg `require("x").a.b.c`
45322                         while (ts.isPropertyAccessExpression(expr)) {
45323                             expr = expr.expression;
45324                         }
45325                         isRequireAlias = ts.isCallExpression(expr) && ts.isRequireCall(expr, /*requireStringLiteralLikeArgument*/ true) && !!valueType.symbol;
45326                     }
45327                     var isImportTypeWithQualifier = node.kind === 188 /* ImportType */ && node.qualifier;
45328                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
45329                     if (valueType.symbol && (isRequireAlias || isImportTypeWithQualifier)) {
45330                         typeType = getTypeReferenceType(node, valueType.symbol);
45331                     }
45332                 }
45333                 links.resolvedJSDocType = typeType;
45334             }
45335             return links.resolvedJSDocType;
45336         }
45337         function getSubstitutionType(baseType, substitute) {
45338             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
45339                 return baseType;
45340             }
45341             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
45342             var cached = substitutionTypes.get(id);
45343             if (cached) {
45344                 return cached;
45345             }
45346             var result = createType(33554432 /* Substitution */);
45347             result.baseType = baseType;
45348             result.substitute = substitute;
45349             substitutionTypes.set(id, result);
45350             return result;
45351         }
45352         function isUnaryTupleTypeNode(node) {
45353             return node.kind === 175 /* TupleType */ && node.elementTypes.length === 1;
45354         }
45355         function getImpliedConstraint(type, checkNode, extendsNode) {
45356             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elementTypes[0], extendsNode.elementTypes[0]) :
45357                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
45358                     undefined;
45359         }
45360         function getConditionalFlowTypeOfType(type, node) {
45361             var constraints;
45362             while (node && !ts.isStatement(node) && node.kind !== 303 /* JSDocComment */) {
45363                 var parent = node.parent;
45364                 if (parent.kind === 180 /* ConditionalType */ && node === parent.trueType) {
45365                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
45366                     if (constraint) {
45367                         constraints = ts.append(constraints, constraint);
45368                     }
45369                 }
45370                 node = parent;
45371             }
45372             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
45373         }
45374         function isJSDocTypeReference(node) {
45375             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 169 /* TypeReference */ || node.kind === 188 /* ImportType */);
45376         }
45377         function checkNoTypeArguments(node, symbol) {
45378             if (node.typeArguments) {
45379                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
45380                 return false;
45381             }
45382             return true;
45383         }
45384         function getIntendedTypeFromJSDocTypeReference(node) {
45385             if (ts.isIdentifier(node.typeName)) {
45386                 var typeArgs = node.typeArguments;
45387                 switch (node.typeName.escapedText) {
45388                     case "String":
45389                         checkNoTypeArguments(node);
45390                         return stringType;
45391                     case "Number":
45392                         checkNoTypeArguments(node);
45393                         return numberType;
45394                     case "Boolean":
45395                         checkNoTypeArguments(node);
45396                         return booleanType;
45397                     case "Void":
45398                         checkNoTypeArguments(node);
45399                         return voidType;
45400                     case "Undefined":
45401                         checkNoTypeArguments(node);
45402                         return undefinedType;
45403                     case "Null":
45404                         checkNoTypeArguments(node);
45405                         return nullType;
45406                     case "Function":
45407                     case "function":
45408                         checkNoTypeArguments(node);
45409                         return globalFunctionType;
45410                     case "array":
45411                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
45412                     case "promise":
45413                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
45414                     case "Object":
45415                         if (typeArgs && typeArgs.length === 2) {
45416                             if (ts.isJSDocIndexSignature(node)) {
45417                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
45418                                 var target = getTypeFromTypeNode(typeArgs[1]);
45419                                 var index = createIndexInfo(target, /*isReadonly*/ false);
45420                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
45421                             }
45422                             return anyType;
45423                         }
45424                         checkNoTypeArguments(node);
45425                         return !noImplicitAny ? anyType : undefined;
45426                 }
45427             }
45428         }
45429         function getTypeFromJSDocNullableTypeNode(node) {
45430             var type = getTypeFromTypeNode(node.type);
45431             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
45432         }
45433         function getTypeFromTypeReference(node) {
45434             var links = getNodeLinks(node);
45435             if (!links.resolvedType) {
45436                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
45437                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
45438                     links.resolvedSymbol = unknownSymbol;
45439                     return links.resolvedType = checkExpressionCached(node.parent.expression);
45440                 }
45441                 var symbol = void 0;
45442                 var type = void 0;
45443                 var meaning = 788968 /* Type */;
45444                 if (isJSDocTypeReference(node)) {
45445                     type = getIntendedTypeFromJSDocTypeReference(node);
45446                     if (!type) {
45447                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
45448                         if (symbol === unknownSymbol) {
45449                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
45450                         }
45451                         else {
45452                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
45453                         }
45454                         type = getTypeReferenceType(node, symbol);
45455                     }
45456                 }
45457                 if (!type) {
45458                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
45459                     type = getTypeReferenceType(node, symbol);
45460                 }
45461                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
45462                 // type reference in checkTypeReferenceNode.
45463                 links.resolvedSymbol = symbol;
45464                 links.resolvedType = type;
45465             }
45466             return links.resolvedType;
45467         }
45468         function typeArgumentsFromTypeReferenceNode(node) {
45469             return ts.map(node.typeArguments, getTypeFromTypeNode);
45470         }
45471         function getTypeFromTypeQueryNode(node) {
45472             var links = getNodeLinks(node);
45473             if (!links.resolvedType) {
45474                 // TypeScript 1.0 spec (April 2014): 3.6.3
45475                 // The expression is processed as an identifier expression (section 4.3)
45476                 // or property access expression(section 4.10),
45477                 // the widened type(section 3.9) of which becomes the result.
45478                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
45479             }
45480             return links.resolvedType;
45481         }
45482         function getTypeOfGlobalSymbol(symbol, arity) {
45483             function getTypeDeclaration(symbol) {
45484                 var declarations = symbol.declarations;
45485                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
45486                     var declaration = declarations_3[_i];
45487                     switch (declaration.kind) {
45488                         case 245 /* ClassDeclaration */:
45489                         case 246 /* InterfaceDeclaration */:
45490                         case 248 /* EnumDeclaration */:
45491                             return declaration;
45492                     }
45493                 }
45494             }
45495             if (!symbol) {
45496                 return arity ? emptyGenericType : emptyObjectType;
45497             }
45498             var type = getDeclaredTypeOfSymbol(symbol);
45499             if (!(type.flags & 524288 /* Object */)) {
45500                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
45501                 return arity ? emptyGenericType : emptyObjectType;
45502             }
45503             if (ts.length(type.typeParameters) !== arity) {
45504                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
45505                 return arity ? emptyGenericType : emptyObjectType;
45506             }
45507             return type;
45508         }
45509         function getGlobalValueSymbol(name, reportErrors) {
45510             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
45511         }
45512         function getGlobalTypeSymbol(name, reportErrors) {
45513             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
45514         }
45515         function getGlobalSymbol(name, meaning, diagnostic) {
45516             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
45517             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
45518         }
45519         function getGlobalType(name, arity, reportErrors) {
45520             var symbol = getGlobalTypeSymbol(name, reportErrors);
45521             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
45522         }
45523         function getGlobalTypedPropertyDescriptorType() {
45524             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
45525         }
45526         function getGlobalTemplateStringsArrayType() {
45527             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45528         }
45529         function getGlobalImportMetaType() {
45530             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
45531         }
45532         function getGlobalESSymbolConstructorSymbol(reportErrors) {
45533             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
45534         }
45535         function getGlobalESSymbolType(reportErrors) {
45536             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
45537         }
45538         function getGlobalPromiseType(reportErrors) {
45539             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
45540         }
45541         function getGlobalPromiseLikeType(reportErrors) {
45542             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
45543         }
45544         function getGlobalPromiseConstructorSymbol(reportErrors) {
45545             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
45546         }
45547         function getGlobalPromiseConstructorLikeType(reportErrors) {
45548             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
45549         }
45550         function getGlobalAsyncIterableType(reportErrors) {
45551             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45552         }
45553         function getGlobalAsyncIteratorType(reportErrors) {
45554             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45555         }
45556         function getGlobalAsyncIterableIteratorType(reportErrors) {
45557             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45558         }
45559         function getGlobalAsyncGeneratorType(reportErrors) {
45560             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45561         }
45562         function getGlobalIterableType(reportErrors) {
45563             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
45564         }
45565         function getGlobalIteratorType(reportErrors) {
45566             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45567         }
45568         function getGlobalIterableIteratorType(reportErrors) {
45569             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
45570         }
45571         function getGlobalGeneratorType(reportErrors) {
45572             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
45573         }
45574         function getGlobalIteratorYieldResultType(reportErrors) {
45575             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45576         }
45577         function getGlobalIteratorReturnResultType(reportErrors) {
45578             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
45579         }
45580         function getGlobalTypeOrUndefined(name, arity) {
45581             if (arity === void 0) { arity = 0; }
45582             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
45583             return symbol && getTypeOfGlobalSymbol(symbol, arity);
45584         }
45585         function getGlobalExtractSymbol() {
45586             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45587         }
45588         function getGlobalOmitSymbol() {
45589             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
45590         }
45591         function getGlobalBigIntType(reportErrors) {
45592             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
45593         }
45594         /**
45595          * Instantiates a global type that is generic with some element type, and returns that instantiation.
45596          */
45597         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
45598             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
45599         }
45600         function createTypedPropertyDescriptorType(propertyType) {
45601             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
45602         }
45603         function createIterableType(iteratedType) {
45604             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
45605         }
45606         function createArrayType(elementType, readonly) {
45607             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
45608         }
45609         function getArrayOrTupleTargetType(node) {
45610             var readonly = isReadonlyTypeOperator(node.parent);
45611             if (node.kind === 174 /* ArrayType */ || node.elementTypes.length === 1 && node.elementTypes[0].kind === 177 /* RestType */) {
45612                 return readonly ? globalReadonlyArrayType : globalArrayType;
45613             }
45614             var lastElement = ts.lastOrUndefined(node.elementTypes);
45615             var restElement = lastElement && lastElement.kind === 177 /* RestType */ ? lastElement : undefined;
45616             var minLength = ts.findLastIndex(node.elementTypes, function (n) { return n.kind !== 176 /* OptionalType */ && n !== restElement; }) + 1;
45617             return getTupleTypeOfArity(node.elementTypes.length, minLength, !!restElement, readonly, /*associatedNames*/ undefined);
45618         }
45619         // Return true if the given type reference node is directly aliased or if it needs to be deferred
45620         // because it is possibly contained in a circular chain of eagerly resolved types.
45621         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
45622             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 174 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
45623                 node.kind === 175 /* TupleType */ ? ts.some(node.elementTypes, mayResolveTypeAlias) :
45624                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
45625         }
45626         // Return true when the given node is transitively contained in type constructs that eagerly
45627         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
45628         // of type aliases are eagerly resolved.
45629         function isResolvedByTypeAlias(node) {
45630             var parent = node.parent;
45631             switch (parent.kind) {
45632                 case 182 /* ParenthesizedType */:
45633                 case 169 /* TypeReference */:
45634                 case 178 /* UnionType */:
45635                 case 179 /* IntersectionType */:
45636                 case 185 /* IndexedAccessType */:
45637                 case 180 /* ConditionalType */:
45638                 case 184 /* TypeOperator */:
45639                 case 174 /* ArrayType */:
45640                 case 175 /* TupleType */:
45641                     return isResolvedByTypeAlias(parent);
45642                 case 247 /* TypeAliasDeclaration */:
45643                     return true;
45644             }
45645             return false;
45646         }
45647         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
45648         // of a type alias.
45649         function mayResolveTypeAlias(node) {
45650             switch (node.kind) {
45651                 case 169 /* TypeReference */:
45652                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
45653                 case 172 /* TypeQuery */:
45654                     return true;
45655                 case 184 /* TypeOperator */:
45656                     return node.operator !== 147 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
45657                 case 182 /* ParenthesizedType */:
45658                 case 176 /* OptionalType */:
45659                 case 299 /* JSDocOptionalType */:
45660                 case 297 /* JSDocNullableType */:
45661                 case 298 /* JSDocNonNullableType */:
45662                 case 294 /* JSDocTypeExpression */:
45663                     return mayResolveTypeAlias(node.type);
45664                 case 177 /* RestType */:
45665                     return node.type.kind !== 174 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
45666                 case 178 /* UnionType */:
45667                 case 179 /* IntersectionType */:
45668                     return ts.some(node.types, mayResolveTypeAlias);
45669                 case 185 /* IndexedAccessType */:
45670                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
45671                 case 180 /* ConditionalType */:
45672                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
45673                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
45674             }
45675             return false;
45676         }
45677         function getTypeFromArrayOrTupleTypeNode(node) {
45678             var links = getNodeLinks(node);
45679             if (!links.resolvedType) {
45680                 var target = getArrayOrTupleTargetType(node);
45681                 if (target === emptyGenericType) {
45682                     links.resolvedType = emptyObjectType;
45683                 }
45684                 else if (isDeferredTypeReferenceNode(node)) {
45685                     links.resolvedType = node.kind === 175 /* TupleType */ && node.elementTypes.length === 0 ? target :
45686                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
45687                 }
45688                 else {
45689                     var elementTypes = node.kind === 174 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elementTypes, getTypeFromTypeNode);
45690                     links.resolvedType = createTypeReference(target, elementTypes);
45691                 }
45692             }
45693             return links.resolvedType;
45694         }
45695         function isReadonlyTypeOperator(node) {
45696             return ts.isTypeOperatorNode(node) && node.operator === 138 /* ReadonlyKeyword */;
45697         }
45698         // We represent tuple types as type references to synthesized generic interface types created by
45699         // this function. The types are of the form:
45700         //
45701         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
45702         //
45703         // Note that the generic type created by this function has no symbol associated with it. The same
45704         // is true for each of the synthesized type parameters.
45705         function createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45706             var typeParameters;
45707             var properties = [];
45708             var maxLength = hasRestElement ? arity - 1 : arity;
45709             if (arity) {
45710                 typeParameters = new Array(arity);
45711                 for (var i = 0; i < arity; i++) {
45712                     var typeParameter = typeParameters[i] = createTypeParameter();
45713                     if (i < maxLength) {
45714                         var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
45715                         property.type = typeParameter;
45716                         properties.push(property);
45717                     }
45718                 }
45719             }
45720             var literalTypes = [];
45721             for (var i = minLength; i <= maxLength; i++)
45722                 literalTypes.push(getLiteralType(i));
45723             var lengthSymbol = createSymbol(4 /* Property */, "length");
45724             lengthSymbol.type = hasRestElement ? numberType : getUnionType(literalTypes);
45725             properties.push(lengthSymbol);
45726             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
45727             type.typeParameters = typeParameters;
45728             type.outerTypeParameters = undefined;
45729             type.localTypeParameters = typeParameters;
45730             type.instantiations = ts.createMap();
45731             type.instantiations.set(getTypeListId(type.typeParameters), type);
45732             type.target = type;
45733             type.resolvedTypeArguments = type.typeParameters;
45734             type.thisType = createTypeParameter();
45735             type.thisType.isThisType = true;
45736             type.thisType.constraint = type;
45737             type.declaredProperties = properties;
45738             type.declaredCallSignatures = ts.emptyArray;
45739             type.declaredConstructSignatures = ts.emptyArray;
45740             type.declaredStringIndexInfo = undefined;
45741             type.declaredNumberIndexInfo = undefined;
45742             type.minLength = minLength;
45743             type.hasRestElement = hasRestElement;
45744             type.readonly = readonly;
45745             type.associatedNames = associatedNames;
45746             return type;
45747         }
45748         function getTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames) {
45749             var key = arity + (hasRestElement ? "+" : ",") + minLength + (readonly ? "R" : "") + (associatedNames && associatedNames.length ? "," + associatedNames.join(",") : "");
45750             var type = tupleTypes.get(key);
45751             if (!type) {
45752                 tupleTypes.set(key, type = createTupleTypeOfArity(arity, minLength, hasRestElement, readonly, associatedNames));
45753             }
45754             return type;
45755         }
45756         function createTupleType(elementTypes, minLength, hasRestElement, readonly, associatedNames) {
45757             if (minLength === void 0) { minLength = elementTypes.length; }
45758             if (hasRestElement === void 0) { hasRestElement = false; }
45759             if (readonly === void 0) { readonly = false; }
45760             var arity = elementTypes.length;
45761             if (arity === 1 && hasRestElement) {
45762                 return createArrayType(elementTypes[0], readonly);
45763             }
45764             var tupleType = getTupleTypeOfArity(arity, minLength, arity > 0 && hasRestElement, readonly, associatedNames);
45765             return elementTypes.length ? createTypeReference(tupleType, elementTypes) : tupleType;
45766         }
45767         function sliceTupleType(type, index) {
45768             var tuple = type.target;
45769             if (tuple.hasRestElement) {
45770                 // don't slice off rest element
45771                 index = Math.min(index, getTypeReferenceArity(type) - 1);
45772             }
45773             return createTupleType(getTypeArguments(type).slice(index), Math.max(0, tuple.minLength - index), tuple.hasRestElement, tuple.readonly, tuple.associatedNames && tuple.associatedNames.slice(index));
45774         }
45775         function getTypeFromOptionalTypeNode(node) {
45776             var type = getTypeFromTypeNode(node.type);
45777             return strictNullChecks ? getOptionalType(type) : type;
45778         }
45779         function getTypeId(type) {
45780             return type.id;
45781         }
45782         function containsType(types, type) {
45783             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
45784         }
45785         function insertType(types, type) {
45786             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
45787             if (index < 0) {
45788                 types.splice(~index, 0, type);
45789                 return true;
45790             }
45791             return false;
45792         }
45793         function addTypeToUnion(typeSet, includes, type) {
45794             var flags = type.flags;
45795             if (flags & 1048576 /* Union */) {
45796                 return addTypesToUnion(typeSet, includes, type.types);
45797             }
45798             // We ignore 'never' types in unions
45799             if (!(flags & 131072 /* Never */)) {
45800                 includes |= flags & 71041023 /* IncludesMask */;
45801                 if (flags & 66846720 /* StructuredOrInstantiable */)
45802                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
45803                 if (type === wildcardType)
45804                     includes |= 8388608 /* IncludesWildcard */;
45805                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
45806                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
45807                         includes |= 4194304 /* IncludesNonWideningType */;
45808                 }
45809                 else {
45810                     var len = typeSet.length;
45811                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
45812                     if (index < 0) {
45813                         typeSet.splice(~index, 0, type);
45814                     }
45815                 }
45816             }
45817             return includes;
45818         }
45819         // Add the given types to the given type set. Order is preserved, duplicates are removed,
45820         // and nested types of the given kind are flattened into the set.
45821         function addTypesToUnion(typeSet, includes, types) {
45822             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
45823                 var type = types_9[_i];
45824                 includes = addTypeToUnion(typeSet, includes, type);
45825             }
45826             return includes;
45827         }
45828         function isSetOfLiteralsFromSameEnum(types) {
45829             var first = types[0];
45830             if (first.flags & 1024 /* EnumLiteral */) {
45831                 var firstEnum = getParentOfSymbol(first.symbol);
45832                 for (var i = 1; i < types.length; i++) {
45833                     var other = types[i];
45834                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
45835                         return false;
45836                     }
45837                 }
45838                 return true;
45839             }
45840             return false;
45841         }
45842         function removeSubtypes(types, primitivesOnly) {
45843             var len = types.length;
45844             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
45845                 return true;
45846             }
45847             var i = len;
45848             var count = 0;
45849             while (i > 0) {
45850                 i--;
45851                 var source = types[i];
45852                 for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
45853                     var target = types_10[_i];
45854                     if (source !== target) {
45855                         if (count === 100000) {
45856                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
45857                             // same ratio of checks per element. If the estimated number of remaining type checks is
45858                             // greater than an upper limit we deem the union type too complex to represent. The
45859                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
45860                             // caps union types at 5000 unique literal types and 1000 unique object types.
45861                             var estimatedCount = (count / (len - i)) * len;
45862                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
45863                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
45864                                 return false;
45865                             }
45866                         }
45867                         count++;
45868                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
45869                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
45870                             isTypeDerivedFrom(source, target))) {
45871                             ts.orderedRemoveItemAt(types, i);
45872                             break;
45873                         }
45874                     }
45875                 }
45876             }
45877             return true;
45878         }
45879         function removeRedundantLiteralTypes(types, includes) {
45880             var i = types.length;
45881             while (i > 0) {
45882                 i--;
45883                 var t = types[i];
45884                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
45885                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
45886                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
45887                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
45888                     isFreshLiteralType(t) && containsType(types, t.regularType);
45889                 if (remove) {
45890                     ts.orderedRemoveItemAt(types, i);
45891                 }
45892             }
45893         }
45894         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
45895         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
45896         // of other types. Subtype reduction is expensive for large union types and is possible only when union
45897         // types are known not to circularly reference themselves (as is the case with union types created by
45898         // expression constructs such as array literals and the || and ?: operators). Named types can
45899         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
45900         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
45901         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
45902             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
45903             if (types.length === 0) {
45904                 return neverType;
45905             }
45906             if (types.length === 1) {
45907                 return types[0];
45908             }
45909             var typeSet = [];
45910             var includes = addTypesToUnion(typeSet, 0, types);
45911             if (unionReduction !== 0 /* None */) {
45912                 if (includes & 3 /* AnyOrUnknown */) {
45913                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
45914                 }
45915                 switch (unionReduction) {
45916                     case 1 /* Literal */:
45917                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
45918                             removeRedundantLiteralTypes(typeSet, includes);
45919                         }
45920                         break;
45921                     case 2 /* Subtype */:
45922                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
45923                             return errorType;
45924                         }
45925                         break;
45926                 }
45927                 if (typeSet.length === 0) {
45928                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
45929                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
45930                             neverType;
45931                 }
45932             }
45933             var objectFlags = (includes & 66994211 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
45934                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
45935             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
45936         }
45937         function getUnionTypePredicate(signatures) {
45938             var first;
45939             var types = [];
45940             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
45941                 var sig = signatures_6[_i];
45942                 var pred = getTypePredicateOfSignature(sig);
45943                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
45944                     continue;
45945                 }
45946                 if (first) {
45947                     if (!typePredicateKindsMatch(first, pred)) {
45948                         // No common type predicate.
45949                         return undefined;
45950                     }
45951                 }
45952                 else {
45953                     first = pred;
45954                 }
45955                 types.push(pred.type);
45956             }
45957             if (!first) {
45958                 // No union signatures had a type predicate.
45959                 return undefined;
45960             }
45961             var unionType = getUnionType(types);
45962             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
45963         }
45964         function typePredicateKindsMatch(a, b) {
45965             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
45966         }
45967         // This function assumes the constituent type list is sorted and deduplicated.
45968         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
45969             if (types.length === 0) {
45970                 return neverType;
45971             }
45972             if (types.length === 1) {
45973                 return types[0];
45974             }
45975             var id = getTypeListId(types);
45976             var type = unionTypes.get(id);
45977             if (!type) {
45978                 type = createType(1048576 /* Union */);
45979                 unionTypes.set(id, type);
45980                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
45981                 type.types = types;
45982                 /*
45983                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
45984                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
45985                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
45986                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
45987                 */
45988                 type.aliasSymbol = aliasSymbol;
45989                 type.aliasTypeArguments = aliasTypeArguments;
45990             }
45991             return type;
45992         }
45993         function getTypeFromUnionTypeNode(node) {
45994             var links = getNodeLinks(node);
45995             if (!links.resolvedType) {
45996                 var aliasSymbol = getAliasSymbolForTypeNode(node);
45997                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
45998             }
45999             return links.resolvedType;
46000         }
46001         function addTypeToIntersection(typeSet, includes, type) {
46002             var flags = type.flags;
46003             if (flags & 2097152 /* Intersection */) {
46004                 return addTypesToIntersection(typeSet, includes, type.types);
46005             }
46006             if (isEmptyAnonymousObjectType(type)) {
46007                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
46008                     includes |= 16777216 /* IncludesEmptyObject */;
46009                     typeSet.set(type.id.toString(), type);
46010                 }
46011             }
46012             else {
46013                 if (flags & 3 /* AnyOrUnknown */) {
46014                     if (type === wildcardType)
46015                         includes |= 8388608 /* IncludesWildcard */;
46016                 }
46017                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
46018                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
46019                         // We have seen two distinct unit types which means we should reduce to an
46020                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
46021                         includes |= 67108864 /* NonPrimitive */;
46022                     }
46023                     typeSet.set(type.id.toString(), type);
46024                 }
46025                 includes |= flags & 71041023 /* IncludesMask */;
46026             }
46027             return includes;
46028         }
46029         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
46030         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
46031         function addTypesToIntersection(typeSet, includes, types) {
46032             for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
46033                 var type = types_11[_i];
46034                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
46035             }
46036             return includes;
46037         }
46038         function removeRedundantPrimitiveTypes(types, includes) {
46039             var i = types.length;
46040             while (i > 0) {
46041                 i--;
46042                 var t = types[i];
46043                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46044                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46045                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46046                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
46047                 if (remove) {
46048                     ts.orderedRemoveItemAt(types, i);
46049                 }
46050             }
46051         }
46052         // Check that the given type has a match in every union. A given type is matched by
46053         // an identical type, and a literal type is additionally matched by its corresponding
46054         // primitive type.
46055         function eachUnionContains(unionTypes, type) {
46056             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
46057                 var u = unionTypes_1[_i];
46058                 if (!containsType(u.types, type)) {
46059                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
46060                         type.flags & 256 /* NumberLiteral */ ? numberType :
46061                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
46062                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
46063                                     undefined;
46064                     if (!primitive || !containsType(u.types, primitive)) {
46065                         return false;
46066                     }
46067                 }
46068             }
46069             return true;
46070         }
46071         function extractIrreducible(types, flag) {
46072             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
46073                 for (var i = 0; i < types.length; i++) {
46074                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
46075                 }
46076                 return true;
46077             }
46078             return false;
46079         }
46080         // If the given list of types contains more than one union of primitive types, replace the
46081         // first with a union containing an intersection of those primitive types, then remove the
46082         // other unions and return true. Otherwise, do nothing and return false.
46083         function intersectUnionsOfPrimitiveTypes(types) {
46084             var unionTypes;
46085             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
46086             if (index < 0) {
46087                 return false;
46088             }
46089             var i = index + 1;
46090             // Remove all but the first union of primitive types and collect them in
46091             // the unionTypes array.
46092             while (i < types.length) {
46093                 var t = types[i];
46094                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
46095                     (unionTypes || (unionTypes = [types[index]])).push(t);
46096                     ts.orderedRemoveItemAt(types, i);
46097                 }
46098                 else {
46099                     i++;
46100                 }
46101             }
46102             // Return false if there was only one union of primitive types
46103             if (!unionTypes) {
46104                 return false;
46105             }
46106             // We have more than one union of primitive types, now intersect them. For each
46107             // type in each union we check if the type is matched in every union and if so
46108             // we include it in the result.
46109             var checked = [];
46110             var result = [];
46111             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
46112                 var u = unionTypes_2[_i];
46113                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
46114                     var t = _b[_a];
46115                     if (insertType(checked, t)) {
46116                         if (eachUnionContains(unionTypes, t)) {
46117                             insertType(result, t);
46118                         }
46119                     }
46120                 }
46121             }
46122             // Finally replace the first union with the result
46123             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
46124             return true;
46125         }
46126         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46127             var result = createType(2097152 /* Intersection */);
46128             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
46129             result.types = types;
46130             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
46131             result.aliasTypeArguments = aliasTypeArguments;
46132             return result;
46133         }
46134         // We normalize combinations of intersection and union types based on the distributive property of the '&'
46135         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
46136         // types with union type constituents into equivalent union types with intersection type constituents and
46137         // effectively ensure that union types are always at the top level in type representations.
46138         //
46139         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
46140         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
46141         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
46142         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
46143         // for intersections of types with signatures can be deterministic.
46144         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
46145             var typeMembershipMap = ts.createMap();
46146             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
46147             var typeSet = ts.arrayFrom(typeMembershipMap.values());
46148             // An intersection type is considered empty if it contains
46149             // the type never, or
46150             // more than one unit type or,
46151             // an object type and a nullable type (null or undefined), or
46152             // a string-like type and a type known to be non-string-like, or
46153             // a number-like type and a type known to be non-number-like, or
46154             // a symbol-like type and a type known to be non-symbol-like, or
46155             // a void-like type and a type known to be non-void-like, or
46156             // a non-primitive type and a type known to be primitive.
46157             if (includes & 131072 /* Never */ ||
46158                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
46159                 includes & 67108864 /* NonPrimitive */ && includes & (67238908 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
46160                 includes & 132 /* StringLike */ && includes & (67238908 /* DisjointDomains */ & ~132 /* StringLike */) ||
46161                 includes & 296 /* NumberLike */ && includes & (67238908 /* DisjointDomains */ & ~296 /* NumberLike */) ||
46162                 includes & 2112 /* BigIntLike */ && includes & (67238908 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
46163                 includes & 12288 /* ESSymbolLike */ && includes & (67238908 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
46164                 includes & 49152 /* VoidLike */ && includes & (67238908 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
46165                 return neverType;
46166             }
46167             if (includes & 1 /* Any */) {
46168                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
46169             }
46170             if (!strictNullChecks && includes & 98304 /* Nullable */) {
46171                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
46172             }
46173             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
46174                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
46175                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
46176                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
46177                 removeRedundantPrimitiveTypes(typeSet, includes);
46178             }
46179             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
46180                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
46181             }
46182             if (typeSet.length === 0) {
46183                 return unknownType;
46184             }
46185             if (typeSet.length === 1) {
46186                 return typeSet[0];
46187             }
46188             var id = getTypeListId(typeSet);
46189             var result = intersectionTypes.get(id);
46190             if (!result) {
46191                 if (includes & 1048576 /* Union */) {
46192                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
46193                         // When the intersection creates a reduced set (which might mean that *all* union types have
46194                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
46195                         // reduced we'll never reduce again, so this occurs at most once.
46196                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46197                     }
46198                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
46199                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46200                     }
46201                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
46202                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46203                     }
46204                     else {
46205                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
46206                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
46207                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
46208                         var size = ts.reduceLeft(typeSet, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : 1); }, 1);
46209                         if (size >= 100000) {
46210                             error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
46211                             return errorType;
46212                         }
46213                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
46214                         var unionType = typeSet[unionIndex_1];
46215                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46216                     }
46217                 }
46218                 else {
46219                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
46220                 }
46221                 intersectionTypes.set(id, result);
46222             }
46223             return result;
46224         }
46225         function getTypeFromIntersectionTypeNode(node) {
46226             var links = getNodeLinks(node);
46227             if (!links.resolvedType) {
46228                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46229                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
46230             }
46231             return links.resolvedType;
46232         }
46233         function createIndexType(type, stringsOnly) {
46234             var result = createType(4194304 /* Index */);
46235             result.type = type;
46236             result.stringsOnly = stringsOnly;
46237             return result;
46238         }
46239         function getIndexTypeForGenericType(type, stringsOnly) {
46240             return stringsOnly ?
46241                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
46242                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
46243         }
46244         function getLiteralTypeFromPropertyName(name) {
46245             if (ts.isPrivateIdentifier(name)) {
46246                 return neverType;
46247             }
46248             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
46249                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
46250         }
46251         function getBigIntLiteralType(node) {
46252             return getLiteralType({
46253                 negative: false,
46254                 base10Value: ts.parsePseudoBigInt(node.text)
46255             });
46256         }
46257         function getLiteralTypeFromProperty(prop, include) {
46258             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
46259                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
46260                 if (!type && !ts.isKnownSymbol(prop)) {
46261                     if (prop.escapedName === "default" /* Default */) {
46262                         type = getLiteralType("default");
46263                     }
46264                     else {
46265                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
46266                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
46267                     }
46268                 }
46269                 if (type && type.flags & include) {
46270                     return type;
46271                 }
46272             }
46273             return neverType;
46274         }
46275         function getLiteralTypeFromProperties(type, include) {
46276             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
46277         }
46278         function getNonEnumNumberIndexInfo(type) {
46279             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
46280             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
46281         }
46282         function getIndexType(type, stringsOnly, noIndexSignatures) {
46283             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
46284             type = getReducedType(type);
46285             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46286                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
46287                     maybeTypeOfKind(type, 58982400 /* InstantiableNonPrimitive */) ? getIndexTypeForGenericType(type, stringsOnly) :
46288                         ts.getObjectFlags(type) & 32 /* Mapped */ ? filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); }) :
46289                             type === wildcardType ? wildcardType :
46290                                 type.flags & 2 /* Unknown */ ? neverType :
46291                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
46292                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
46293                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
46294                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
46295                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
46296         }
46297         function getExtractStringType(type) {
46298             if (keyofStringsOnly) {
46299                 return type;
46300             }
46301             var extractTypeAlias = getGlobalExtractSymbol();
46302             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
46303         }
46304         function getIndexTypeOrString(type) {
46305             var indexType = getExtractStringType(getIndexType(type));
46306             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
46307         }
46308         function getTypeFromTypeOperatorNode(node) {
46309             var links = getNodeLinks(node);
46310             if (!links.resolvedType) {
46311                 switch (node.operator) {
46312                     case 134 /* KeyOfKeyword */:
46313                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
46314                         break;
46315                     case 147 /* UniqueKeyword */:
46316                         links.resolvedType = node.type.kind === 144 /* SymbolKeyword */
46317                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
46318                             : errorType;
46319                         break;
46320                     case 138 /* ReadonlyKeyword */:
46321                         links.resolvedType = getTypeFromTypeNode(node.type);
46322                         break;
46323                     default:
46324                         throw ts.Debug.assertNever(node.operator);
46325                 }
46326             }
46327             return links.resolvedType;
46328         }
46329         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments) {
46330             var type = createType(8388608 /* IndexedAccess */);
46331             type.objectType = objectType;
46332             type.indexType = indexType;
46333             type.aliasSymbol = aliasSymbol;
46334             type.aliasTypeArguments = aliasTypeArguments;
46335             return type;
46336         }
46337         /**
46338          * Returns if a type is or consists of a JSLiteral object type
46339          * In addition to objects which are directly literals,
46340          * * unions where every element is a jsliteral
46341          * * intersections where at least one element is a jsliteral
46342          * * and instantiable types constrained to a jsliteral
46343          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
46344          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
46345          */
46346         function isJSLiteralType(type) {
46347             if (noImplicitAny) {
46348                 return false; // Flag is meaningless under `noImplicitAny` mode
46349             }
46350             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
46351                 return true;
46352             }
46353             if (type.flags & 1048576 /* Union */) {
46354                 return ts.every(type.types, isJSLiteralType);
46355             }
46356             if (type.flags & 2097152 /* Intersection */) {
46357                 return ts.some(type.types, isJSLiteralType);
46358             }
46359             if (type.flags & 63176704 /* Instantiable */) {
46360                 return isJSLiteralType(getResolvedBaseConstraint(type));
46361             }
46362             return false;
46363         }
46364         function getPropertyNameFromIndex(indexType, accessNode) {
46365             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46366             return isTypeUsableAsPropertyName(indexType) ?
46367                 getPropertyNameFromType(indexType) :
46368                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
46369                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
46370                     accessNode && ts.isPropertyName(accessNode) ?
46371                         // late bound names are handled in the first branch, so here we only need to handle normal names
46372                         ts.getPropertyNameForPropertyNameNode(accessNode) :
46373                         undefined;
46374         }
46375         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags) {
46376             var accessExpression = accessNode && accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode : undefined;
46377             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
46378             if (propName !== undefined) {
46379                 var prop = getPropertyOfType(objectType, propName);
46380                 if (prop) {
46381                     if (accessExpression) {
46382                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 104 /* ThisKeyword */);
46383                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
46384                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
46385                             return undefined;
46386                         }
46387                         if (accessFlags & 4 /* CacheSymbol */) {
46388                             getNodeLinks(accessNode).resolvedSymbol = prop;
46389                         }
46390                     }
46391                     var propType = getTypeOfSymbol(prop);
46392                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
46393                         getFlowTypeOfReference(accessExpression, propType) :
46394                         propType;
46395                 }
46396                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
46397                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
46398                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46399                         if (isTupleType(objectType)) {
46400                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
46401                         }
46402                         else {
46403                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46404                         }
46405                     }
46406                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
46407                     return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
46408                 }
46409             }
46410             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
46411                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
46412                     return objectType;
46413                 }
46414                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
46415                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
46416                 if (indexInfo) {
46417                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
46418                         if (accessExpression) {
46419                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
46420                         }
46421                         return undefined;
46422                     }
46423                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46424                         var indexNode = getIndexNodeForAccessExpression(accessNode);
46425                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46426                         return indexInfo.type;
46427                     }
46428                     errorIfWritingToReadonlyIndex(indexInfo);
46429                     return indexInfo.type;
46430                 }
46431                 if (indexType.flags & 131072 /* Never */) {
46432                     return neverType;
46433                 }
46434                 if (isJSLiteralType(objectType)) {
46435                     return anyType;
46436                 }
46437                 if (accessExpression && !isConstEnumObjectType(objectType)) {
46438                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
46439                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
46440                     }
46441                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
46442                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
46443                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
46444                         }
46445                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
46446                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
46447                         }
46448                         else {
46449                             var suggestion = void 0;
46450                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
46451                                 if (suggestion !== undefined) {
46452                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
46453                                 }
46454                             }
46455                             else {
46456                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
46457                                 if (suggestion_1 !== undefined) {
46458                                     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);
46459                                 }
46460                                 else {
46461                                     var errorInfo = void 0;
46462                                     if (indexType.flags & 1024 /* EnumLiteral */) {
46463                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
46464                                     }
46465                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
46466                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
46467                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
46468                                     }
46469                                     else if (indexType.flags & 128 /* StringLiteral */) {
46470                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46471                                     }
46472                                     else if (indexType.flags & 256 /* NumberLiteral */) {
46473                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
46474                                     }
46475                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
46476                                         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));
46477                                     }
46478                                     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));
46479                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
46480                                 }
46481                             }
46482                         }
46483                     }
46484                     return undefined;
46485                 }
46486             }
46487             if (isJSLiteralType(objectType)) {
46488                 return anyType;
46489             }
46490             if (accessNode) {
46491                 var indexNode = getIndexNodeForAccessExpression(accessNode);
46492                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
46493                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
46494                 }
46495                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
46496                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
46497                 }
46498                 else {
46499                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
46500                 }
46501             }
46502             if (isTypeAny(indexType)) {
46503                 return indexType;
46504             }
46505             return undefined;
46506             function errorIfWritingToReadonlyIndex(indexInfo) {
46507                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
46508                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
46509                 }
46510             }
46511         }
46512         function getIndexNodeForAccessExpression(accessNode) {
46513             return accessNode.kind === 195 /* ElementAccessExpression */ ? accessNode.argumentExpression :
46514                 accessNode.kind === 185 /* IndexedAccessType */ ? accessNode.indexType :
46515                     accessNode.kind === 154 /* ComputedPropertyName */ ? accessNode.expression :
46516                         accessNode;
46517         }
46518         function isGenericObjectType(type) {
46519             if (type.flags & 3145728 /* UnionOrIntersection */) {
46520                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
46521                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
46522                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
46523                 }
46524                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
46525             }
46526             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type);
46527         }
46528         function isGenericIndexType(type) {
46529             if (type.flags & 3145728 /* UnionOrIntersection */) {
46530                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
46531                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
46532                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
46533                 }
46534                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
46535             }
46536             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */));
46537         }
46538         function isThisTypeParameter(type) {
46539             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
46540         }
46541         function getSimplifiedType(type, writing) {
46542             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
46543                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
46544                     type;
46545         }
46546         function distributeIndexOverObjectType(objectType, indexType, writing) {
46547             // (T | U)[K] -> T[K] | U[K] (reading)
46548             // (T | U)[K] -> T[K] & U[K] (writing)
46549             // (T & U)[K] -> T[K] & U[K]
46550             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
46551                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
46552                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
46553             }
46554         }
46555         function distributeObjectOverIndexType(objectType, indexType, writing) {
46556             // T[A | B] -> T[A] | T[B] (reading)
46557             // T[A | B] -> T[A] & T[B] (writing)
46558             if (indexType.flags & 1048576 /* Union */) {
46559                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
46560                 return writing ? getIntersectionType(types) : getUnionType(types);
46561             }
46562         }
46563         function unwrapSubstitution(type) {
46564             if (type.flags & 33554432 /* Substitution */) {
46565                 return type.substitute;
46566             }
46567             return type;
46568         }
46569         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
46570         // the type itself if no transformation is possible. The writing flag indicates that the type is
46571         // the target of an assignment.
46572         function getSimplifiedIndexedAccessType(type, writing) {
46573             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
46574             if (type[cache]) {
46575                 return type[cache] === circularConstraintType ? type : type[cache];
46576             }
46577             type[cache] = circularConstraintType;
46578             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
46579             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
46580             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
46581             var indexType = getSimplifiedType(type.indexType, writing);
46582             // T[A | B] -> T[A] | T[B] (reading)
46583             // T[A | B] -> T[A] & T[B] (writing)
46584             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
46585             if (distributedOverIndex) {
46586                 return type[cache] = distributedOverIndex;
46587             }
46588             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
46589             if (!(indexType.flags & 63176704 /* Instantiable */)) {
46590                 // (T | U)[K] -> T[K] | U[K] (reading)
46591                 // (T | U)[K] -> T[K] & U[K] (writing)
46592                 // (T & U)[K] -> T[K] & U[K]
46593                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
46594                 if (distributedOverObject) {
46595                     return type[cache] = distributedOverObject;
46596                 }
46597             }
46598             // So ultimately (reading):
46599             // ((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]
46600             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
46601             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
46602             // construct the type Box<T[X]>.
46603             if (isGenericMappedType(objectType)) {
46604                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
46605             }
46606             return type[cache] = type;
46607         }
46608         function getSimplifiedConditionalType(type, writing) {
46609             var checkType = type.checkType;
46610             var extendsType = type.extendsType;
46611             var trueType = getTrueTypeFromConditionalType(type);
46612             var falseType = getFalseTypeFromConditionalType(type);
46613             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
46614             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
46615                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46616                     return getSimplifiedType(trueType, writing);
46617                 }
46618                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
46619                     return neverType;
46620                 }
46621             }
46622             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
46623                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
46624                     return neverType;
46625                 }
46626                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
46627                     return getSimplifiedType(falseType, writing);
46628                 }
46629             }
46630             return type;
46631         }
46632         /**
46633          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
46634          */
46635         function isIntersectionEmpty(type1, type2) {
46636             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
46637         }
46638         function substituteIndexedMappedType(objectType, index) {
46639             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
46640             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
46641             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
46642         }
46643         function getIndexedAccessType(objectType, indexType, accessNode, aliasSymbol, aliasTypeArguments) {
46644             return getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, 0 /* None */, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
46645         }
46646         function getIndexedAccessTypeOrUndefined(objectType, indexType, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
46647             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
46648             if (objectType === wildcardType || indexType === wildcardType) {
46649                 return wildcardType;
46650             }
46651             // If the object type has a string index signature and no other members we know that the result will
46652             // always be the type of that index signature and we can simplify accordingly.
46653             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
46654                 indexType = stringType;
46655             }
46656             // If the index type is generic, or if the object type is generic and doesn't originate in an expression,
46657             // we are performing a higher-order index access where we cannot meaningfully access the properties of the
46658             // object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
46659             // an expression. This is to preserve backwards compatibility. For example, an element access 'this["foo"]'
46660             // has always been resolved eagerly using the constraint type of 'this' at the given location.
46661             if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind !== 185 /* IndexedAccessType */) && isGenericObjectType(objectType)) {
46662                 if (objectType.flags & 3 /* AnyOrUnknown */) {
46663                     return objectType;
46664                 }
46665                 // Defer the operation by creating an indexed access type.
46666                 var id = objectType.id + "," + indexType.id;
46667                 var type = indexedAccessTypes.get(id);
46668                 if (!type) {
46669                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments));
46670                 }
46671                 return type;
46672             }
46673             // In the following we resolve T[K] to the type of the property in T selected by K.
46674             // We treat boolean as different from other unions to improve errors;
46675             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
46676             var apparentObjectType = getReducedApparentType(objectType);
46677             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
46678                 var propTypes = [];
46679                 var wasMissingProp = false;
46680                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
46681                     var t = _a[_i];
46682                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags);
46683                     if (propType) {
46684                         propTypes.push(propType);
46685                     }
46686                     else if (!accessNode) {
46687                         // If there's no error node, we can immeditely stop, since error reporting is off
46688                         return undefined;
46689                     }
46690                     else {
46691                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
46692                         wasMissingProp = true;
46693                     }
46694                 }
46695                 if (wasMissingProp) {
46696                     return undefined;
46697                 }
46698                 return accessFlags & 2 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
46699             }
46700             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */);
46701         }
46702         function getTypeFromIndexedAccessTypeNode(node) {
46703             var links = getNodeLinks(node);
46704             if (!links.resolvedType) {
46705                 var objectType = getTypeFromTypeNode(node.objectType);
46706                 var indexType = getTypeFromTypeNode(node.indexType);
46707                 var potentialAlias = getAliasSymbolForTypeNode(node);
46708                 var resolved = getIndexedAccessType(objectType, indexType, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
46709                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
46710                     resolved.objectType === objectType &&
46711                     resolved.indexType === indexType ?
46712                     getConditionalFlowTypeOfType(resolved, node) : resolved;
46713             }
46714             return links.resolvedType;
46715         }
46716         function getTypeFromMappedTypeNode(node) {
46717             var links = getNodeLinks(node);
46718             if (!links.resolvedType) {
46719                 var type = createObjectType(32 /* Mapped */, node.symbol);
46720                 type.declaration = node;
46721                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
46722                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
46723                 links.resolvedType = type;
46724                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
46725                 // references itself through one or more type aliases.
46726                 getConstraintTypeFromMappedType(type);
46727             }
46728             return links.resolvedType;
46729         }
46730         function getActualTypeVariable(type) {
46731             if (type.flags & 33554432 /* Substitution */) {
46732                 return type.baseType;
46733             }
46734             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
46735                 type.indexType.flags & 33554432 /* Substitution */)) {
46736                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
46737             }
46738             return type;
46739         }
46740         function getConditionalType(root, mapper) {
46741             var result;
46742             var extraTypes;
46743             var _loop_12 = function () {
46744                 var checkType = instantiateType(root.checkType, mapper);
46745                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
46746                 var extendsType = instantiateType(root.extendsType, mapper);
46747                 if (checkType === wildcardType || extendsType === wildcardType) {
46748                     return { value: wildcardType };
46749                 }
46750                 var combinedMapper = void 0;
46751                 if (root.inferTypeParameters) {
46752                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
46753                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
46754                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
46755                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
46756                     // so in those cases we refain from performing inference and retain the uninfered type parameter
46757                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
46758                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
46759                         // conditional type instead of deferring resolution. Also, we always want strict function
46760                         // types rules (i.e. proper contravariance) for inferences.
46761                         inferTypes(context.inferences, checkType, extendsType, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
46762                     }
46763                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
46764                 }
46765                 // Instantiate the extends type including inferences for 'infer T' type parameters
46766                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
46767                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
46768                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
46769                     // Return falseType for a definitely false extends check. We check an instantiations of the two
46770                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
46771                     // possible (the wildcard type is assignable to and from all types). If those are not related,
46772                     // then no instantiations will be and we can just return the false branch type.
46773                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
46774                         // Return union of trueType and falseType for 'any' since it matches anything
46775                         if (checkType.flags & 1 /* Any */) {
46776                             (extraTypes || (extraTypes = [])).push(instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper));
46777                         }
46778                         // If falseType is an immediately nested conditional type that isn't distributive or has an
46779                         // identical checkType, switch to that type and loop.
46780                         var falseType_1 = root.falseType;
46781                         if (falseType_1.flags & 16777216 /* Conditional */) {
46782                             var newRoot = falseType_1.root;
46783                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
46784                                 root = newRoot;
46785                                 return "continue";
46786                             }
46787                         }
46788                         result = instantiateTypeWithoutDepthIncrease(falseType_1, mapper);
46789                         return "break";
46790                     }
46791                     // Return trueType for a definitely true extends check. We check instantiations of the two
46792                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
46793                     // that has no constraint. This ensures that, for example, the type
46794                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
46795                     // doesn't immediately resolve to 'string' instead of being deferred.
46796                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
46797                         result = instantiateTypeWithoutDepthIncrease(root.trueType, combinedMapper || mapper);
46798                         return "break";
46799                     }
46800                 }
46801                 // Return a deferred type for a check that is neither definitely true nor definitely false
46802                 var erasedCheckType = getActualTypeVariable(checkType);
46803                 result = createType(16777216 /* Conditional */);
46804                 result.root = root;
46805                 result.checkType = erasedCheckType;
46806                 result.extendsType = extendsType;
46807                 result.mapper = mapper;
46808                 result.combinedMapper = combinedMapper;
46809                 result.aliasSymbol = root.aliasSymbol;
46810                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
46811                 return "break";
46812             };
46813             // We loop here for an immediately nested conditional type in the false position, effectively treating
46814             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
46815             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
46816             while (true) {
46817                 var state_4 = _loop_12();
46818                 if (typeof state_4 === "object")
46819                     return state_4.value;
46820                 if (state_4 === "break")
46821                     break;
46822             }
46823             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
46824         }
46825         function getTrueTypeFromConditionalType(type) {
46826             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper));
46827         }
46828         function getFalseTypeFromConditionalType(type) {
46829             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper));
46830         }
46831         function getInferredTrueTypeFromConditionalType(type) {
46832             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(type.root.trueType, type.combinedMapper) : getTrueTypeFromConditionalType(type));
46833         }
46834         function getInferTypeParameters(node) {
46835             var result;
46836             if (node.locals) {
46837                 node.locals.forEach(function (symbol) {
46838                     if (symbol.flags & 262144 /* TypeParameter */) {
46839                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
46840                     }
46841                 });
46842             }
46843             return result;
46844         }
46845         function getTypeFromConditionalTypeNode(node) {
46846             var links = getNodeLinks(node);
46847             if (!links.resolvedType) {
46848                 var checkType = getTypeFromTypeNode(node.checkType);
46849                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46850                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46851                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
46852                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
46853                 var root = {
46854                     node: node,
46855                     checkType: checkType,
46856                     extendsType: getTypeFromTypeNode(node.extendsType),
46857                     trueType: getTypeFromTypeNode(node.trueType),
46858                     falseType: getTypeFromTypeNode(node.falseType),
46859                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
46860                     inferTypeParameters: getInferTypeParameters(node),
46861                     outerTypeParameters: outerTypeParameters,
46862                     instantiations: undefined,
46863                     aliasSymbol: aliasSymbol,
46864                     aliasTypeArguments: aliasTypeArguments
46865                 };
46866                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
46867                 if (outerTypeParameters) {
46868                     root.instantiations = ts.createMap();
46869                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
46870                 }
46871             }
46872             return links.resolvedType;
46873         }
46874         function getTypeFromInferTypeNode(node) {
46875             var links = getNodeLinks(node);
46876             if (!links.resolvedType) {
46877                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
46878             }
46879             return links.resolvedType;
46880         }
46881         function getIdentifierChain(node) {
46882             if (ts.isIdentifier(node)) {
46883                 return [node];
46884             }
46885             else {
46886                 return ts.append(getIdentifierChain(node.left), node.right);
46887             }
46888         }
46889         function getTypeFromImportTypeNode(node) {
46890             var links = getNodeLinks(node);
46891             if (!links.resolvedType) {
46892                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
46893                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
46894                     links.resolvedSymbol = unknownSymbol;
46895                     return links.resolvedType = errorType;
46896                 }
46897                 if (!ts.isLiteralImportTypeNode(node)) {
46898                     error(node.argument, ts.Diagnostics.String_literal_expected);
46899                     links.resolvedSymbol = unknownSymbol;
46900                     return links.resolvedType = errorType;
46901                 }
46902                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
46903                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
46904                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
46905                 if (!innerModuleSymbol) {
46906                     links.resolvedSymbol = unknownSymbol;
46907                     return links.resolvedType = errorType;
46908                 }
46909                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
46910                 if (!ts.nodeIsMissing(node.qualifier)) {
46911                     var nameStack = getIdentifierChain(node.qualifier);
46912                     var currentNamespace = moduleSymbol;
46913                     var current = void 0;
46914                     while (current = nameStack.shift()) {
46915                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
46916                         var next = getSymbol(getExportsOfSymbol(getMergedSymbol(resolveSymbol(currentNamespace))), current.escapedText, meaning);
46917                         if (!next) {
46918                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
46919                             return links.resolvedType = errorType;
46920                         }
46921                         getNodeLinks(current).resolvedSymbol = next;
46922                         getNodeLinks(current.parent).resolvedSymbol = next;
46923                         currentNamespace = next;
46924                     }
46925                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
46926                 }
46927                 else {
46928                     if (moduleSymbol.flags & targetMeaning) {
46929                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
46930                     }
46931                     else {
46932                         var errorMessage = targetMeaning === 111551 /* Value */
46933                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
46934                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
46935                         error(node, errorMessage, node.argument.literal.text);
46936                         links.resolvedSymbol = unknownSymbol;
46937                         links.resolvedType = errorType;
46938                     }
46939                 }
46940             }
46941             return links.resolvedType;
46942         }
46943         function resolveImportSymbolType(node, links, symbol, meaning) {
46944             var resolvedSymbol = resolveSymbol(symbol);
46945             links.resolvedSymbol = resolvedSymbol;
46946             if (meaning === 111551 /* Value */) {
46947                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
46948             }
46949             else {
46950                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
46951             }
46952         }
46953         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
46954             var links = getNodeLinks(node);
46955             if (!links.resolvedType) {
46956                 // Deferred resolution of members is handled by resolveObjectTypeMembers
46957                 var aliasSymbol = getAliasSymbolForTypeNode(node);
46958                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
46959                     links.resolvedType = emptyTypeLiteralType;
46960                 }
46961                 else {
46962                     var type = createObjectType(16 /* Anonymous */, node.symbol);
46963                     type.aliasSymbol = aliasSymbol;
46964                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
46965                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
46966                         type = createArrayType(type);
46967                     }
46968                     links.resolvedType = type;
46969                 }
46970             }
46971             return links.resolvedType;
46972         }
46973         function getAliasSymbolForTypeNode(node) {
46974             var host = node.parent;
46975             while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 138 /* ReadonlyKeyword */) {
46976                 host = host.parent;
46977             }
46978             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
46979         }
46980         function getTypeArgumentsForAliasSymbol(symbol) {
46981             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
46982         }
46983         function isNonGenericObjectType(type) {
46984             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
46985         }
46986         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
46987             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
46988         }
46989         function isSinglePropertyAnonymousObjectType(type) {
46990             return !!(type.flags & 524288 /* Object */) &&
46991                 !!(ts.getObjectFlags(type) & 16 /* Anonymous */) &&
46992                 (ts.length(getPropertiesOfType(type)) === 1 || ts.every(getPropertiesOfType(type), function (p) { return !!(p.flags & 16777216 /* Optional */); }));
46993         }
46994         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
46995             if (type.types.length === 2) {
46996                 var firstType = type.types[0];
46997                 var secondType = type.types[1];
46998                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
46999                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
47000                 }
47001                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType) && isSinglePropertyAnonymousObjectType(secondType)) {
47002                     return getAnonymousPartialType(secondType);
47003                 }
47004                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType) && isSinglePropertyAnonymousObjectType(firstType)) {
47005                     return getAnonymousPartialType(firstType);
47006                 }
47007             }
47008             function getAnonymousPartialType(type) {
47009                 // gets the type as if it had been spread, but where everything in the spread is made optional
47010                 var members = ts.createSymbolTable();
47011                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
47012                     var prop = _a[_i];
47013                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
47014                         // do nothing, skip privates
47015                     }
47016                     else if (isSpreadableProperty(prop)) {
47017                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47018                         var flags = 4 /* Property */ | 16777216 /* Optional */;
47019                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47020                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47021                         result.declarations = prop.declarations;
47022                         result.nameType = getSymbolLinks(prop).nameType;
47023                         result.syntheticOrigin = prop;
47024                         members.set(prop.escapedName, result);
47025                     }
47026                 }
47027                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
47028                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
47029                 return spread;
47030             }
47031         }
47032         /**
47033          * Since the source of spread types are object literals, which are not binary,
47034          * this function should be called in a left folding style, with left = previous result of getSpreadType
47035          * and right = the new element to be spread.
47036          */
47037         function getSpreadType(left, right, symbol, objectFlags, readonly) {
47038             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
47039                 return anyType;
47040             }
47041             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
47042                 return unknownType;
47043             }
47044             if (left.flags & 131072 /* Never */) {
47045                 return right;
47046             }
47047             if (right.flags & 131072 /* Never */) {
47048                 return left;
47049             }
47050             if (left.flags & 1048576 /* Union */) {
47051                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
47052                 if (merged) {
47053                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
47054                 }
47055                 return mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); });
47056             }
47057             if (right.flags & 1048576 /* Union */) {
47058                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
47059                 if (merged) {
47060                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
47061                 }
47062                 return mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); });
47063             }
47064             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
47065                 return left;
47066             }
47067             if (isGenericObjectType(left) || isGenericObjectType(right)) {
47068                 if (isEmptyObjectType(left)) {
47069                     return right;
47070                 }
47071                 // When the left type is an intersection, we may need to merge the last constituent of the
47072                 // intersection with the right type. For example when the left type is 'T & { a: string }'
47073                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
47074                 if (left.flags & 2097152 /* Intersection */) {
47075                     var types = left.types;
47076                     var lastLeft = types[types.length - 1];
47077                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
47078                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
47079                     }
47080                 }
47081                 return getIntersectionType([left, right]);
47082             }
47083             var members = ts.createSymbolTable();
47084             var skippedPrivateMembers = ts.createUnderscoreEscapedMap();
47085             var stringIndexInfo;
47086             var numberIndexInfo;
47087             if (left === emptyObjectType) {
47088                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
47089                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
47090                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
47091             }
47092             else {
47093                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
47094                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
47095             }
47096             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
47097                 var rightProp = _a[_i];
47098                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
47099                     skippedPrivateMembers.set(rightProp.escapedName, true);
47100                 }
47101                 else if (isSpreadableProperty(rightProp)) {
47102                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
47103                 }
47104             }
47105             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
47106                 var leftProp = _c[_b];
47107                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
47108                     continue;
47109                 }
47110                 if (members.has(leftProp.escapedName)) {
47111                     var rightProp = members.get(leftProp.escapedName);
47112                     var rightType = getTypeOfSymbol(rightProp);
47113                     if (rightProp.flags & 16777216 /* Optional */) {
47114                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
47115                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
47116                         var result = createSymbol(flags, leftProp.escapedName);
47117                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
47118                         result.leftSpread = leftProp;
47119                         result.rightSpread = rightProp;
47120                         result.declarations = declarations;
47121                         result.nameType = getSymbolLinks(leftProp).nameType;
47122                         members.set(leftProp.escapedName, result);
47123                     }
47124                 }
47125                 else {
47126                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
47127                 }
47128             }
47129             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
47130             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
47131             return spread;
47132         }
47133         /** We approximate own properties as non-methods plus methods that are inside the object literal */
47134         function isSpreadableProperty(prop) {
47135             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
47136                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
47137                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
47138         }
47139         function getSpreadSymbol(prop, readonly) {
47140             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
47141             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
47142                 return prop;
47143             }
47144             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
47145             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
47146             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
47147             result.declarations = prop.declarations;
47148             result.nameType = getSymbolLinks(prop).nameType;
47149             result.syntheticOrigin = prop;
47150             return result;
47151         }
47152         function getIndexInfoWithReadonly(info, readonly) {
47153             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
47154         }
47155         function createLiteralType(flags, value, symbol) {
47156             var type = createType(flags);
47157             type.symbol = symbol;
47158             type.value = value;
47159             return type;
47160         }
47161         function getFreshTypeOfLiteralType(type) {
47162             if (type.flags & 2944 /* Literal */) {
47163                 if (!type.freshType) {
47164                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
47165                     freshType.regularType = type;
47166                     freshType.freshType = freshType;
47167                     type.freshType = freshType;
47168                 }
47169                 return type.freshType;
47170             }
47171             return type;
47172         }
47173         function getRegularTypeOfLiteralType(type) {
47174             return type.flags & 2944 /* Literal */ ? type.regularType :
47175                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
47176                     type;
47177         }
47178         function isFreshLiteralType(type) {
47179             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
47180         }
47181         function getLiteralType(value, enumId, symbol) {
47182             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
47183             // where NNN is the text representation of a numeric literal and SSS are the characters
47184             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
47185             // EEE is a unique id for the containing enum type.
47186             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
47187             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
47188             var type = literalTypes.get(key);
47189             if (!type) {
47190                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
47191                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
47192                     (enumId ? 1024 /* EnumLiteral */ : 0);
47193                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
47194                 type.regularType = type;
47195             }
47196             return type;
47197         }
47198         function getTypeFromLiteralTypeNode(node) {
47199             var links = getNodeLinks(node);
47200             if (!links.resolvedType) {
47201                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
47202             }
47203             return links.resolvedType;
47204         }
47205         function createUniqueESSymbolType(symbol) {
47206             var type = createType(8192 /* UniqueESSymbol */);
47207             type.symbol = symbol;
47208             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
47209             return type;
47210         }
47211         function getESSymbolLikeTypeForNode(node) {
47212             if (ts.isValidESSymbolDeclaration(node)) {
47213                 var symbol = getSymbolOfNode(node);
47214                 var links = getSymbolLinks(symbol);
47215                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
47216             }
47217             return esSymbolType;
47218         }
47219         function getThisType(node) {
47220             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
47221             var parent = container && container.parent;
47222             if (parent && (ts.isClassLike(parent) || parent.kind === 246 /* InterfaceDeclaration */)) {
47223                 if (!ts.hasModifier(container, 32 /* Static */) &&
47224                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
47225                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
47226                 }
47227             }
47228             // inside x.prototype = { ... }
47229             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
47230                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
47231             }
47232             // /** @return {this} */
47233             // x.prototype.m = function() { ... }
47234             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
47235             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
47236                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
47237             }
47238             // inside constructor function C() { ... }
47239             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
47240                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
47241             }
47242             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
47243             return errorType;
47244         }
47245         function getTypeFromThisTypeNode(node) {
47246             var links = getNodeLinks(node);
47247             if (!links.resolvedType) {
47248                 links.resolvedType = getThisType(node);
47249             }
47250             return links.resolvedType;
47251         }
47252         function getTypeFromTypeNode(node) {
47253             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
47254         }
47255         function getTypeFromTypeNodeWorker(node) {
47256             switch (node.kind) {
47257                 case 125 /* AnyKeyword */:
47258                 case 295 /* JSDocAllType */:
47259                 case 296 /* JSDocUnknownType */:
47260                     return anyType;
47261                 case 148 /* UnknownKeyword */:
47262                     return unknownType;
47263                 case 143 /* StringKeyword */:
47264                     return stringType;
47265                 case 140 /* NumberKeyword */:
47266                     return numberType;
47267                 case 151 /* BigIntKeyword */:
47268                     return bigintType;
47269                 case 128 /* BooleanKeyword */:
47270                     return booleanType;
47271                 case 144 /* SymbolKeyword */:
47272                     return esSymbolType;
47273                 case 110 /* VoidKeyword */:
47274                     return voidType;
47275                 case 146 /* UndefinedKeyword */:
47276                     return undefinedType;
47277                 case 100 /* NullKeyword */:
47278                     return nullType;
47279                 case 137 /* NeverKeyword */:
47280                     return neverType;
47281                 case 141 /* ObjectKeyword */:
47282                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
47283                 case 183 /* ThisType */:
47284                 case 104 /* ThisKeyword */:
47285                     return getTypeFromThisTypeNode(node);
47286                 case 187 /* LiteralType */:
47287                     return getTypeFromLiteralTypeNode(node);
47288                 case 169 /* TypeReference */:
47289                     return getTypeFromTypeReference(node);
47290                 case 168 /* TypePredicate */:
47291                     return node.assertsModifier ? voidType : booleanType;
47292                 case 216 /* ExpressionWithTypeArguments */:
47293                     return getTypeFromTypeReference(node);
47294                 case 172 /* TypeQuery */:
47295                     return getTypeFromTypeQueryNode(node);
47296                 case 174 /* ArrayType */:
47297                 case 175 /* TupleType */:
47298                     return getTypeFromArrayOrTupleTypeNode(node);
47299                 case 176 /* OptionalType */:
47300                     return getTypeFromOptionalTypeNode(node);
47301                 case 178 /* UnionType */:
47302                     return getTypeFromUnionTypeNode(node);
47303                 case 179 /* IntersectionType */:
47304                     return getTypeFromIntersectionTypeNode(node);
47305                 case 297 /* JSDocNullableType */:
47306                     return getTypeFromJSDocNullableTypeNode(node);
47307                 case 299 /* JSDocOptionalType */:
47308                     return addOptionality(getTypeFromTypeNode(node.type));
47309                 case 182 /* ParenthesizedType */:
47310                 case 298 /* JSDocNonNullableType */:
47311                 case 294 /* JSDocTypeExpression */:
47312                     return getTypeFromTypeNode(node.type);
47313                 case 177 /* RestType */:
47314                     return getElementTypeOfArrayType(getTypeFromTypeNode(node.type)) || errorType;
47315                 case 301 /* JSDocVariadicType */:
47316                     return getTypeFromJSDocVariadicType(node);
47317                 case 170 /* FunctionType */:
47318                 case 171 /* ConstructorType */:
47319                 case 173 /* TypeLiteral */:
47320                 case 304 /* JSDocTypeLiteral */:
47321                 case 300 /* JSDocFunctionType */:
47322                 case 305 /* JSDocSignature */:
47323                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
47324                 case 184 /* TypeOperator */:
47325                     return getTypeFromTypeOperatorNode(node);
47326                 case 185 /* IndexedAccessType */:
47327                     return getTypeFromIndexedAccessTypeNode(node);
47328                 case 186 /* MappedType */:
47329                     return getTypeFromMappedTypeNode(node);
47330                 case 180 /* ConditionalType */:
47331                     return getTypeFromConditionalTypeNode(node);
47332                 case 181 /* InferType */:
47333                     return getTypeFromInferTypeNode(node);
47334                 case 188 /* ImportType */:
47335                     return getTypeFromImportTypeNode(node);
47336                 // This function assumes that an identifier or qualified name is a type expression
47337                 // Callers should first ensure this by calling isTypeNode
47338                 case 75 /* Identifier */:
47339                 case 153 /* QualifiedName */:
47340                     var symbol = getSymbolAtLocation(node);
47341                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
47342                 default:
47343                     return errorType;
47344             }
47345         }
47346         function instantiateList(items, mapper, instantiator) {
47347             if (items && items.length) {
47348                 for (var i = 0; i < items.length; i++) {
47349                     var item = items[i];
47350                     var mapped = instantiator(item, mapper);
47351                     if (item !== mapped) {
47352                         var result = i === 0 ? [] : items.slice(0, i);
47353                         result.push(mapped);
47354                         for (i++; i < items.length; i++) {
47355                             result.push(instantiator(items[i], mapper));
47356                         }
47357                         return result;
47358                     }
47359                 }
47360             }
47361             return items;
47362         }
47363         function instantiateTypes(types, mapper) {
47364             return instantiateList(types, mapper, instantiateType);
47365         }
47366         function instantiateSignatures(signatures, mapper) {
47367             return instantiateList(signatures, mapper, instantiateSignature);
47368         }
47369         function createTypeMapper(sources, targets) {
47370             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
47371         }
47372         function getMappedType(type, mapper) {
47373             switch (mapper.kind) {
47374                 case 0 /* Simple */:
47375                     return type === mapper.source ? mapper.target : type;
47376                 case 1 /* Array */:
47377                     var sources = mapper.sources;
47378                     var targets = mapper.targets;
47379                     for (var i = 0; i < sources.length; i++) {
47380                         if (type === sources[i]) {
47381                             return targets ? targets[i] : anyType;
47382                         }
47383                     }
47384                     return type;
47385                 case 2 /* Function */:
47386                     return mapper.func(type);
47387                 case 3 /* Composite */:
47388                 case 4 /* Merged */:
47389                     var t1 = getMappedType(type, mapper.mapper1);
47390                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
47391             }
47392         }
47393         function makeUnaryTypeMapper(source, target) {
47394             return { kind: 0 /* Simple */, source: source, target: target };
47395         }
47396         function makeArrayTypeMapper(sources, targets) {
47397             return { kind: 1 /* Array */, sources: sources, targets: targets };
47398         }
47399         function makeFunctionTypeMapper(func) {
47400             return { kind: 2 /* Function */, func: func };
47401         }
47402         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
47403             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
47404         }
47405         function createTypeEraser(sources) {
47406             return createTypeMapper(sources, /*targets*/ undefined);
47407         }
47408         /**
47409          * Maps forward-references to later types parameters to the empty object type.
47410          * This is used during inference when instantiating type parameter defaults.
47411          */
47412         function createBackreferenceMapper(context, index) {
47413             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
47414         }
47415         function combineTypeMappers(mapper1, mapper2) {
47416             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
47417         }
47418         function mergeTypeMappers(mapper1, mapper2) {
47419             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
47420         }
47421         function prependTypeMapping(source, target, mapper) {
47422             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
47423         }
47424         function appendTypeMapping(mapper, source, target) {
47425             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
47426         }
47427         function getRestrictiveTypeParameter(tp) {
47428             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
47429                 tp.restrictiveInstantiation.constraint = unknownType,
47430                 tp.restrictiveInstantiation);
47431         }
47432         function cloneTypeParameter(typeParameter) {
47433             var result = createTypeParameter(typeParameter.symbol);
47434             result.target = typeParameter;
47435             return result;
47436         }
47437         function instantiateTypePredicate(predicate, mapper) {
47438             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
47439         }
47440         function instantiateSignature(signature, mapper, eraseTypeParameters) {
47441             var freshTypeParameters;
47442             if (signature.typeParameters && !eraseTypeParameters) {
47443                 // First create a fresh set of type parameters, then include a mapping from the old to the
47444                 // new type parameters in the mapper function. Finally store this mapper in the new type
47445                 // parameters such that we can use it when instantiating constraints.
47446                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
47447                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
47448                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
47449                     var tp = freshTypeParameters_1[_i];
47450                     tp.mapper = mapper;
47451                 }
47452             }
47453             // Don't compute resolvedReturnType and resolvedTypePredicate now,
47454             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
47455             // See GH#17600.
47456             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
47457             /*resolvedReturnType*/ undefined, 
47458             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */);
47459             result.target = signature;
47460             result.mapper = mapper;
47461             return result;
47462         }
47463         function instantiateSymbol(symbol, mapper) {
47464             var links = getSymbolLinks(symbol);
47465             if (links.type && !couldContainTypeVariables(links.type)) {
47466                 // If the type of the symbol is already resolved, and if that type could not possibly
47467                 // be affected by instantiation, simply return the symbol itself.
47468                 return symbol;
47469             }
47470             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
47471                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
47472                 // type mappers. This ensures that original type identities are properly preserved and that aliases
47473                 // always reference a non-aliases.
47474                 symbol = links.target;
47475                 mapper = combineTypeMappers(links.mapper, mapper);
47476             }
47477             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
47478             // also transient so that we can just store data on it directly.
47479             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
47480             result.declarations = symbol.declarations;
47481             result.parent = symbol.parent;
47482             result.target = symbol;
47483             result.mapper = mapper;
47484             if (symbol.valueDeclaration) {
47485                 result.valueDeclaration = symbol.valueDeclaration;
47486             }
47487             if (links.nameType) {
47488                 result.nameType = links.nameType;
47489             }
47490             return result;
47491         }
47492         function getObjectTypeInstantiation(type, mapper) {
47493             var target = type.objectFlags & 64 /* Instantiated */ ? type.target : type;
47494             var node = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
47495             var links = getNodeLinks(node);
47496             var typeParameters = links.outerTypeParameters;
47497             if (!typeParameters) {
47498                 // The first time an anonymous type is instantiated we compute and store a list of the type
47499                 // parameters that are in scope (and therefore potentially referenced). For type literals that
47500                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
47501                 // set of type parameters to those that are possibly referenced in the literal.
47502                 var declaration_1 = node;
47503                 if (ts.isInJSFile(declaration_1)) {
47504                     var paramTag = ts.findAncestor(declaration_1, ts.isJSDocParameterTag);
47505                     if (paramTag) {
47506                         var paramSymbol = ts.getParameterSymbolFromJSDoc(paramTag);
47507                         if (paramSymbol) {
47508                             declaration_1 = paramSymbol.valueDeclaration;
47509                         }
47510                     }
47511                 }
47512                 var outerTypeParameters = getOuterTypeParameters(declaration_1, /*includeThisTypes*/ true);
47513                 if (isJSConstructor(declaration_1)) {
47514                     var templateTagParameters = getTypeParametersFromDeclaration(declaration_1);
47515                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
47516                 }
47517                 typeParameters = outerTypeParameters || ts.emptyArray;
47518                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
47519                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration_1); }) :
47520                     typeParameters;
47521                 links.outerTypeParameters = typeParameters;
47522                 if (typeParameters.length) {
47523                     links.instantiations = ts.createMap();
47524                     links.instantiations.set(getTypeListId(typeParameters), target);
47525                 }
47526             }
47527             if (typeParameters.length) {
47528                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
47529                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47530                 // instantiation cache key from the type IDs of the type arguments.
47531                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
47532                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
47533                 var id = getTypeListId(typeArguments);
47534                 var result = links.instantiations.get(id);
47535                 if (!result) {
47536                     var newMapper = createTypeMapper(typeParameters, typeArguments);
47537                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
47538                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
47539                             instantiateAnonymousType(target, newMapper);
47540                     links.instantiations.set(id, result);
47541                 }
47542                 return result;
47543             }
47544             return type;
47545         }
47546         function maybeTypeParameterReference(node) {
47547             return !(node.kind === 153 /* QualifiedName */ ||
47548                 node.parent.kind === 169 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
47549                 node.parent.kind === 188 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
47550         }
47551         function isTypeParameterPossiblyReferenced(tp, node) {
47552             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
47553             // between the node and the type parameter declaration, if the node contains actual references to the
47554             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
47555             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
47556                 var container = tp.symbol.declarations[0].parent;
47557                 for (var n = node; n !== container; n = n.parent) {
47558                     if (!n || n.kind === 223 /* Block */ || n.kind === 180 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
47559                         return true;
47560                     }
47561                 }
47562                 return !!ts.forEachChild(node, containsReference);
47563             }
47564             return true;
47565             function containsReference(node) {
47566                 switch (node.kind) {
47567                     case 183 /* ThisType */:
47568                         return !!tp.isThisType;
47569                     case 75 /* Identifier */:
47570                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
47571                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
47572                     case 172 /* TypeQuery */:
47573                         return true;
47574                 }
47575                 return !!ts.forEachChild(node, containsReference);
47576             }
47577         }
47578         function getHomomorphicTypeVariable(type) {
47579             var constraintType = getConstraintTypeFromMappedType(type);
47580             if (constraintType.flags & 4194304 /* Index */) {
47581                 var typeVariable = getActualTypeVariable(constraintType.type);
47582                 if (typeVariable.flags & 262144 /* TypeParameter */) {
47583                     return typeVariable;
47584                 }
47585             }
47586             return undefined;
47587         }
47588         function instantiateMappedType(type, mapper) {
47589             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
47590             // operation depends on T as follows:
47591             // * If T is a primitive type no mapping is performed and the result is simply T.
47592             // * If T is a union type we distribute the mapped type over the union.
47593             // * If T is an array we map to an array where the element type has been transformed.
47594             // * If T is a tuple we map to a tuple where the element types have been transformed.
47595             // * Otherwise we map to an object type where the type of each property has been transformed.
47596             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
47597             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
47598             // { [P in keyof A]: X } | undefined.
47599             var typeVariable = getHomomorphicTypeVariable(type);
47600             if (typeVariable) {
47601                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
47602                 if (typeVariable !== mappedTypeVariable) {
47603                     return mapType(getReducedType(mappedTypeVariable), function (t) {
47604                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
47605                             var replacementMapper = prependTypeMapping(typeVariable, t, mapper);
47606                             return isArrayType(t) ? instantiateMappedArrayType(t, type, replacementMapper) :
47607                                 isTupleType(t) ? instantiateMappedTupleType(t, type, replacementMapper) :
47608                                     instantiateAnonymousType(type, replacementMapper);
47609                         }
47610                         return t;
47611                     });
47612                 }
47613             }
47614             return instantiateAnonymousType(type, mapper);
47615         }
47616         function getModifiedReadonlyState(state, modifiers) {
47617             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
47618         }
47619         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
47620             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
47621             return elementType === errorType ? errorType :
47622                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
47623         }
47624         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
47625             var minLength = tupleType.target.minLength;
47626             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
47627                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), i >= minLength, mapper);
47628             });
47629             var modifiers = getMappedTypeModifiers(mappedType);
47630             var newMinLength = modifiers & 4 /* IncludeOptional */ ? 0 :
47631                 modifiers & 8 /* ExcludeOptional */ ? getTypeReferenceArity(tupleType) - (tupleType.target.hasRestElement ? 1 : 0) :
47632                     minLength;
47633             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
47634             return ts.contains(elementTypes, errorType) ? errorType :
47635                 createTupleType(elementTypes, newMinLength, tupleType.target.hasRestElement, newReadonly, tupleType.target.associatedNames);
47636         }
47637         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
47638             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
47639             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
47640             var modifiers = getMappedTypeModifiers(type);
47641             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
47642                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
47643                     propType;
47644         }
47645         function instantiateAnonymousType(type, mapper) {
47646             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
47647             if (type.objectFlags & 32 /* Mapped */) {
47648                 result.declaration = type.declaration;
47649                 // C.f. instantiateSignature
47650                 var origTypeParameter = getTypeParameterFromMappedType(type);
47651                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
47652                 result.typeParameter = freshTypeParameter;
47653                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
47654                 freshTypeParameter.mapper = mapper;
47655             }
47656             result.target = type;
47657             result.mapper = mapper;
47658             result.aliasSymbol = type.aliasSymbol;
47659             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
47660             return result;
47661         }
47662         function getConditionalTypeInstantiation(type, mapper) {
47663             var root = type.root;
47664             if (root.outerTypeParameters) {
47665                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
47666                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
47667                 // instantiation cache key from the type IDs of the type arguments.
47668                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
47669                 var id = getTypeListId(typeArguments);
47670                 var result = root.instantiations.get(id);
47671                 if (!result) {
47672                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
47673                     result = instantiateConditionalType(root, newMapper);
47674                     root.instantiations.set(id, result);
47675                 }
47676                 return result;
47677             }
47678             return type;
47679         }
47680         function instantiateConditionalType(root, mapper) {
47681             // Check if we have a conditional type where the check type is a naked type parameter. If so,
47682             // the conditional type is distributive over union types and when T is instantiated to a union
47683             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
47684             if (root.isDistributive) {
47685                 var checkType_1 = root.checkType;
47686                 var instantiatedType = getMappedType(checkType_1, mapper);
47687                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
47688                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
47689                 }
47690             }
47691             return getConditionalType(root, mapper);
47692         }
47693         function instantiateType(type, mapper) {
47694             if (!type || !mapper) {
47695                 return type;
47696             }
47697             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
47698                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
47699                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
47700                 // the recursion here by yielding the error type.
47701                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
47702                 return errorType;
47703             }
47704             totalInstantiationCount++;
47705             instantiationCount++;
47706             instantiationDepth++;
47707             var result = instantiateTypeWorker(type, mapper);
47708             instantiationDepth--;
47709             return result;
47710         }
47711         /**
47712          * This can be used to avoid the penalty on instantiation depth for types which result from immediate
47713          * simplification. It essentially removes the depth increase done in `instantiateType`.
47714          */
47715         function instantiateTypeWithoutDepthIncrease(type, mapper) {
47716             instantiationDepth--;
47717             var result = instantiateType(type, mapper);
47718             instantiationDepth++;
47719             return result;
47720         }
47721         function instantiateTypeWorker(type, mapper) {
47722             var flags = type.flags;
47723             if (flags & 262144 /* TypeParameter */) {
47724                 return getMappedType(type, mapper);
47725             }
47726             if (flags & 524288 /* Object */) {
47727                 var objectFlags = type.objectFlags;
47728                 if (objectFlags & 16 /* Anonymous */) {
47729                     // If the anonymous type originates in a declaration of a function, method, class, or
47730                     // interface, in an object type literal, or in an object literal expression, we may need
47731                     // to instantiate the type because it might reference a type parameter.
47732                     return couldContainTypeVariables(type) ?
47733                         getObjectTypeInstantiation(type, mapper) : type;
47734                 }
47735                 if (objectFlags & 32 /* Mapped */) {
47736                     return getObjectTypeInstantiation(type, mapper);
47737                 }
47738                 if (objectFlags & 4 /* Reference */) {
47739                     if (type.node) {
47740                         return getObjectTypeInstantiation(type, mapper);
47741                     }
47742                     var resolvedTypeArguments = type.resolvedTypeArguments;
47743                     var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
47744                     return newTypeArguments !== resolvedTypeArguments ? createTypeReference(type.target, newTypeArguments) : type;
47745                 }
47746                 return type;
47747             }
47748             if ((flags & 2097152 /* Intersection */) || (flags & 1048576 /* Union */ && !(flags & 131068 /* Primitive */))) {
47749                 if (!couldContainTypeVariables(type)) {
47750                     return type;
47751                 }
47752                 var types = type.types;
47753                 var newTypes = instantiateTypes(types, mapper);
47754                 return newTypes === types
47755                     ? type
47756                     : (flags & 2097152 /* Intersection */)
47757                         ? getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper))
47758                         : getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47759             }
47760             if (flags & 4194304 /* Index */) {
47761                 return getIndexType(instantiateType(type.type, mapper));
47762             }
47763             if (flags & 8388608 /* IndexedAccess */) {
47764                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
47765             }
47766             if (flags & 16777216 /* Conditional */) {
47767                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
47768             }
47769             if (flags & 33554432 /* Substitution */) {
47770                 var maybeVariable = instantiateType(type.baseType, mapper);
47771                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
47772                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
47773                 }
47774                 else {
47775                     var sub = instantiateType(type.substitute, mapper);
47776                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
47777                         return maybeVariable;
47778                     }
47779                     return sub;
47780                 }
47781             }
47782             return type;
47783         }
47784         function getPermissiveInstantiation(type) {
47785             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
47786                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
47787         }
47788         function getRestrictiveInstantiation(type) {
47789             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
47790                 return type;
47791             }
47792             if (type.restrictiveInstantiation) {
47793                 return type.restrictiveInstantiation;
47794             }
47795             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
47796             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
47797             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
47798             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
47799             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
47800             // are constrained to `unknown` and produce tons of false positives/negatives!
47801             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
47802             return type.restrictiveInstantiation;
47803         }
47804         function instantiateIndexInfo(info, mapper) {
47805             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
47806         }
47807         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
47808         // that is subject to contextual typing.
47809         function isContextSensitive(node) {
47810             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
47811             switch (node.kind) {
47812                 case 201 /* FunctionExpression */:
47813                 case 202 /* ArrowFunction */:
47814                 case 161 /* MethodDeclaration */:
47815                 case 244 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
47816                     return isContextSensitiveFunctionLikeDeclaration(node);
47817                 case 193 /* ObjectLiteralExpression */:
47818                     return ts.some(node.properties, isContextSensitive);
47819                 case 192 /* ArrayLiteralExpression */:
47820                     return ts.some(node.elements, isContextSensitive);
47821                 case 210 /* ConditionalExpression */:
47822                     return isContextSensitive(node.whenTrue) ||
47823                         isContextSensitive(node.whenFalse);
47824                 case 209 /* BinaryExpression */:
47825                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
47826                         (isContextSensitive(node.left) || isContextSensitive(node.right));
47827                 case 281 /* PropertyAssignment */:
47828                     return isContextSensitive(node.initializer);
47829                 case 200 /* ParenthesizedExpression */:
47830                     return isContextSensitive(node.expression);
47831                 case 274 /* JsxAttributes */:
47832                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
47833                 case 273 /* JsxAttribute */: {
47834                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
47835                     var initializer = node.initializer;
47836                     return !!initializer && isContextSensitive(initializer);
47837                 }
47838                 case 276 /* JsxExpression */: {
47839                     // It is possible to that node.expression is undefined (e.g <div x={} />)
47840                     var expression = node.expression;
47841                     return !!expression && isContextSensitive(expression);
47842                 }
47843             }
47844             return false;
47845         }
47846         function isContextSensitiveFunctionLikeDeclaration(node) {
47847             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
47848                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
47849         }
47850         function hasContextSensitiveParameters(node) {
47851             // Functions with type parameters are not context sensitive.
47852             if (!node.typeParameters) {
47853                 // Functions with any parameters that lack type annotations are context sensitive.
47854                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
47855                     return true;
47856                 }
47857                 if (node.kind !== 202 /* ArrowFunction */) {
47858                     // If the first parameter is not an explicit 'this' parameter, then the function has
47859                     // an implicit 'this' parameter which is subject to contextual typing.
47860                     var parameter = ts.firstOrUndefined(node.parameters);
47861                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
47862                         return true;
47863                     }
47864                 }
47865             }
47866             return false;
47867         }
47868         function hasContextSensitiveReturnExpression(node) {
47869             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
47870             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 223 /* Block */ && isContextSensitive(node.body);
47871         }
47872         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
47873             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
47874                 isContextSensitiveFunctionLikeDeclaration(func);
47875         }
47876         function getTypeWithoutSignatures(type) {
47877             if (type.flags & 524288 /* Object */) {
47878                 var resolved = resolveStructuredTypeMembers(type);
47879                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
47880                     var result = createObjectType(16 /* Anonymous */, type.symbol);
47881                     result.members = resolved.members;
47882                     result.properties = resolved.properties;
47883                     result.callSignatures = ts.emptyArray;
47884                     result.constructSignatures = ts.emptyArray;
47885                     return result;
47886                 }
47887             }
47888             else if (type.flags & 2097152 /* Intersection */) {
47889                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
47890             }
47891             return type;
47892         }
47893         // TYPE CHECKING
47894         function isTypeIdenticalTo(source, target) {
47895             return isTypeRelatedTo(source, target, identityRelation);
47896         }
47897         function compareTypesIdentical(source, target) {
47898             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
47899         }
47900         function compareTypesAssignable(source, target) {
47901             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
47902         }
47903         function compareTypesSubtypeOf(source, target) {
47904             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
47905         }
47906         function isTypeSubtypeOf(source, target) {
47907             return isTypeRelatedTo(source, target, subtypeRelation);
47908         }
47909         function isTypeAssignableTo(source, target) {
47910             return isTypeRelatedTo(source, target, assignableRelation);
47911         }
47912         // An object type S is considered to be derived from an object type T if
47913         // S is a union type and every constituent of S is derived from T,
47914         // T is a union type and S is derived from at least one constituent of T, or
47915         // S is a type variable with a base constraint that is derived from T,
47916         // T is one of the global types Object and Function and S is a subtype of T, or
47917         // T occurs directly or indirectly in an 'extends' clause of S.
47918         // Note that this check ignores type parameters and only considers the
47919         // inheritance hierarchy.
47920         function isTypeDerivedFrom(source, target) {
47921             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
47922                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
47923                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
47924                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
47925                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
47926                                 hasBaseType(source, getTargetType(target));
47927         }
47928         /**
47929          * This is *not* a bi-directional relationship.
47930          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
47931          *
47932          * 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.
47933          * It is used to check following cases:
47934          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
47935          *   - the types of `case` clause expressions and their respective `switch` expressions.
47936          *   - the type of an expression in a type assertion with the type being asserted.
47937          */
47938         function isTypeComparableTo(source, target) {
47939             return isTypeRelatedTo(source, target, comparableRelation);
47940         }
47941         function areTypesComparable(type1, type2) {
47942             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
47943         }
47944         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
47945             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
47946         }
47947         /**
47948          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
47949          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
47950          */
47951         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
47952             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
47953         }
47954         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
47955             if (isTypeRelatedTo(source, target, relation))
47956                 return true;
47957             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47958                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
47959             }
47960             return false;
47961         }
47962         function isOrHasGenericConditional(type) {
47963             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
47964         }
47965         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47966             if (!node || isOrHasGenericConditional(target))
47967                 return false;
47968             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
47969                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
47970                 return true;
47971             }
47972             switch (node.kind) {
47973                 case 276 /* JsxExpression */:
47974                 case 200 /* ParenthesizedExpression */:
47975                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47976                 case 209 /* BinaryExpression */:
47977                     switch (node.operatorToken.kind) {
47978                         case 62 /* EqualsToken */:
47979                         case 27 /* CommaToken */:
47980                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
47981                     }
47982                     break;
47983                 case 193 /* ObjectLiteralExpression */:
47984                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47985                 case 192 /* ArrayLiteralExpression */:
47986                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
47987                 case 274 /* JsxAttributes */:
47988                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
47989                 case 202 /* ArrowFunction */:
47990                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
47991             }
47992             return false;
47993         }
47994         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
47995             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
47996             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
47997             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
47998                 var signatures = _a[_i];
47999                 if (ts.some(signatures, function (s) {
48000                     var returnType = getReturnTypeOfSignature(s);
48001                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
48002                 })) {
48003                     var resultObj = errorOutputContainer || {};
48004                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
48005                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
48006                     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));
48007                     return true;
48008                 }
48009             }
48010             return false;
48011         }
48012         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48013             // Don't elaborate blocks
48014             if (ts.isBlock(node.body)) {
48015                 return false;
48016             }
48017             // Or functions with annotated parameter types
48018             if (ts.some(node.parameters, ts.hasType)) {
48019                 return false;
48020             }
48021             var sourceSig = getSingleCallSignature(source);
48022             if (!sourceSig) {
48023                 return false;
48024             }
48025             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
48026             if (!ts.length(targetSignatures)) {
48027                 return false;
48028             }
48029             var returnExpression = node.body;
48030             var sourceReturn = getReturnTypeOfSignature(sourceSig);
48031             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
48032             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
48033                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48034                 if (elaborated) {
48035                     return elaborated;
48036                 }
48037                 var resultObj = errorOutputContainer || {};
48038                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
48039                 if (resultObj.errors) {
48040                     if (target.symbol && ts.length(target.symbol.declarations)) {
48041                         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));
48042                     }
48043                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
48044                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
48045                         // an IPromise and a Promise that are slightly different
48046                         && !getTypeOfPropertyOfType(sourceReturn, "then")
48047                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
48048                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
48049                     }
48050                     return true;
48051                 }
48052             }
48053             return false;
48054         }
48055         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
48056             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
48057             if (idx) {
48058                 return idx;
48059             }
48060             if (target.flags & 1048576 /* Union */) {
48061                 var best = getBestMatchingType(source, target);
48062                 if (best) {
48063                     return getIndexedAccessTypeOrUndefined(best, nameType);
48064                 }
48065             }
48066         }
48067         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
48068             next.contextualType = sourcePropType;
48069             try {
48070                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
48071             }
48072             finally {
48073                 next.contextualType = undefined;
48074             }
48075         }
48076         /**
48077          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
48078          * 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`
48079          * Otherwise, we issue an error on _every_ element which fail the assignability check
48080          */
48081         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
48082             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
48083             var reportedError = false;
48084             for (var status = iterator.next(); !status.done; status = iterator.next()) {
48085                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
48086                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
48087                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
48088                     continue; // Don't elaborate on indexes on generic variables
48089                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
48090                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
48091                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
48092                     if (elaborated) {
48093                         reportedError = true;
48094                     }
48095                     else {
48096                         // Issue error on the prop itself, since the prop couldn't elaborate the error
48097                         var resultObj = errorOutputContainer || {};
48098                         // Use the expression type, if available
48099                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
48100                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48101                         if (result && specificSource !== sourcePropType) {
48102                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
48103                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
48104                         }
48105                         if (resultObj.errors) {
48106                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
48107                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
48108                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
48109                             var issuedElaboration = false;
48110                             if (!targetProp) {
48111                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
48112                                     getIndexInfoOfType(target, 0 /* String */) ||
48113                                     undefined;
48114                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
48115                                     issuedElaboration = true;
48116                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
48117                                 }
48118                             }
48119                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
48120                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
48121                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
48122                                     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)));
48123                                 }
48124                             }
48125                         }
48126                         reportedError = true;
48127                     }
48128                 }
48129             }
48130             return reportedError;
48131         }
48132         function generateJsxAttributes(node) {
48133             var _i, _a, prop;
48134             return __generator(this, function (_b) {
48135                 switch (_b.label) {
48136                     case 0:
48137                         if (!ts.length(node.properties))
48138                             return [2 /*return*/];
48139                         _i = 0, _a = node.properties;
48140                         _b.label = 1;
48141                     case 1:
48142                         if (!(_i < _a.length)) return [3 /*break*/, 4];
48143                         prop = _a[_i];
48144                         if (ts.isJsxSpreadAttribute(prop))
48145                             return [3 /*break*/, 3];
48146                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
48147                     case 2:
48148                         _b.sent();
48149                         _b.label = 3;
48150                     case 3:
48151                         _i++;
48152                         return [3 /*break*/, 1];
48153                     case 4: return [2 /*return*/];
48154                 }
48155             });
48156         }
48157         function generateJsxChildren(node, getInvalidTextDiagnostic) {
48158             var memberOffset, i, child, nameType, elem;
48159             return __generator(this, function (_a) {
48160                 switch (_a.label) {
48161                     case 0:
48162                         if (!ts.length(node.children))
48163                             return [2 /*return*/];
48164                         memberOffset = 0;
48165                         i = 0;
48166                         _a.label = 1;
48167                     case 1:
48168                         if (!(i < node.children.length)) return [3 /*break*/, 5];
48169                         child = node.children[i];
48170                         nameType = getLiteralType(i - memberOffset);
48171                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
48172                         if (!elem) return [3 /*break*/, 3];
48173                         return [4 /*yield*/, elem];
48174                     case 2:
48175                         _a.sent();
48176                         return [3 /*break*/, 4];
48177                     case 3:
48178                         memberOffset++;
48179                         _a.label = 4;
48180                     case 4:
48181                         i++;
48182                         return [3 /*break*/, 1];
48183                     case 5: return [2 /*return*/];
48184                 }
48185             });
48186         }
48187         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
48188             switch (child.kind) {
48189                 case 276 /* JsxExpression */:
48190                     // child is of the type of the expression
48191                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
48192                 case 11 /* JsxText */:
48193                     if (child.containsOnlyTriviaWhiteSpaces) {
48194                         break; // Whitespace only jsx text isn't real jsx text
48195                     }
48196                     // child is a string
48197                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
48198                 case 266 /* JsxElement */:
48199                 case 267 /* JsxSelfClosingElement */:
48200                 case 270 /* JsxFragment */:
48201                     // child is of type JSX.Element
48202                     return { errorNode: child, innerExpression: child, nameType: nameType };
48203                 default:
48204                     return ts.Debug.assertNever(child, "Found invalid jsx child");
48205             }
48206         }
48207         function getSemanticJsxChildren(children) {
48208             return ts.filter(children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyTriviaWhiteSpaces; });
48209         }
48210         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48211             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
48212             var invalidTextDiagnostic;
48213             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
48214                 var containingElement = node.parent.parent;
48215                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48216                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48217                 var childrenNameType = getLiteralType(childrenPropName);
48218                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
48219                 var validChildren = getSemanticJsxChildren(containingElement.children);
48220                 if (!ts.length(validChildren)) {
48221                     return result;
48222                 }
48223                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
48224                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
48225                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
48226                 if (moreThanOneRealChildren) {
48227                     if (arrayLikeTargetParts !== neverType) {
48228                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
48229                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
48230                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
48231                     }
48232                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48233                         // arity mismatch
48234                         result = true;
48235                         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));
48236                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48237                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48238                         }
48239                     }
48240                 }
48241                 else {
48242                     if (nonArrayLikeTargetParts !== neverType) {
48243                         var child = validChildren[0];
48244                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
48245                         if (elem_1) {
48246                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
48247                                 switch (_a.label) {
48248                                     case 0: return [4 /*yield*/, elem_1];
48249                                     case 1:
48250                                         _a.sent();
48251                                         return [2 /*return*/];
48252                                 }
48253                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
48254                         }
48255                     }
48256                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
48257                         // arity mismatch
48258                         result = true;
48259                         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));
48260                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
48261                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48262                         }
48263                     }
48264                 }
48265             }
48266             return result;
48267             function getInvalidTextualChildDiagnostic() {
48268                 if (!invalidTextDiagnostic) {
48269                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
48270                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
48271                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
48272                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
48273                     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;
48274                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
48275                 }
48276                 return invalidTextDiagnostic;
48277             }
48278         }
48279         function generateLimitedTupleElements(node, target) {
48280             var len, i, elem, nameType;
48281             return __generator(this, function (_a) {
48282                 switch (_a.label) {
48283                     case 0:
48284                         len = ts.length(node.elements);
48285                         if (!len)
48286                             return [2 /*return*/];
48287                         i = 0;
48288                         _a.label = 1;
48289                     case 1:
48290                         if (!(i < len)) return [3 /*break*/, 4];
48291                         // 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
48292                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
48293                             return [3 /*break*/, 3];
48294                         elem = node.elements[i];
48295                         if (ts.isOmittedExpression(elem))
48296                             return [3 /*break*/, 3];
48297                         nameType = getLiteralType(i);
48298                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
48299                     case 2:
48300                         _a.sent();
48301                         _a.label = 3;
48302                     case 3:
48303                         i++;
48304                         return [3 /*break*/, 1];
48305                     case 4: return [2 /*return*/];
48306                 }
48307             });
48308         }
48309         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48310             if (target.flags & 131068 /* Primitive */)
48311                 return false;
48312             if (isTupleLikeType(source)) {
48313                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
48314             }
48315             // recreate a tuple from the elements, if possible
48316             // Since we're re-doing the expression type, we need to reapply the contextual type
48317             var oldContext = node.contextualType;
48318             node.contextualType = target;
48319             try {
48320                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
48321                 node.contextualType = oldContext;
48322                 if (isTupleLikeType(tupleizedType)) {
48323                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
48324                 }
48325                 return false;
48326             }
48327             finally {
48328                 node.contextualType = oldContext;
48329             }
48330         }
48331         function generateObjectLiteralElements(node) {
48332             var _i, _a, prop, type, _b;
48333             return __generator(this, function (_c) {
48334                 switch (_c.label) {
48335                     case 0:
48336                         if (!ts.length(node.properties))
48337                             return [2 /*return*/];
48338                         _i = 0, _a = node.properties;
48339                         _c.label = 1;
48340                     case 1:
48341                         if (!(_i < _a.length)) return [3 /*break*/, 8];
48342                         prop = _a[_i];
48343                         if (ts.isSpreadAssignment(prop))
48344                             return [3 /*break*/, 7];
48345                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
48346                         if (!type || (type.flags & 131072 /* Never */)) {
48347                             return [3 /*break*/, 7];
48348                         }
48349                         _b = prop.kind;
48350                         switch (_b) {
48351                             case 164 /* SetAccessor */: return [3 /*break*/, 2];
48352                             case 163 /* GetAccessor */: return [3 /*break*/, 2];
48353                             case 161 /* MethodDeclaration */: return [3 /*break*/, 2];
48354                             case 282 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
48355                             case 281 /* PropertyAssignment */: return [3 /*break*/, 4];
48356                         }
48357                         return [3 /*break*/, 6];
48358                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
48359                     case 3:
48360                         _c.sent();
48361                         return [3 /*break*/, 7];
48362                     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 }];
48363                     case 5:
48364                         _c.sent();
48365                         return [3 /*break*/, 7];
48366                     case 6:
48367                         ts.Debug.assertNever(prop);
48368                         _c.label = 7;
48369                     case 7:
48370                         _i++;
48371                         return [3 /*break*/, 1];
48372                     case 8: return [2 /*return*/];
48373                 }
48374             });
48375         }
48376         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
48377             if (target.flags & 131068 /* Primitive */)
48378                 return false;
48379             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
48380         }
48381         /**
48382          * This is *not* a bi-directional relationship.
48383          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
48384          */
48385         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
48386             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
48387         }
48388         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
48389             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
48390             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
48391         }
48392         /**
48393          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
48394          */
48395         function isAnySignature(s) {
48396             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
48397                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
48398                 isTypeAny(getReturnTypeOfSignature(s));
48399         }
48400         /**
48401          * See signatureRelatedTo, compareSignaturesIdentical
48402          */
48403         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
48404             // TODO (drosen): De-duplicate code between related functions.
48405             if (source === target) {
48406                 return -1 /* True */;
48407             }
48408             if (isAnySignature(target)) {
48409                 return -1 /* True */;
48410             }
48411             var targetCount = getParameterCount(target);
48412             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
48413                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
48414             if (sourceHasMoreParameters) {
48415                 return 0 /* False */;
48416             }
48417             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
48418                 target = getCanonicalSignature(target);
48419                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
48420             }
48421             var sourceCount = getParameterCount(source);
48422             var sourceRestType = getNonArrayRestType(source);
48423             var targetRestType = getNonArrayRestType(target);
48424             if (sourceRestType || targetRestType) {
48425                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
48426             }
48427             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
48428                 // We're not able to relate misaligned complex rest parameters
48429                 return 0 /* False */;
48430             }
48431             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
48432             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 161 /* MethodDeclaration */ &&
48433                 kind !== 160 /* MethodSignature */ && kind !== 162 /* Constructor */;
48434             var result = -1 /* True */;
48435             var sourceThisType = getThisTypeOfSignature(source);
48436             if (sourceThisType && sourceThisType !== voidType) {
48437                 var targetThisType = getThisTypeOfSignature(target);
48438                 if (targetThisType) {
48439                     // void sources are assignable to anything.
48440                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
48441                         || compareTypes(targetThisType, sourceThisType, reportErrors);
48442                     if (!related) {
48443                         if (reportErrors) {
48444                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
48445                         }
48446                         return 0 /* False */;
48447                     }
48448                     result &= related;
48449                 }
48450             }
48451             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
48452             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
48453             for (var i = 0; i < paramCount; i++) {
48454                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : getTypeAtPosition(source, i);
48455                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : getTypeAtPosition(target, i);
48456                 // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
48457                 // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
48458                 // they naturally relate only contra-variantly). However, if the source and target parameters both have
48459                 // function types with a single call signature, we know we are relating two callback parameters. In
48460                 // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
48461                 // similar to return values, callback parameters are output positions. This means that a Promise<T>,
48462                 // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
48463                 // with respect to T.
48464                 var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
48465                 var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
48466                 var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
48467                     (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
48468                 var related = callbacks ?
48469                     compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
48470                     !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
48471                 // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
48472                 if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
48473                     related = 0 /* False */;
48474                 }
48475                 if (!related) {
48476                     if (reportErrors) {
48477                         errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
48478                     }
48479                     return 0 /* False */;
48480                 }
48481                 result &= related;
48482             }
48483             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
48484                 // If a signature resolution is already in-flight, skip issuing a circularity error
48485                 // here and just use the `any` type directly
48486                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
48487                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
48488                         : getReturnTypeOfSignature(target);
48489                 if (targetReturnType === voidType) {
48490                     return result;
48491                 }
48492                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
48493                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
48494                         : getReturnTypeOfSignature(source);
48495                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
48496                 var targetTypePredicate = getTypePredicateOfSignature(target);
48497                 if (targetTypePredicate) {
48498                     var sourceTypePredicate = getTypePredicateOfSignature(source);
48499                     if (sourceTypePredicate) {
48500                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
48501                     }
48502                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
48503                         if (reportErrors) {
48504                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
48505                         }
48506                         return 0 /* False */;
48507                     }
48508                 }
48509                 else {
48510                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
48511                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
48512                     // wouldn't be co-variant for T without this rule.
48513                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
48514                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
48515                     if (!result && reportErrors && incompatibleErrorReporter) {
48516                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
48517                     }
48518                 }
48519             }
48520             return result;
48521         }
48522         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
48523             if (source.kind !== target.kind) {
48524                 if (reportErrors) {
48525                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
48526                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48527                 }
48528                 return 0 /* False */;
48529             }
48530             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
48531                 if (source.parameterIndex !== target.parameterIndex) {
48532                     if (reportErrors) {
48533                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
48534                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48535                     }
48536                     return 0 /* False */;
48537                 }
48538             }
48539             var related = source.type === target.type ? -1 /* True */ :
48540                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
48541                     0 /* False */;
48542             if (related === 0 /* False */ && reportErrors) {
48543                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
48544             }
48545             return related;
48546         }
48547         function isImplementationCompatibleWithOverload(implementation, overload) {
48548             var erasedSource = getErasedSignature(implementation);
48549             var erasedTarget = getErasedSignature(overload);
48550             // First see if the return types are compatible in either direction.
48551             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
48552             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
48553             if (targetReturnType === voidType
48554                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
48555                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
48556                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
48557             }
48558             return false;
48559         }
48560         function isEmptyResolvedType(t) {
48561             return t !== anyFunctionType &&
48562                 t.properties.length === 0 &&
48563                 t.callSignatures.length === 0 &&
48564                 t.constructSignatures.length === 0 &&
48565                 !t.stringIndexInfo &&
48566                 !t.numberIndexInfo;
48567         }
48568         function isEmptyObjectType(type) {
48569             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
48570                 type.flags & 67108864 /* NonPrimitive */ ? true :
48571                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
48572                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
48573                             false;
48574         }
48575         function isEmptyAnonymousObjectType(type) {
48576             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && isEmptyObjectType(type);
48577         }
48578         function isStringIndexSignatureOnlyType(type) {
48579             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
48580                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
48581                 false;
48582         }
48583         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
48584             if (sourceSymbol === targetSymbol) {
48585                 return true;
48586             }
48587             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
48588             var entry = enumRelation.get(id);
48589             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
48590                 return !!(entry & 1 /* Succeeded */);
48591             }
48592             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
48593                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48594                 return false;
48595             }
48596             var targetEnumType = getTypeOfSymbol(targetSymbol);
48597             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
48598                 var property = _a[_i];
48599                 if (property.flags & 8 /* EnumMember */) {
48600                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
48601                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
48602                         if (errorReporter) {
48603                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
48604                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
48605                         }
48606                         else {
48607                             enumRelation.set(id, 2 /* Failed */);
48608                         }
48609                         return false;
48610                     }
48611                 }
48612             }
48613             enumRelation.set(id, 1 /* Succeeded */);
48614             return true;
48615         }
48616         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
48617             var s = source.flags;
48618             var t = target.flags;
48619             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
48620                 return true;
48621             if (t & 131072 /* Never */)
48622                 return false;
48623             if (s & 132 /* StringLike */ && t & 4 /* String */)
48624                 return true;
48625             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
48626                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48627                 source.value === target.value)
48628                 return true;
48629             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
48630                 return true;
48631             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
48632                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
48633                 source.value === target.value)
48634                 return true;
48635             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
48636                 return true;
48637             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
48638                 return true;
48639             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
48640                 return true;
48641             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48642                 return true;
48643             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
48644                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
48645                     return true;
48646                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
48647                     source.value === target.value &&
48648                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
48649                     return true;
48650             }
48651             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
48652                 return true;
48653             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
48654                 return true;
48655             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
48656                 return true;
48657             if (relation === assignableRelation || relation === comparableRelation) {
48658                 if (s & 1 /* Any */)
48659                     return true;
48660                 // Type number or any numeric literal type is assignable to any numeric enum type or any
48661                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
48662                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
48663                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
48664                     return true;
48665             }
48666             return false;
48667         }
48668         function isTypeRelatedTo(source, target, relation) {
48669             if (isFreshLiteralType(source)) {
48670                 source = source.regularType;
48671             }
48672             if (isFreshLiteralType(target)) {
48673                 target = target.regularType;
48674             }
48675             if (source === target) {
48676                 return true;
48677             }
48678             if (relation !== identityRelation) {
48679                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
48680                     return true;
48681                 }
48682             }
48683             else {
48684                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
48685                     source.flags !== target.flags && !(source.flags & 66584576 /* Substructure */))
48686                     return false;
48687             }
48688             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
48689                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
48690                 if (related !== undefined) {
48691                     return !!(related & 1 /* Succeeded */);
48692                 }
48693             }
48694             if (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */) {
48695                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
48696             }
48697             return false;
48698         }
48699         function isIgnoredJsxProperty(source, sourceProp) {
48700             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
48701         }
48702         function getNormalizedType(type, writing) {
48703             while (true) {
48704                 var t = isFreshLiteralType(type) ? type.regularType :
48705                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
48706                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
48707                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
48708                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
48709                                     type;
48710                 if (t === type)
48711                     break;
48712                 type = t;
48713             }
48714             return type;
48715         }
48716         /**
48717          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
48718          * @param source The left-hand-side of the relation.
48719          * @param target The right-hand-side of the relation.
48720          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
48721          * Used as both to determine which checks are performed and as a cache of previously computed results.
48722          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
48723          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
48724          * @param containingMessageChain A chain of errors to prepend any new errors found.
48725          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
48726          */
48727         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
48728             var errorInfo;
48729             var relatedInfo;
48730             var maybeKeys;
48731             var sourceStack;
48732             var targetStack;
48733             var maybeCount = 0;
48734             var depth = 0;
48735             var expandingFlags = 0 /* None */;
48736             var overflow = false;
48737             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
48738             var lastSkippedInfo;
48739             var incompatibleStack = [];
48740             var inPropertyCheck = false;
48741             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
48742             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
48743             if (incompatibleStack.length) {
48744                 reportIncompatibleStack();
48745             }
48746             if (overflow) {
48747                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
48748                 if (errorOutputContainer) {
48749                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48750                 }
48751             }
48752             else if (errorInfo) {
48753                 if (containingMessageChain) {
48754                     var chain = containingMessageChain();
48755                     if (chain) {
48756                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
48757                         errorInfo = chain;
48758                     }
48759                 }
48760                 var relatedInformation = void 0;
48761                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
48762                 if (headMessage && errorNode && !result && source.symbol) {
48763                     var links = getSymbolLinks(source.symbol);
48764                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
48765                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
48766                         if (helpfulRetry) {
48767                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
48768                             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);
48769                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
48770                         }
48771                     }
48772                 }
48773                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
48774                 if (relatedInfo) {
48775                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
48776                 }
48777                 if (errorOutputContainer) {
48778                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
48779                 }
48780                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
48781                     diagnostics.add(diag);
48782                 }
48783             }
48784             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
48785                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
48786             }
48787             return result !== 0 /* False */;
48788             function resetErrorInfo(saved) {
48789                 errorInfo = saved.errorInfo;
48790                 lastSkippedInfo = saved.lastSkippedInfo;
48791                 incompatibleStack = saved.incompatibleStack;
48792                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
48793                 relatedInfo = saved.relatedInfo;
48794             }
48795             function captureErrorCalculationState() {
48796                 return {
48797                     errorInfo: errorInfo,
48798                     lastSkippedInfo: lastSkippedInfo,
48799                     incompatibleStack: incompatibleStack.slice(),
48800                     overrideNextErrorInfo: overrideNextErrorInfo,
48801                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
48802                 };
48803             }
48804             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
48805                 overrideNextErrorInfo++; // Suppress the next relation error
48806                 lastSkippedInfo = undefined; // Reset skipped info cache
48807                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
48808             }
48809             function reportIncompatibleStack() {
48810                 var stack = incompatibleStack;
48811                 incompatibleStack = [];
48812                 var info = lastSkippedInfo;
48813                 lastSkippedInfo = undefined;
48814                 if (stack.length === 1) {
48815                     reportError.apply(void 0, stack[0]);
48816                     if (info) {
48817                         // Actually do the last relation error
48818                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48819                     }
48820                     return;
48821                 }
48822                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
48823                 // we can build from left to right
48824                 var path = "";
48825                 var secondaryRootErrors = [];
48826                 while (stack.length) {
48827                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
48828                     switch (msg.code) {
48829                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
48830                             // Parenthesize a `new` if there is one
48831                             if (path.indexOf("new ") === 0) {
48832                                 path = "(" + path + ")";
48833                             }
48834                             var str = "" + args[0];
48835                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
48836                             if (path.length === 0) {
48837                                 path = "" + str;
48838                             }
48839                             // Otherwise write a dotted name if possible
48840                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
48841                                 path = path + "." + str;
48842                             }
48843                             // Failing that, check if the name is already a computed name
48844                             else if (str[0] === "[" && str[str.length - 1] === "]") {
48845                                 path = "" + path + str;
48846                             }
48847                             // And finally write out a computed name as a last resort
48848                             else {
48849                                 path = path + "[" + str + "]";
48850                             }
48851                             break;
48852                         }
48853                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
48854                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
48855                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
48856                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
48857                             if (path.length === 0) {
48858                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
48859                                 // to unify (the with no arguments bit is excessive for printback) and print them back
48860                                 var mappedMsg = msg;
48861                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48862                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
48863                                 }
48864                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
48865                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
48866                                 }
48867                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
48868                             }
48869                             else {
48870                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
48871                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48872                                     ? "new "
48873                                     : "";
48874                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
48875                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
48876                                     ? ""
48877                                     : "...";
48878                                 path = "" + prefix + path + "(" + params + ")";
48879                             }
48880                             break;
48881                         }
48882                         default:
48883                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
48884                     }
48885                 }
48886                 if (path) {
48887                     reportError(path[path.length - 1] === ")"
48888                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
48889                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
48890                 }
48891                 else {
48892                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
48893                     secondaryRootErrors.shift();
48894                 }
48895                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
48896                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
48897                     var originalValue = msg.elidedInCompatabilityPyramid;
48898                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
48899                     reportError.apply(void 0, __spreadArrays([msg], args));
48900                     msg.elidedInCompatabilityPyramid = originalValue;
48901                 }
48902                 if (info) {
48903                     // Actually do the last relation error
48904                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
48905                 }
48906             }
48907             function reportError(message, arg0, arg1, arg2, arg3) {
48908                 ts.Debug.assert(!!errorNode);
48909                 if (incompatibleStack.length)
48910                     reportIncompatibleStack();
48911                 if (message.elidedInCompatabilityPyramid)
48912                     return;
48913                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
48914             }
48915             function associateRelatedInfo(info) {
48916                 ts.Debug.assert(!!errorInfo);
48917                 if (!relatedInfo) {
48918                     relatedInfo = [info];
48919                 }
48920                 else {
48921                     relatedInfo.push(info);
48922                 }
48923             }
48924             function reportRelationError(message, source, target) {
48925                 if (incompatibleStack.length)
48926                     reportIncompatibleStack();
48927                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
48928                 if (target.flags & 262144 /* TypeParameter */) {
48929                     var constraint = getBaseConstraintOfType(target);
48930                     var constraintElab = constraint && isTypeAssignableTo(source, constraint);
48931                     if (constraintElab) {
48932                         reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, sourceType, targetType, typeToString(constraint));
48933                     }
48934                     else {
48935                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, sourceType);
48936                     }
48937                 }
48938                 if (!message) {
48939                     if (relation === comparableRelation) {
48940                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
48941                     }
48942                     else if (sourceType === targetType) {
48943                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
48944                     }
48945                     else {
48946                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
48947                     }
48948                 }
48949                 reportError(message, sourceType, targetType);
48950             }
48951             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
48952                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
48953                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
48954                 if ((globalStringType === source && stringType === target) ||
48955                     (globalNumberType === source && numberType === target) ||
48956                     (globalBooleanType === source && booleanType === target) ||
48957                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
48958                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
48959                 }
48960             }
48961             /**
48962              * Try and elaborate array and tuple errors. Returns false
48963              * if we have found an elaboration, or we should ignore
48964              * any other elaborations when relating the `source` and
48965              * `target` types.
48966              */
48967             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
48968                 /**
48969                  * The spec for elaboration is:
48970                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48971                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
48972                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
48973                  * - If the source an array then skip property elaborations if the target is a tuple.
48974                  */
48975                 if (isTupleType(source)) {
48976                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
48977                         if (reportErrors) {
48978                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48979                         }
48980                         return false;
48981                     }
48982                     return isTupleType(target) || isArrayType(target);
48983                 }
48984                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
48985                     if (reportErrors) {
48986                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
48987                     }
48988                     return false;
48989                 }
48990                 if (isTupleType(target)) {
48991                     return isArrayType(source);
48992                 }
48993                 return true;
48994             }
48995             /**
48996              * Compare two types and return
48997              * * Ternary.True if they are related with no assumptions,
48998              * * Ternary.Maybe if they are related with assumptions of other relationships, or
48999              * * Ternary.False if they are not related.
49000              */
49001             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
49002                 if (reportErrors === void 0) { reportErrors = false; }
49003                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
49004                 // Before normalization: if `source` is type an object type, and `target` is primitive,
49005                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
49006                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
49007                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
49008                         return -1 /* True */;
49009                     }
49010                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
49011                     return 0 /* False */;
49012                 }
49013                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
49014                 // turn deferred type references into regular type references, simplify indexed access and
49015                 // conditional types, and resolve substitution types to either the substitution (on the source
49016                 // side) or the type variable (on the target side).
49017                 var source = getNormalizedType(originalSource, /*writing*/ false);
49018                 var target = getNormalizedType(originalTarget, /*writing*/ true);
49019                 if (source === target)
49020                     return -1 /* True */;
49021                 if (relation === identityRelation) {
49022                     return isIdenticalTo(source, target);
49023                 }
49024                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
49025                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
49026                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
49027                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
49028                 // the target is exactly the constraint.
49029                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
49030                     return -1 /* True */;
49031                 }
49032                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
49033                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
49034                 // First, see if we're even relating an object type to a union.
49035                 // Then see if the target is stripped down to a single non-union type.
49036                 // Note
49037                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
49038                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
49039                 //    when dealing with generics.
49040                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
49041                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
49042                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
49043                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
49044                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
49045                         if (source === nullStrippedTarget)
49046                             return -1 /* True */;
49047                         target = nullStrippedTarget;
49048                     }
49049                 }
49050                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
49051                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
49052                     return -1 /* True */;
49053                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49054                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
49055                 if (isPerformingExcessPropertyChecks) {
49056                     if (hasExcessProperties(source, target, reportErrors)) {
49057                         if (reportErrors) {
49058                             reportRelationError(headMessage, source, target);
49059                         }
49060                         return 0 /* False */;
49061                     }
49062                 }
49063                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
49064                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
49065                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
49066                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
49067                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
49068                     if (reportErrors) {
49069                         var calls = getSignaturesOfType(source, 0 /* Call */);
49070                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
49071                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
49072                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
49073                             reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, typeToString(source), typeToString(target));
49074                         }
49075                         else {
49076                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
49077                         }
49078                     }
49079                     return 0 /* False */;
49080                 }
49081                 var result = 0 /* False */;
49082                 var saveErrorInfo = captureErrorCalculationState();
49083                 // Note that these checks are specifically ordered to produce correct results. In particular,
49084                 // we need to deconstruct unions before intersections (because unions are always at the top),
49085                 // and we need to handle "each" relations before "some" relations for the same kind of type.
49086                 if (source.flags & 1048576 /* Union */) {
49087                     result = relation === comparableRelation ?
49088                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
49089                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
49090                 }
49091                 else {
49092                     if (target.flags & 1048576 /* Union */) {
49093                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
49094                     }
49095                     else if (target.flags & 2097152 /* Intersection */) {
49096                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
49097                     }
49098                     else if (source.flags & 2097152 /* Intersection */) {
49099                         // Check to see if any constituents of the intersection are immediately related to the target.
49100                         //
49101                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
49102                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
49103                         // take care of this, or to not elaborate at all. For instance,
49104                         //
49105                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
49106                         //
49107                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
49108                         //          than to report that 'D' is not assignable to 'A' or 'B'.
49109                         //
49110                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
49111                         //          breaking the intersection apart.
49112                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
49113                     }
49114                     if (!result && (source.flags & 66846720 /* StructuredOrInstantiable */ || target.flags & 66846720 /* StructuredOrInstantiable */)) {
49115                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
49116                             resetErrorInfo(saveErrorInfo);
49117                         }
49118                     }
49119                 }
49120                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
49121                     // The combined constraint of an intersection type is the intersection of the constraints of
49122                     // the constituents. When an intersection type contains instantiable types with union type
49123                     // constraints, there are situations where we need to examine the combined constraint. One is
49124                     // when the target is a union type. Another is when the intersection contains types belonging
49125                     // to one of the disjoint domains. For example, given type variables T and U, each with the
49126                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
49127                     // we need to check this constraint against a union on the target side. Also, given a type
49128                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
49129                     // 'string & number | number & number' which reduces to just 'number'.
49130                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
49131                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
49132                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
49133                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
49134                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
49135                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
49136                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
49137                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
49138                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49139                                 resetErrorInfo(saveErrorInfo);
49140                             }
49141                         }
49142                     }
49143                 }
49144                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
49145                 // an extra property check where the intersection is viewed as a single object. The following are motivating
49146                 // examples that all should be errors, but aren't without this extra property check:
49147                 //
49148                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
49149                 //
49150                 //   declare let wrong: { a: { y: string } };
49151                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
49152                 //
49153                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
49154                 //     x = y;  // Mismatched property in source intersection
49155                 //   }
49156                 //
49157                 // We suppress recursive intersection property checks because they can generate lots of work when relating
49158                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
49159                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
49160                     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 */); }))) {
49161                     inPropertyCheck = true;
49162                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
49163                     inPropertyCheck = false;
49164                 }
49165                 reportErrorResults(source, target, result, isComparingJsxAttributes);
49166                 return result;
49167                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
49168                     if (!result && reportErrors) {
49169                         source = originalSource.aliasSymbol ? originalSource : source;
49170                         target = originalTarget.aliasSymbol ? originalTarget : target;
49171                         var maybeSuppress = overrideNextErrorInfo > 0;
49172                         if (maybeSuppress) {
49173                             overrideNextErrorInfo--;
49174                         }
49175                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
49176                             var currentError = errorInfo;
49177                             tryElaborateArrayLikeErrors(source, target, reportErrors);
49178                             if (errorInfo !== currentError) {
49179                                 maybeSuppress = !!errorInfo;
49180                             }
49181                         }
49182                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
49183                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
49184                         }
49185                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
49186                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
49187                         }
49188                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
49189                             var targetTypes = target.types;
49190                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
49191                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
49192                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
49193                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
49194                                 // do not report top error
49195                                 return result;
49196                             }
49197                         }
49198                         else {
49199                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
49200                         }
49201                         if (!headMessage && maybeSuppress) {
49202                             lastSkippedInfo = [source, target];
49203                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
49204                             return result;
49205                         }
49206                         reportRelationError(headMessage, source, target);
49207                     }
49208                 }
49209             }
49210             function isIdenticalTo(source, target) {
49211                 var flags = source.flags & target.flags;
49212                 if (!(flags & 66584576 /* Substructure */)) {
49213                     return 0 /* False */;
49214                 }
49215                 if (flags & 3145728 /* UnionOrIntersection */) {
49216                     var result_5 = eachTypeRelatedToSomeType(source, target);
49217                     if (result_5) {
49218                         result_5 &= eachTypeRelatedToSomeType(target, source);
49219                     }
49220                     return result_5;
49221                 }
49222                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
49223             }
49224             function getTypeOfPropertyInTypes(types, name) {
49225                 var appendPropType = function (propTypes, type) {
49226                     type = getApparentType(type);
49227                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
49228                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
49229                     return ts.append(propTypes, propType);
49230                 };
49231                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
49232             }
49233             function hasExcessProperties(source, target, reportErrors) {
49234                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
49235                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
49236                 }
49237                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
49238                 if ((relation === assignableRelation || relation === comparableRelation) &&
49239                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
49240                     return false;
49241                 }
49242                 var reducedTarget = target;
49243                 var checkTypes;
49244                 if (target.flags & 1048576 /* Union */) {
49245                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
49246                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
49247                 }
49248                 var _loop_13 = function (prop) {
49249                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
49250                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
49251                             if (reportErrors) {
49252                                 // Report error in terms of object types in the target as those are the only ones
49253                                 // we check in isKnownProperty.
49254                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
49255                                 // We know *exactly* where things went wrong when comparing the types.
49256                                 // Use this property as the error node as this will be more helpful in
49257                                 // reasoning about what went wrong.
49258                                 if (!errorNode)
49259                                     return { value: ts.Debug.fail() };
49260                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
49261                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
49262                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
49263                                     // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages)
49264                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
49265                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
49266                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
49267                                         errorNode = prop.valueDeclaration.name;
49268                                     }
49269                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget));
49270                                 }
49271                                 else {
49272                                     // use the property's value declaration if the property is assigned inside the literal itself
49273                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
49274                                     var suggestion = void 0;
49275                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
49276                                         var propDeclaration = prop.valueDeclaration;
49277                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
49278                                         errorNode = propDeclaration;
49279                                         var name = propDeclaration.name;
49280                                         if (ts.isIdentifier(name)) {
49281                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
49282                                         }
49283                                     }
49284                                     if (suggestion !== undefined) {
49285                                         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);
49286                                     }
49287                                     else {
49288                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
49289                                     }
49290                                 }
49291                             }
49292                             return { value: true };
49293                         }
49294                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
49295                             if (reportErrors) {
49296                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
49297                             }
49298                             return { value: true };
49299                         }
49300                     }
49301                 };
49302                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
49303                     var prop = _a[_i];
49304                     var state_5 = _loop_13(prop);
49305                     if (typeof state_5 === "object")
49306                         return state_5.value;
49307                 }
49308                 return false;
49309             }
49310             function shouldCheckAsExcessProperty(prop, container) {
49311                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
49312             }
49313             function eachTypeRelatedToSomeType(source, target) {
49314                 var result = -1 /* True */;
49315                 var sourceTypes = source.types;
49316                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
49317                     var sourceType = sourceTypes_1[_i];
49318                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
49319                     if (!related) {
49320                         return 0 /* False */;
49321                     }
49322                     result &= related;
49323                 }
49324                 return result;
49325             }
49326             function typeRelatedToSomeType(source, target, reportErrors) {
49327                 var targetTypes = target.types;
49328                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
49329                     return -1 /* True */;
49330                 }
49331                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
49332                     var type = targetTypes_1[_i];
49333                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
49334                     if (related) {
49335                         return related;
49336                     }
49337                 }
49338                 if (reportErrors) {
49339                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
49340                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
49341                 }
49342                 return 0 /* False */;
49343             }
49344             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
49345                 var result = -1 /* True */;
49346                 var targetTypes = target.types;
49347                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
49348                     var targetType = targetTypes_2[_i];
49349                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
49350                     if (!related) {
49351                         return 0 /* False */;
49352                     }
49353                     result &= related;
49354                 }
49355                 return result;
49356             }
49357             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
49358                 var sourceTypes = source.types;
49359                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
49360                     return -1 /* True */;
49361                 }
49362                 var len = sourceTypes.length;
49363                 for (var i = 0; i < len; i++) {
49364                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
49365                     if (related) {
49366                         return related;
49367                     }
49368                 }
49369                 return 0 /* False */;
49370             }
49371             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
49372                 var result = -1 /* True */;
49373                 var sourceTypes = source.types;
49374                 for (var i = 0; i < sourceTypes.length; i++) {
49375                     var sourceType = sourceTypes[i];
49376                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
49377                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
49378                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
49379                         if (related_1) {
49380                             result &= related_1;
49381                             continue;
49382                         }
49383                     }
49384                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
49385                     if (!related) {
49386                         return 0 /* False */;
49387                     }
49388                     result &= related;
49389                 }
49390                 return result;
49391             }
49392             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
49393                 if (sources === void 0) { sources = ts.emptyArray; }
49394                 if (targets === void 0) { targets = ts.emptyArray; }
49395                 if (variances === void 0) { variances = ts.emptyArray; }
49396                 if (sources.length !== targets.length && relation === identityRelation) {
49397                     return 0 /* False */;
49398                 }
49399                 var length = sources.length <= targets.length ? sources.length : targets.length;
49400                 var result = -1 /* True */;
49401                 for (var i = 0; i < length; i++) {
49402                     // When variance information isn't available we default to covariance. This happens
49403                     // in the process of computing variance information for recursive types and when
49404                     // comparing 'this' type arguments.
49405                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
49406                     var variance = varianceFlags & 7 /* VarianceMask */;
49407                     // We ignore arguments for independent type parameters (because they're never witnessed).
49408                     if (variance !== 4 /* Independent */) {
49409                         var s = sources[i];
49410                         var t = targets[i];
49411                         var related = -1 /* True */;
49412                         if (varianceFlags & 8 /* Unmeasurable */) {
49413                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
49414                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
49415                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
49416                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
49417                         }
49418                         else if (variance === 1 /* Covariant */) {
49419                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49420                         }
49421                         else if (variance === 2 /* Contravariant */) {
49422                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49423                         }
49424                         else if (variance === 3 /* Bivariant */) {
49425                             // In the bivariant case we first compare contravariantly without reporting
49426                             // errors. Then, if that doesn't succeed, we compare covariantly with error
49427                             // reporting. Thus, error elaboration will be based on the the covariant check,
49428                             // which is generally easier to reason about.
49429                             related = isRelatedTo(t, s, /*reportErrors*/ false);
49430                             if (!related) {
49431                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49432                             }
49433                         }
49434                         else {
49435                             // In the invariant case we first compare covariantly, and only when that
49436                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
49437                             // will typically be based on the covariant check.
49438                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
49439                             if (related) {
49440                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
49441                             }
49442                         }
49443                         if (!related) {
49444                             return 0 /* False */;
49445                         }
49446                         result &= related;
49447                     }
49448                 }
49449                 return result;
49450             }
49451             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
49452             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
49453             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
49454             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
49455             // and issue an error. Otherwise, actually compare the structure of the two types.
49456             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
49457                 if (overflow) {
49458                     return 0 /* False */;
49459                 }
49460                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
49461                 var entry = relation.get(id);
49462                 if (entry !== undefined) {
49463                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
49464                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
49465                         // as a failure, and should be updated as a reported failure by the bottom of this function.
49466                     }
49467                     else {
49468                         if (outofbandVarianceMarkerHandler) {
49469                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
49470                             var saved = entry & 24 /* ReportsMask */;
49471                             if (saved & 8 /* ReportsUnmeasurable */) {
49472                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
49473                             }
49474                             if (saved & 16 /* ReportsUnreliable */) {
49475                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
49476                             }
49477                         }
49478                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
49479                     }
49480                 }
49481                 if (!maybeKeys) {
49482                     maybeKeys = [];
49483                     sourceStack = [];
49484                     targetStack = [];
49485                 }
49486                 else {
49487                     for (var i = 0; i < maybeCount; i++) {
49488                         // If source and target are already being compared, consider them related with assumptions
49489                         if (id === maybeKeys[i]) {
49490                             return 1 /* Maybe */;
49491                         }
49492                     }
49493                     if (depth === 100) {
49494                         overflow = true;
49495                         return 0 /* False */;
49496                     }
49497                 }
49498                 var maybeStart = maybeCount;
49499                 maybeKeys[maybeCount] = id;
49500                 maybeCount++;
49501                 sourceStack[depth] = source;
49502                 targetStack[depth] = target;
49503                 depth++;
49504                 var saveExpandingFlags = expandingFlags;
49505                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
49506                     expandingFlags |= 1 /* Source */;
49507                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
49508                     expandingFlags |= 2 /* Target */;
49509                 var originalHandler;
49510                 var propagatingVarianceFlags = 0;
49511                 if (outofbandVarianceMarkerHandler) {
49512                     originalHandler = outofbandVarianceMarkerHandler;
49513                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
49514                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
49515                         return originalHandler(onlyUnreliable);
49516                     };
49517                 }
49518                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 1 /* Maybe */;
49519                 if (outofbandVarianceMarkerHandler) {
49520                     outofbandVarianceMarkerHandler = originalHandler;
49521                 }
49522                 expandingFlags = saveExpandingFlags;
49523                 depth--;
49524                 if (result) {
49525                     if (result === -1 /* True */ || depth === 0) {
49526                         // If result is definitely true, record all maybe keys as having succeeded
49527                         for (var i = maybeStart; i < maybeCount; i++) {
49528                             relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
49529                         }
49530                         maybeCount = maybeStart;
49531                     }
49532                 }
49533                 else {
49534                     // A false result goes straight into global cache (when something is false under
49535                     // assumptions it will also be false without assumptions)
49536                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
49537                     maybeCount = maybeStart;
49538                 }
49539                 return result;
49540             }
49541             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
49542                 if (intersectionState & 4 /* PropertyCheck */) {
49543                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
49544                 }
49545                 var flags = source.flags & target.flags;
49546                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
49547                     if (flags & 4194304 /* Index */) {
49548                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
49549                     }
49550                     var result_6 = 0 /* False */;
49551                     if (flags & 8388608 /* IndexedAccess */) {
49552                         if (result_6 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
49553                             if (result_6 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
49554                                 return result_6;
49555                             }
49556                         }
49557                     }
49558                     if (flags & 16777216 /* Conditional */) {
49559                         if (source.root.isDistributive === target.root.isDistributive) {
49560                             if (result_6 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
49561                                 if (result_6 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
49562                                     if (result_6 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
49563                                         if (result_6 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
49564                                             return result_6;
49565                                         }
49566                                     }
49567                                 }
49568                             }
49569                         }
49570                     }
49571                     if (flags & 33554432 /* Substitution */) {
49572                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
49573                     }
49574                     return 0 /* False */;
49575                 }
49576                 var result;
49577                 var originalErrorInfo;
49578                 var varianceCheckFailed = false;
49579                 var saveErrorInfo = captureErrorCalculationState();
49580                 // We limit alias variance probing to only object and conditional types since their alias behavior
49581                 // is more predictable than other, interned types, which may or may not have an alias depending on
49582                 // the order in which things were checked.
49583                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
49584                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
49585                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
49586                     var variances = getAliasVariances(source.aliasSymbol);
49587                     if (variances === ts.emptyArray) {
49588                         return 1 /* Maybe */;
49589                     }
49590                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
49591                     if (varianceResult !== undefined) {
49592                         return varianceResult;
49593                     }
49594                 }
49595                 if (target.flags & 262144 /* TypeParameter */) {
49596                     // 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].
49597                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
49598                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
49599                             var templateType = getTemplateTypeFromMappedType(source);
49600                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
49601                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
49602                                 return result;
49603                             }
49604                         }
49605                     }
49606                 }
49607                 else if (target.flags & 4194304 /* Index */) {
49608                     // A keyof S is related to a keyof T if T is related to S.
49609                     if (source.flags & 4194304 /* Index */) {
49610                         if (result = isRelatedTo(target.type, source.type, /*reportErrors*/ false)) {
49611                             return result;
49612                         }
49613                     }
49614                     // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
49615                     // simplified form of T or, if T doesn't simplify, the constraint of T.
49616                     var constraint = getSimplifiedTypeOrConstraint(target.type);
49617                     if (constraint) {
49618                         // We require Ternary.True here such that circular constraints don't cause
49619                         // false positives. For example, given 'T extends { [K in keyof T]: string }',
49620                         // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
49621                         // related to other types.
49622                         if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
49623                             return -1 /* True */;
49624                         }
49625                     }
49626                 }
49627                 else if (target.flags & 8388608 /* IndexedAccess */) {
49628                     // A type S is related to a type T[K] if S is related to C, where C is the base
49629                     // constraint of T[K] for writing.
49630                     if (relation !== identityRelation) {
49631                         var objectType = target.objectType;
49632                         var indexType = target.indexType;
49633                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
49634                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
49635                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
49636                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
49637                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, /*accessNode*/ undefined, accessFlags);
49638                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
49639                                 return result;
49640                             }
49641                         }
49642                     }
49643                 }
49644                 else if (isGenericMappedType(target)) {
49645                     // A source type T is related to a target type { [P in X]: T[P] }
49646                     var template = getTemplateTypeFromMappedType(target);
49647                     var modifiers = getMappedTypeModifiers(target);
49648                     if (!(modifiers & 8 /* ExcludeOptional */)) {
49649                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
49650                             template.indexType === getTypeParameterFromMappedType(target)) {
49651                             return -1 /* True */;
49652                         }
49653                         if (!isGenericMappedType(source)) {
49654                             var targetConstraint = getConstraintTypeFromMappedType(target);
49655                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
49656                             var includeOptional = modifiers & 4 /* IncludeOptional */;
49657                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
49658                             // 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.
49659                             // 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.
49660                             if (includeOptional
49661                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
49662                                 : isRelatedTo(targetConstraint, sourceKeys)) {
49663                                 var typeParameter = getTypeParameterFromMappedType(target);
49664                                 var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
49665                                 var indexedAccessType = getIndexedAccessType(source, indexingType);
49666                                 var templateType = getTemplateTypeFromMappedType(target);
49667                                 if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
49668                                     return result;
49669                                 }
49670                             }
49671                             originalErrorInfo = errorInfo;
49672                             resetErrorInfo(saveErrorInfo);
49673                         }
49674                     }
49675                 }
49676                 if (source.flags & 8650752 /* TypeVariable */) {
49677                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
49678                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
49679                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
49680                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
49681                         }
49682                         if (result) {
49683                             resetErrorInfo(saveErrorInfo);
49684                             return result;
49685                         }
49686                     }
49687                     else {
49688                         var constraint = getConstraintOfType(source);
49689                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
49690                             // A type variable with no constraint is not related to the non-primitive object type.
49691                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
49692                                 resetErrorInfo(saveErrorInfo);
49693                                 return result;
49694                             }
49695                         }
49696                         // 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
49697                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
49698                             resetErrorInfo(saveErrorInfo);
49699                             return result;
49700                         }
49701                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
49702                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
49703                             resetErrorInfo(saveErrorInfo);
49704                             return result;
49705                         }
49706                     }
49707                 }
49708                 else if (source.flags & 4194304 /* Index */) {
49709                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
49710                         resetErrorInfo(saveErrorInfo);
49711                         return result;
49712                     }
49713                 }
49714                 else if (source.flags & 16777216 /* Conditional */) {
49715                     if (target.flags & 16777216 /* Conditional */) {
49716                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
49717                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
49718                         // and Y1 is related to Y2.
49719                         var sourceParams = source.root.inferTypeParameters;
49720                         var sourceExtends = source.extendsType;
49721                         var mapper = void 0;
49722                         if (sourceParams) {
49723                             // If the source has infer type parameters, we instantiate them in the context of the target
49724                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
49725                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 128 /* NoConstraints */ | 256 /* AlwaysStrict */);
49726                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
49727                             mapper = ctx.mapper;
49728                         }
49729                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
49730                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
49731                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
49732                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
49733                             }
49734                             if (result) {
49735                                 resetErrorInfo(saveErrorInfo);
49736                                 return result;
49737                             }
49738                         }
49739                     }
49740                     else {
49741                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
49742                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
49743                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
49744                         if (distributiveConstraint) {
49745                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
49746                                 resetErrorInfo(saveErrorInfo);
49747                                 return result;
49748                             }
49749                         }
49750                     }
49751                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
49752                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
49753                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
49754                     if (defaultConstraint) {
49755                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
49756                             resetErrorInfo(saveErrorInfo);
49757                             return result;
49758                         }
49759                     }
49760                 }
49761                 else {
49762                     // An empty object type is related to any mapped type that includes a '?' modifier.
49763                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
49764                         return -1 /* True */;
49765                     }
49766                     if (isGenericMappedType(target)) {
49767                         if (isGenericMappedType(source)) {
49768                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
49769                                 resetErrorInfo(saveErrorInfo);
49770                                 return result;
49771                             }
49772                         }
49773                         return 0 /* False */;
49774                     }
49775                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
49776                     if (relation !== identityRelation) {
49777                         source = getApparentType(source);
49778                     }
49779                     else if (isGenericMappedType(source)) {
49780                         return 0 /* False */;
49781                     }
49782                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
49783                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
49784                         // We have type references to the same generic type, and the type references are not marker
49785                         // type references (which are intended by be compared structurally). Obtain the variance
49786                         // information for the type parameters and relate the type arguments accordingly.
49787                         var variances = getVariances(source.target);
49788                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
49789                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
49790                         // recursive instantiations of the generic type.
49791                         if (variances === ts.emptyArray) {
49792                             return 1 /* Maybe */;
49793                         }
49794                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
49795                         if (varianceResult !== undefined) {
49796                             return varianceResult;
49797                         }
49798                     }
49799                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
49800                         if (relation !== identityRelation) {
49801                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
49802                         }
49803                         else {
49804                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
49805                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
49806                             return 0 /* False */;
49807                         }
49808                     }
49809                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
49810                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
49811                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
49812                         return 0 /* False */;
49813                     }
49814                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
49815                     // it may hold in a structural comparison.
49816                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
49817                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
49818                     // relates to X. Thus, we include intersection types on the source side here.
49819                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
49820                         // Report structural errors only if we haven't reported any errors yet
49821                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
49822                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
49823                         if (result) {
49824                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
49825                             if (result) {
49826                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
49827                                 if (result) {
49828                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49829                                     if (result) {
49830                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
49831                                     }
49832                                 }
49833                             }
49834                         }
49835                         if (varianceCheckFailed && result) {
49836                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
49837                         }
49838                         else if (result) {
49839                             return result;
49840                         }
49841                     }
49842                     // If S is an object type and T is a discriminated union, S may be related to T if
49843                     // there exists a constituent of T for every combination of the discriminants of S
49844                     // with respect to T. We do not report errors here, as we will use the existing
49845                     // error result from checking each constituent of the union.
49846                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
49847                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
49848                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
49849                             var result_7 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
49850                             if (result_7) {
49851                                 return result_7;
49852                             }
49853                         }
49854                     }
49855                 }
49856                 return 0 /* False */;
49857                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
49858                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
49859                         return result;
49860                     }
49861                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
49862                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
49863                         // have to allow a structural fallback check
49864                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
49865                         // be assuming identity of the type parameter.
49866                         originalErrorInfo = undefined;
49867                         resetErrorInfo(saveErrorInfo);
49868                         return undefined;
49869                     }
49870                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
49871                     varianceCheckFailed = !allowStructuralFallback;
49872                     // The type arguments did not relate appropriately, but it may be because we have no variance
49873                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
49874                     // arguments). It might also be the case that the target type has a 'void' type argument for
49875                     // a covariant type parameter that is only used in return positions within the generic type
49876                     // (in which case any type argument is permitted on the source side). In those cases we proceed
49877                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
49878                     // related and we can return here.
49879                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
49880                         // In some cases generic types that are covariant in regular type checking mode become
49881                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
49882                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
49883                         // types are invariant, if any of the type parameters are invariant we reset the reported
49884                         // errors and instead force a structural comparison (which will include elaborations that
49885                         // reveal the reason).
49886                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
49887                         // we can return `False` early here to skip calculating the structural error message we don't need.
49888                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
49889                             return 0 /* False */;
49890                         }
49891                         // We remember the original error information so we can restore it in case the structural
49892                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
49893                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
49894                         originalErrorInfo = errorInfo;
49895                         resetErrorInfo(saveErrorInfo);
49896                     }
49897                 }
49898             }
49899             function reportUnmeasurableMarkers(p) {
49900                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49901                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
49902                 }
49903                 return p;
49904             }
49905             function reportUnreliableMarkers(p) {
49906                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
49907                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
49908                 }
49909                 return p;
49910             }
49911             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
49912             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
49913             // that S and T are contra-variant whereas X and Y are co-variant.
49914             function mappedTypeRelatedTo(source, target, reportErrors) {
49915                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
49916                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
49917                 if (modifiersRelated) {
49918                     var result_8;
49919                     var targetConstraint = getConstraintTypeFromMappedType(target);
49920                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
49921                     if (result_8 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
49922                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
49923                         return result_8 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
49924                     }
49925                 }
49926                 return 0 /* False */;
49927             }
49928             function typeRelatedToDiscriminatedType(source, target) {
49929                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
49930                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
49931                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
49932                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
49933                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
49934                 //    'target' are related to a property in 'source'.
49935                 //
49936                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
49937                 //       for examples.
49938                 var sourceProperties = getPropertiesOfType(source);
49939                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
49940                 if (!sourcePropertiesFiltered)
49941                     return 0 /* False */;
49942                 // Though we could compute the number of combinations as we generate
49943                 // the matrix, this would incur additional memory overhead due to
49944                 // array allocations. To reduce this overhead, we first compute
49945                 // the number of combinations to ensure we will not surpass our
49946                 // fixed limit before incurring the cost of any allocations:
49947                 var numCombinations = 1;
49948                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
49949                     var sourceProperty = sourcePropertiesFiltered_1[_i];
49950                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
49951                     if (numCombinations > 25) {
49952                         // We've reached the complexity limit.
49953                         return 0 /* False */;
49954                     }
49955                 }
49956                 // Compute the set of types for each discriminant property.
49957                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
49958                 var excludedProperties = ts.createUnderscoreEscapedMap();
49959                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49960                     var sourceProperty = sourcePropertiesFiltered[i];
49961                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
49962                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
49963                         ? sourcePropertyType.types
49964                         : [sourcePropertyType];
49965                     excludedProperties.set(sourceProperty.escapedName, true);
49966                 }
49967                 // Match each combination of the cartesian product of discriminant properties to one or more
49968                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
49969                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
49970                 var matchingTypes = [];
49971                 var _loop_14 = function (combination) {
49972                     var hasMatch = false;
49973                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
49974                         var type = _a[_i];
49975                         var _loop_15 = function (i) {
49976                             var sourceProperty = sourcePropertiesFiltered[i];
49977                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
49978                             if (!targetProperty)
49979                                 return "continue-outer";
49980                             if (sourceProperty === targetProperty)
49981                                 return "continue";
49982                             // We compare the source property to the target in the context of a single discriminant type.
49983                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
49984                             // If the target property could not be found, or if the properties were not related,
49985                             // then this constituent is not a match.
49986                             if (!related) {
49987                                 return "continue-outer";
49988                             }
49989                         };
49990                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
49991                             var state_7 = _loop_15(i);
49992                             switch (state_7) {
49993                                 case "continue-outer": continue outer;
49994                             }
49995                         }
49996                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
49997                         hasMatch = true;
49998                     }
49999                     if (!hasMatch) {
50000                         return { value: 0 /* False */ };
50001                     }
50002                 };
50003                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
50004                     var combination = discriminantCombinations_1[_a];
50005                     var state_6 = _loop_14(combination);
50006                     if (typeof state_6 === "object")
50007                         return state_6.value;
50008                 }
50009                 // Compare the remaining non-discriminant properties of each match.
50010                 var result = -1 /* True */;
50011                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
50012                     var type = matchingTypes_1[_b];
50013                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
50014                     if (result) {
50015                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
50016                         if (result) {
50017                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
50018                             if (result) {
50019                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50020                                 if (result) {
50021                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
50022                                 }
50023                             }
50024                         }
50025                     }
50026                     if (!result) {
50027                         return result;
50028                     }
50029                 }
50030                 return result;
50031             }
50032             function excludeProperties(properties, excludedProperties) {
50033                 if (!excludedProperties || properties.length === 0)
50034                     return properties;
50035                 var result;
50036                 for (var i = 0; i < properties.length; i++) {
50037                     if (!excludedProperties.has(properties[i].escapedName)) {
50038                         if (result) {
50039                             result.push(properties[i]);
50040                         }
50041                     }
50042                     else if (!result) {
50043                         result = properties.slice(0, i);
50044                     }
50045                 }
50046                 return result || properties;
50047             }
50048             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
50049                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
50050                 var source = getTypeOfSourceProperty(sourceProp);
50051                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
50052                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
50053                     var links = getSymbolLinks(targetProp);
50054                     ts.Debug.assertIsDefined(links.deferralParent);
50055                     ts.Debug.assertIsDefined(links.deferralConstituents);
50056                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
50057                     var result_9 = unionParent ? 0 /* False */ : -1 /* True */;
50058                     var targetTypes = links.deferralConstituents;
50059                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
50060                         var targetType = targetTypes_3[_i];
50061                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
50062                         if (!unionParent) {
50063                             if (!related) {
50064                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
50065                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50066                             }
50067                             result_9 &= related;
50068                         }
50069                         else {
50070                             if (related) {
50071                                 return related;
50072                             }
50073                         }
50074                     }
50075                     if (unionParent && !result_9 && targetIsOptional) {
50076                         result_9 = isRelatedTo(source, undefinedType);
50077                     }
50078                     if (unionParent && !result_9 && reportErrors) {
50079                         // The easiest way to get the right errors here is to un-defer (which may be costly)
50080                         // If it turns out this is too costly too often, we can replicate the error handling logic within
50081                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
50082                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
50083                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
50084                     }
50085                     return result_9;
50086                 }
50087                 else {
50088                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
50089                 }
50090             }
50091             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
50092                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
50093                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
50094                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
50095                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
50096                         if (reportErrors) {
50097                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
50098                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
50099                             }
50100                             else {
50101                                 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));
50102                             }
50103                         }
50104                         return 0 /* False */;
50105                     }
50106                 }
50107                 else if (targetPropFlags & 16 /* Protected */) {
50108                     if (!isValidOverrideOf(sourceProp, targetProp)) {
50109                         if (reportErrors) {
50110                             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));
50111                         }
50112                         return 0 /* False */;
50113                     }
50114                 }
50115                 else if (sourcePropFlags & 16 /* Protected */) {
50116                     if (reportErrors) {
50117                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50118                     }
50119                     return 0 /* False */;
50120                 }
50121                 // If the target comes from a partial union prop, allow `undefined` in the target type
50122                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
50123                 if (!related) {
50124                     if (reportErrors) {
50125                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
50126                     }
50127                     return 0 /* False */;
50128                 }
50129                 // When checking for comparability, be more lenient with optional properties.
50130                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
50131                     // TypeScript 1.0 spec (April 2014): 3.8.3
50132                     // S is a subtype of a type T, and T is a supertype of S if ...
50133                     // S' and T are object types and, for each member M in T..
50134                     // M is a property and S' contains a property N where
50135                     // if M is a required property, N is also a required property
50136                     // (M - property in T)
50137                     // (N - property in S)
50138                     if (reportErrors) {
50139                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
50140                     }
50141                     return 0 /* False */;
50142                 }
50143                 return related;
50144             }
50145             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
50146                 var shouldSkipElaboration = false;
50147                 // give specific error in case where private names have the same description
50148                 if (unmatchedProperty.valueDeclaration
50149                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
50150                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
50151                     && source.symbol
50152                     && source.symbol.flags & 32 /* Class */) {
50153                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
50154                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
50155                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
50156                         var sourceName = ts.getDeclarationName(source.symbol.valueDeclaration);
50157                         var targetName = ts.getDeclarationName(target.symbol.valueDeclaration);
50158                         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));
50159                         return;
50160                     }
50161                 }
50162                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
50163                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
50164                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
50165                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
50166                 }
50167                 if (props.length === 1) {
50168                     var propName = symbolToString(unmatchedProperty);
50169                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
50170                     if (ts.length(unmatchedProperty.declarations)) {
50171                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
50172                     }
50173                     if (shouldSkipElaboration && errorInfo) {
50174                         overrideNextErrorInfo++;
50175                     }
50176                 }
50177                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
50178                     if (props.length > 5) { // arbitrary cutoff for too-long list form
50179                         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);
50180                     }
50181                     else {
50182                         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(", "));
50183                     }
50184                     if (shouldSkipElaboration && errorInfo) {
50185                         overrideNextErrorInfo++;
50186                     }
50187                 }
50188                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
50189             }
50190             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
50191                 if (relation === identityRelation) {
50192                     return propertiesIdenticalTo(source, target, excludedProperties);
50193                 }
50194                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
50195                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
50196                 if (unmatchedProperty) {
50197                     if (reportErrors) {
50198                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
50199                     }
50200                     return 0 /* False */;
50201                 }
50202                 if (isObjectLiteralType(target)) {
50203                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
50204                         var sourceProp = _a[_i];
50205                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
50206                             var sourceType = getTypeOfSymbol(sourceProp);
50207                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
50208                                 if (reportErrors) {
50209                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
50210                                 }
50211                                 return 0 /* False */;
50212                             }
50213                         }
50214                     }
50215                 }
50216                 var result = -1 /* True */;
50217                 if (isTupleType(target)) {
50218                     var targetRestType = getRestTypeOfTupleType(target);
50219                     if (targetRestType) {
50220                         if (!isTupleType(source)) {
50221                             return 0 /* False */;
50222                         }
50223                         var sourceRestType = getRestTypeOfTupleType(source);
50224                         if (sourceRestType && !isRelatedTo(sourceRestType, targetRestType, reportErrors)) {
50225                             if (reportErrors) {
50226                                 reportError(ts.Diagnostics.Rest_signatures_are_incompatible);
50227                             }
50228                             return 0 /* False */;
50229                         }
50230                         var targetCount = getTypeReferenceArity(target) - 1;
50231                         var sourceCount = getTypeReferenceArity(source) - (sourceRestType ? 1 : 0);
50232                         var sourceTypeArguments = getTypeArguments(source);
50233                         for (var i = targetCount; i < sourceCount; i++) {
50234                             var related = isRelatedTo(sourceTypeArguments[i], targetRestType, reportErrors);
50235                             if (!related) {
50236                                 if (reportErrors) {
50237                                     reportError(ts.Diagnostics.Property_0_is_incompatible_with_rest_element_type, "" + i);
50238                                 }
50239                                 return 0 /* False */;
50240                             }
50241                             result &= related;
50242                         }
50243                     }
50244                 }
50245                 // 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_
50246                 // from the target union, across all members
50247                 var properties = getPropertiesOfType(target);
50248                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
50249                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
50250                     var targetProp = _c[_b];
50251                     var name = targetProp.escapedName;
50252                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
50253                         var sourceProp = getPropertyOfType(source, name);
50254                         if (sourceProp && sourceProp !== targetProp) {
50255                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
50256                             if (!related) {
50257                                 return 0 /* False */;
50258                             }
50259                             result &= related;
50260                         }
50261                     }
50262                 }
50263                 return result;
50264             }
50265             function propertiesIdenticalTo(source, target, excludedProperties) {
50266                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
50267                     return 0 /* False */;
50268                 }
50269                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
50270                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
50271                 if (sourceProperties.length !== targetProperties.length) {
50272                     return 0 /* False */;
50273                 }
50274                 var result = -1 /* True */;
50275                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
50276                     var sourceProp = sourceProperties_1[_i];
50277                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
50278                     if (!targetProp) {
50279                         return 0 /* False */;
50280                     }
50281                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
50282                     if (!related) {
50283                         return 0 /* False */;
50284                     }
50285                     result &= related;
50286                 }
50287                 return result;
50288             }
50289             function signaturesRelatedTo(source, target, kind, reportErrors) {
50290                 if (relation === identityRelation) {
50291                     return signaturesIdenticalTo(source, target, kind);
50292                 }
50293                 if (target === anyFunctionType || source === anyFunctionType) {
50294                     return -1 /* True */;
50295                 }
50296                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
50297                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
50298                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
50299                     0 /* Call */ : kind);
50300                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
50301                     0 /* Call */ : kind);
50302                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
50303                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
50304                         // An abstract constructor type is not assignable to a non-abstract constructor type
50305                         // as it would otherwise be possible to new an abstract class. Note that the assignability
50306                         // check we perform for an extends clause excludes construct signatures from the target,
50307                         // so this check never proceeds.
50308                         if (reportErrors) {
50309                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
50310                         }
50311                         return 0 /* False */;
50312                     }
50313                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
50314                         return 0 /* False */;
50315                     }
50316                 }
50317                 var result = -1 /* True */;
50318                 var saveErrorInfo = captureErrorCalculationState();
50319                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
50320                 if (ts.getObjectFlags(source) & 64 /* Instantiated */ && ts.getObjectFlags(target) & 64 /* Instantiated */ && source.symbol === target.symbol) {
50321                     // We have instantiations of the same anonymous type (which typically will be the type of a
50322                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
50323                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
50324                     // as they are known to always be the same.
50325                     for (var i = 0; i < targetSignatures.length; i++) {
50326                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
50327                         if (!related) {
50328                             return 0 /* False */;
50329                         }
50330                         result &= related;
50331                     }
50332                 }
50333                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
50334                     // For simple functions (functions with a single signature) we only erase type parameters for
50335                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
50336                     // in the context of the target signature before checking the relationship. Ideally we'd do
50337                     // this regardless of the number of signatures, but the potential costs are prohibitive due
50338                     // to the quadratic nature of the logic below.
50339                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
50340                     result = signatureRelatedTo(sourceSignatures[0], targetSignatures[0], eraseGenerics, reportErrors, incompatibleReporter(sourceSignatures[0], targetSignatures[0]));
50341                 }
50342                 else {
50343                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
50344                         var t = targetSignatures_1[_i];
50345                         // Only elaborate errors from the first failure
50346                         var shouldElaborateErrors = reportErrors;
50347                         for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) {
50348                             var s = sourceSignatures_1[_a];
50349                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
50350                             if (related) {
50351                                 result &= related;
50352                                 resetErrorInfo(saveErrorInfo);
50353                                 continue outer;
50354                             }
50355                             shouldElaborateErrors = false;
50356                         }
50357                         if (shouldElaborateErrors) {
50358                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
50359                         }
50360                         return 0 /* False */;
50361                     }
50362                 }
50363                 return result;
50364             }
50365             function reportIncompatibleCallSignatureReturn(siga, sigb) {
50366                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50367                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50368                 }
50369                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50370             }
50371             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
50372                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
50373                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
50374                 }
50375                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
50376             }
50377             /**
50378              * See signatureAssignableTo, compareSignaturesIdentical
50379              */
50380             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
50381                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
50382             }
50383             function signaturesIdenticalTo(source, target, kind) {
50384                 var sourceSignatures = getSignaturesOfType(source, kind);
50385                 var targetSignatures = getSignaturesOfType(target, kind);
50386                 if (sourceSignatures.length !== targetSignatures.length) {
50387                     return 0 /* False */;
50388                 }
50389                 var result = -1 /* True */;
50390                 for (var i = 0; i < sourceSignatures.length; i++) {
50391                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
50392                     if (!related) {
50393                         return 0 /* False */;
50394                     }
50395                     result &= related;
50396                 }
50397                 return result;
50398             }
50399             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
50400                 var result = -1 /* True */;
50401                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
50402                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
50403                     var prop = props_2[_i];
50404                     // Skip over ignored JSX and symbol-named members
50405                     if (isIgnoredJsxProperty(source, prop)) {
50406                         continue;
50407                     }
50408                     var nameType = getSymbolLinks(prop).nameType;
50409                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
50410                         continue;
50411                     }
50412                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
50413                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
50414                         if (!related) {
50415                             if (reportErrors) {
50416                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
50417                             }
50418                             return 0 /* False */;
50419                         }
50420                         result &= related;
50421                     }
50422                 }
50423                 return result;
50424             }
50425             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
50426                 var related = isRelatedTo(sourceType, targetType, reportErrors);
50427                 if (!related && reportErrors) {
50428                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
50429                 }
50430                 return related;
50431             }
50432             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
50433                 if (relation === identityRelation) {
50434                     return indexTypesIdenticalTo(source, target, kind);
50435                 }
50436                 var targetType = getIndexTypeOfType(target, kind);
50437                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
50438                     // Index signature of type any permits assignment from everything but primitives
50439                     return -1 /* True */;
50440                 }
50441                 if (isGenericMappedType(source)) {
50442                     // A generic mapped type { [P in K]: T } is related to an index signature { [x: string]: U }
50443                     // if T is related to U.
50444                     return kind === 0 /* String */ ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
50445                 }
50446                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
50447                 if (indexType) {
50448                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
50449                 }
50450                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
50451                     // Intersection constituents are never considered to have an inferred index signature
50452                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
50453                     if (related && kind === 0 /* String */) {
50454                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
50455                         if (numberIndexType) {
50456                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
50457                         }
50458                     }
50459                     return related;
50460                 }
50461                 if (reportErrors) {
50462                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
50463                 }
50464                 return 0 /* False */;
50465             }
50466             function indexTypesIdenticalTo(source, target, indexKind) {
50467                 var targetInfo = getIndexInfoOfType(target, indexKind);
50468                 var sourceInfo = getIndexInfoOfType(source, indexKind);
50469                 if (!sourceInfo && !targetInfo) {
50470                     return -1 /* True */;
50471                 }
50472                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
50473                     return isRelatedTo(sourceInfo.type, targetInfo.type);
50474                 }
50475                 return 0 /* False */;
50476             }
50477             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
50478                 if (!sourceSignature.declaration || !targetSignature.declaration) {
50479                     return true;
50480                 }
50481                 var sourceAccessibility = ts.getSelectedModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50482                 var targetAccessibility = ts.getSelectedModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
50483                 // A public, protected and private signature is assignable to a private signature.
50484                 if (targetAccessibility === 8 /* Private */) {
50485                     return true;
50486                 }
50487                 // A public and protected signature is assignable to a protected signature.
50488                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
50489                     return true;
50490                 }
50491                 // Only a public signature is assignable to public signature.
50492                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
50493                     return true;
50494                 }
50495                 if (reportErrors) {
50496                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
50497                 }
50498                 return false;
50499             }
50500         }
50501         function getBestMatchingType(source, target, isRelatedTo) {
50502             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
50503             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
50504                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
50505                 findBestTypeForObjectLiteral(source, target) ||
50506                 findBestTypeForInvokable(source, target) ||
50507                 findMostOverlappyType(source, target);
50508         }
50509         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
50510             // undefined=unknown, true=discriminated, false=not discriminated
50511             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
50512             var discriminable = target.types.map(function (_) { return undefined; });
50513             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
50514                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
50515                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
50516                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
50517                     continue;
50518                 }
50519                 var i = 0;
50520                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
50521                     var type = _c[_b];
50522                     var targetType = getTypeOfPropertyOfType(type, propertyName);
50523                     if (targetType && related(getDiscriminatingType(), targetType)) {
50524                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
50525                     }
50526                     else {
50527                         discriminable[i] = false;
50528                     }
50529                     i++;
50530                 }
50531             }
50532             var match = discriminable.indexOf(/*searchElement*/ true);
50533             // make sure exactly 1 matches before returning it
50534             return match === -1 || discriminable.indexOf(/*searchElement*/ true, match + 1) !== -1 ? defaultValue : target.types[match];
50535         }
50536         /**
50537          * A type is 'weak' if it is an object type with at least one optional property
50538          * and no required properties, call/construct signatures or index signatures
50539          */
50540         function isWeakType(type) {
50541             if (type.flags & 524288 /* Object */) {
50542                 var resolved = resolveStructuredTypeMembers(type);
50543                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
50544                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
50545                     resolved.properties.length > 0 &&
50546                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
50547             }
50548             if (type.flags & 2097152 /* Intersection */) {
50549                 return ts.every(type.types, isWeakType);
50550             }
50551             return false;
50552         }
50553         function hasCommonProperties(source, target, isComparingJsxAttributes) {
50554             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50555                 var prop = _a[_i];
50556                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
50557                     return true;
50558                 }
50559             }
50560             return false;
50561         }
50562         // Return a type reference where the source type parameter is replaced with the target marker
50563         // type, and flag the result as a marker type reference.
50564         function getMarkerTypeReference(type, source, target) {
50565             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
50566             result.objectFlags |= 8192 /* MarkerType */;
50567             return result;
50568         }
50569         function getAliasVariances(symbol) {
50570             var links = getSymbolLinks(symbol);
50571             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
50572                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
50573                 type.aliasTypeArgumentsContainsMarker = true;
50574                 return type;
50575             });
50576         }
50577         // Return an array containing the variance of each type parameter. The variance is effectively
50578         // a digest of the type comparisons that occur for each type argument when instantiations of the
50579         // generic type are structurally compared. We infer the variance information by comparing
50580         // instantiations of the generic type for type arguments with known relations. The function
50581         // returns the emptyArray singleton when invoked recursively for the given generic type.
50582         function getVariancesWorker(typeParameters, cache, createMarkerType) {
50583             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
50584             var variances = cache.variances;
50585             if (!variances) {
50586                 // The emptyArray singleton is used to signal a recursive invocation.
50587                 cache.variances = ts.emptyArray;
50588                 variances = [];
50589                 var _loop_16 = function (tp) {
50590                     var unmeasurable = false;
50591                     var unreliable = false;
50592                     var oldHandler = outofbandVarianceMarkerHandler;
50593                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
50594                     // We first compare instantiations where the type parameter is replaced with
50595                     // marker types that have a known subtype relationship. From this we can infer
50596                     // invariance, covariance, contravariance or bivariance.
50597                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
50598                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
50599                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
50600                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
50601                     // If the instantiations appear to be related bivariantly it may be because the
50602                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
50603                     // type). To determine this we compare instantiations where the type parameter is
50604                     // replaced with marker types that are known to be unrelated.
50605                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
50606                         variance = 4 /* Independent */;
50607                     }
50608                     outofbandVarianceMarkerHandler = oldHandler;
50609                     if (unmeasurable || unreliable) {
50610                         if (unmeasurable) {
50611                             variance |= 8 /* Unmeasurable */;
50612                         }
50613                         if (unreliable) {
50614                             variance |= 16 /* Unreliable */;
50615                         }
50616                     }
50617                     variances.push(variance);
50618                 };
50619                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
50620                     var tp = typeParameters_1[_i];
50621                     _loop_16(tp);
50622                 }
50623                 cache.variances = variances;
50624             }
50625             return variances;
50626         }
50627         function getVariances(type) {
50628             // Arrays and tuples are known to be covariant, no need to spend time computing this.
50629             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
50630                 return arrayVariances;
50631             }
50632             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
50633         }
50634         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
50635         // See comment at call in recursiveTypeRelatedTo for when this case matters.
50636         function hasCovariantVoidArgument(typeArguments, variances) {
50637             for (var i = 0; i < variances.length; i++) {
50638                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
50639                     return true;
50640                 }
50641             }
50642             return false;
50643         }
50644         function isUnconstrainedTypeParameter(type) {
50645             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
50646         }
50647         function isNonDeferredTypeReference(type) {
50648             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
50649         }
50650         function isTypeReferenceWithGenericArguments(type) {
50651             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
50652         }
50653         /**
50654          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
50655          *   where A.id=111 and number.id=12
50656          */
50657         function getTypeReferenceId(type, typeParameters, depth) {
50658             if (depth === void 0) { depth = 0; }
50659             var result = "" + type.target.id;
50660             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
50661                 var t = _a[_i];
50662                 if (isUnconstrainedTypeParameter(t)) {
50663                     var index = typeParameters.indexOf(t);
50664                     if (index < 0) {
50665                         index = typeParameters.length;
50666                         typeParameters.push(t);
50667                     }
50668                     result += "=" + index;
50669                 }
50670                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
50671                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
50672                 }
50673                 else {
50674                     result += "-" + t.id;
50675                 }
50676             }
50677             return result;
50678         }
50679         /**
50680          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
50681          * For other cases, the types ids are used.
50682          */
50683         function getRelationKey(source, target, intersectionState, relation) {
50684             if (relation === identityRelation && source.id > target.id) {
50685                 var temp = source;
50686                 source = target;
50687                 target = temp;
50688             }
50689             var postFix = intersectionState ? ":" + intersectionState : "";
50690             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
50691                 var typeParameters = [];
50692                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
50693             }
50694             return source.id + "," + target.id + postFix;
50695         }
50696         // Invoke the callback for each underlying property symbol of the given symbol and return the first
50697         // value that isn't undefined.
50698         function forEachProperty(prop, callback) {
50699             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
50700                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
50701                     var t = _a[_i];
50702                     var p = getPropertyOfType(t, prop.escapedName);
50703                     var result = p && forEachProperty(p, callback);
50704                     if (result) {
50705                         return result;
50706                     }
50707                 }
50708                 return undefined;
50709             }
50710             return callback(prop);
50711         }
50712         // Return the declaring class type of a property or undefined if property not declared in class
50713         function getDeclaringClass(prop) {
50714             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
50715         }
50716         // Return true if some underlying source property is declared in a class that derives
50717         // from the given base class.
50718         function isPropertyInClassDerivedFrom(prop, baseClass) {
50719             return forEachProperty(prop, function (sp) {
50720                 var sourceClass = getDeclaringClass(sp);
50721                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
50722             });
50723         }
50724         // Return true if source property is a valid override of protected parts of target property.
50725         function isValidOverrideOf(sourceProp, targetProp) {
50726             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
50727                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
50728         }
50729         // Return true if the given class derives from each of the declaring classes of the protected
50730         // constituents of the given property.
50731         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
50732             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
50733                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
50734         }
50735         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
50736         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
50737         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
50738         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
50739         // levels, but unequal at some level beyond that.
50740         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
50741         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
50742         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
50743         function isDeeplyNestedType(type, stack, depth) {
50744             // We track all object types that have an associated symbol (representing the origin of the type)
50745             if (depth >= 5 && type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
50746                 var symbol = type.symbol;
50747                 if (symbol) {
50748                     var count = 0;
50749                     for (var i = 0; i < depth; i++) {
50750                         var t = stack[i];
50751                         if (t.flags & 524288 /* Object */ && t.symbol === symbol) {
50752                             count++;
50753                             if (count >= 5)
50754                                 return true;
50755                         }
50756                     }
50757                 }
50758             }
50759             if (depth >= 5 && type.flags & 8388608 /* IndexedAccess */) {
50760                 var root = getRootObjectTypeFromIndexedAccessChain(type);
50761                 var count = 0;
50762                 for (var i = 0; i < depth; i++) {
50763                     var t = stack[i];
50764                     if (getRootObjectTypeFromIndexedAccessChain(t) === root) {
50765                         count++;
50766                         if (count >= 5)
50767                             return true;
50768                     }
50769                 }
50770             }
50771             return false;
50772         }
50773         /**
50774          * Gets the leftmost object type in a chain of indexed accesses, eg, in A[P][Q], returns A
50775          */
50776         function getRootObjectTypeFromIndexedAccessChain(type) {
50777             var t = type;
50778             while (t.flags & 8388608 /* IndexedAccess */) {
50779                 t = t.objectType;
50780             }
50781             return t;
50782         }
50783         function isPropertyIdenticalTo(sourceProp, targetProp) {
50784             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
50785         }
50786         function compareProperties(sourceProp, targetProp, compareTypes) {
50787             // Two members are considered identical when
50788             // - they are public properties with identical names, optionality, and types,
50789             // - they are private or protected properties originating in the same declaration and having identical types
50790             if (sourceProp === targetProp) {
50791                 return -1 /* True */;
50792             }
50793             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
50794             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
50795             if (sourcePropAccessibility !== targetPropAccessibility) {
50796                 return 0 /* False */;
50797             }
50798             if (sourcePropAccessibility) {
50799                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
50800                     return 0 /* False */;
50801                 }
50802             }
50803             else {
50804                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
50805                     return 0 /* False */;
50806                 }
50807             }
50808             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
50809                 return 0 /* False */;
50810             }
50811             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
50812         }
50813         function isMatchingSignature(source, target, partialMatch) {
50814             var sourceParameterCount = getParameterCount(source);
50815             var targetParameterCount = getParameterCount(target);
50816             var sourceMinArgumentCount = getMinArgumentCount(source);
50817             var targetMinArgumentCount = getMinArgumentCount(target);
50818             var sourceHasRestParameter = hasEffectiveRestParameter(source);
50819             var targetHasRestParameter = hasEffectiveRestParameter(target);
50820             // A source signature matches a target signature if the two signatures have the same number of required,
50821             // optional, and rest parameters.
50822             if (sourceParameterCount === targetParameterCount &&
50823                 sourceMinArgumentCount === targetMinArgumentCount &&
50824                 sourceHasRestParameter === targetHasRestParameter) {
50825                 return true;
50826             }
50827             // A source signature partially matches a target signature if the target signature has no fewer required
50828             // parameters
50829             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
50830                 return true;
50831             }
50832             return false;
50833         }
50834         /**
50835          * See signatureRelatedTo, compareSignaturesIdentical
50836          */
50837         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
50838             // TODO (drosen): De-duplicate code between related functions.
50839             if (source === target) {
50840                 return -1 /* True */;
50841             }
50842             if (!(isMatchingSignature(source, target, partialMatch))) {
50843                 return 0 /* False */;
50844             }
50845             // Check that the two signatures have the same number of type parameters.
50846             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
50847                 return 0 /* False */;
50848             }
50849             // Check that type parameter constraints and defaults match. If they do, instantiate the source
50850             // signature with the type parameters of the target signature and continue the comparison.
50851             if (target.typeParameters) {
50852                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
50853                 for (var i = 0; i < target.typeParameters.length; i++) {
50854                     var s = source.typeParameters[i];
50855                     var t = target.typeParameters[i];
50856                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
50857                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
50858                         return 0 /* False */;
50859                     }
50860                 }
50861                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
50862             }
50863             var result = -1 /* True */;
50864             if (!ignoreThisTypes) {
50865                 var sourceThisType = getThisTypeOfSignature(source);
50866                 if (sourceThisType) {
50867                     var targetThisType = getThisTypeOfSignature(target);
50868                     if (targetThisType) {
50869                         var related = compareTypes(sourceThisType, targetThisType);
50870                         if (!related) {
50871                             return 0 /* False */;
50872                         }
50873                         result &= related;
50874                     }
50875                 }
50876             }
50877             var targetLen = getParameterCount(target);
50878             for (var i = 0; i < targetLen; i++) {
50879                 var s = getTypeAtPosition(source, i);
50880                 var t = getTypeAtPosition(target, i);
50881                 var related = compareTypes(t, s);
50882                 if (!related) {
50883                     return 0 /* False */;
50884                 }
50885                 result &= related;
50886             }
50887             if (!ignoreReturnTypes) {
50888                 var sourceTypePredicate = getTypePredicateOfSignature(source);
50889                 var targetTypePredicate = getTypePredicateOfSignature(target);
50890                 result &= sourceTypePredicate || targetTypePredicate ?
50891                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
50892                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
50893             }
50894             return result;
50895         }
50896         function compareTypePredicatesIdentical(source, target, compareTypes) {
50897             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
50898                 source.type === target.type ? -1 /* True */ :
50899                     source.type && target.type ? compareTypes(source.type, target.type) :
50900                         0 /* False */;
50901         }
50902         function literalTypesWithSameBaseType(types) {
50903             var commonBaseType;
50904             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
50905                 var t = types_12[_i];
50906                 var baseType = getBaseTypeOfLiteralType(t);
50907                 if (!commonBaseType) {
50908                     commonBaseType = baseType;
50909                 }
50910                 if (baseType === t || baseType !== commonBaseType) {
50911                     return false;
50912                 }
50913             }
50914             return true;
50915         }
50916         // When the candidate types are all literal types with the same base type, return a union
50917         // of those literal types. Otherwise, return the leftmost type for which no type to the
50918         // right is a supertype.
50919         function getSupertypeOrUnion(types) {
50920             return literalTypesWithSameBaseType(types) ?
50921                 getUnionType(types) :
50922                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
50923         }
50924         function getCommonSupertype(types) {
50925             if (!strictNullChecks) {
50926                 return getSupertypeOrUnion(types);
50927             }
50928             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
50929             return primaryTypes.length ?
50930                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
50931                 getUnionType(types, 2 /* Subtype */);
50932         }
50933         // Return the leftmost type for which no type to the right is a subtype.
50934         function getCommonSubtype(types) {
50935             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
50936         }
50937         function isArrayType(type) {
50938             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
50939         }
50940         function isReadonlyArrayType(type) {
50941             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
50942         }
50943         function isMutableArrayOrTuple(type) {
50944             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
50945         }
50946         function getElementTypeOfArrayType(type) {
50947             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50948         }
50949         function isArrayLikeType(type) {
50950             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
50951             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
50952             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
50953         }
50954         function isEmptyArrayLiteralType(type) {
50955             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
50956             return elementType === undefinedWideningType || elementType === implicitNeverType;
50957         }
50958         function isTupleLikeType(type) {
50959             return isTupleType(type) || !!getPropertyOfType(type, "0");
50960         }
50961         function isArrayOrTupleLikeType(type) {
50962             return isArrayLikeType(type) || isTupleLikeType(type);
50963         }
50964         function getTupleElementType(type, index) {
50965             var propType = getTypeOfPropertyOfType(type, "" + index);
50966             if (propType) {
50967                 return propType;
50968             }
50969             if (everyType(type, isTupleType)) {
50970                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
50971             }
50972             return undefined;
50973         }
50974         function isNeitherUnitTypeNorNever(type) {
50975             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
50976         }
50977         function isUnitType(type) {
50978             return !!(type.flags & 109440 /* Unit */);
50979         }
50980         function isLiteralType(type) {
50981             return type.flags & 16 /* Boolean */ ? true :
50982                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
50983                     isUnitType(type);
50984         }
50985         function getBaseTypeOfLiteralType(type) {
50986             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
50987                 type.flags & 128 /* StringLiteral */ ? stringType :
50988                     type.flags & 256 /* NumberLiteral */ ? numberType :
50989                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
50990                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
50991                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
50992                                     type;
50993         }
50994         function getWidenedLiteralType(type) {
50995             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
50996                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
50997                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
50998                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
50999                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
51000                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
51001                                     type;
51002         }
51003         function getWidenedUniqueESSymbolType(type) {
51004             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
51005                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
51006                     type;
51007         }
51008         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
51009             if (!isLiteralOfContextualType(type, contextualType)) {
51010                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
51011             }
51012             return type;
51013         }
51014         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
51015             if (type && isUnitType(type)) {
51016                 var contextualType = !contextualSignatureReturnType ? undefined :
51017                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
51018                         contextualSignatureReturnType;
51019                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51020             }
51021             return type;
51022         }
51023         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
51024             if (type && isUnitType(type)) {
51025                 var contextualType = !contextualSignatureReturnType ? undefined :
51026                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
51027                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
51028             }
51029             return type;
51030         }
51031         /**
51032          * Check if a Type was written as a tuple type literal.
51033          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
51034          */
51035         function isTupleType(type) {
51036             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
51037         }
51038         function getRestTypeOfTupleType(type) {
51039             return type.target.hasRestElement ? getTypeArguments(type)[type.target.typeParameters.length - 1] : undefined;
51040         }
51041         function getRestArrayTypeOfTupleType(type) {
51042             var restType = getRestTypeOfTupleType(type);
51043             return restType && createArrayType(restType);
51044         }
51045         function getLengthOfTupleType(type) {
51046             return getTypeReferenceArity(type) - (type.target.hasRestElement ? 1 : 0);
51047         }
51048         function isZeroBigInt(_a) {
51049             var value = _a.value;
51050             return value.base10Value === "0";
51051         }
51052         function getFalsyFlagsOfTypes(types) {
51053             var result = 0;
51054             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
51055                 var t = types_13[_i];
51056                 result |= getFalsyFlags(t);
51057             }
51058             return result;
51059         }
51060         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
51061         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
51062         // no flags for all other types (including non-falsy literal types).
51063         function getFalsyFlags(type) {
51064             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
51065                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
51066                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
51067                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
51068                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
51069                                 type.flags & 117724 /* PossiblyFalsy */;
51070         }
51071         function removeDefinitelyFalsyTypes(type) {
51072             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
51073                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
51074                 type;
51075         }
51076         function extractDefinitelyFalsyTypes(type) {
51077             return mapType(type, getDefinitelyFalsyPartOfType);
51078         }
51079         function getDefinitelyFalsyPartOfType(type) {
51080             return type.flags & 4 /* String */ ? emptyStringType :
51081                 type.flags & 8 /* Number */ ? zeroType :
51082                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
51083                         type === regularFalseType ||
51084                             type === falseType ||
51085                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */) ||
51086                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
51087                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
51088                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
51089                             neverType;
51090         }
51091         /**
51092          * Add undefined or null or both to a type if they are missing.
51093          * @param type - type to add undefined and/or null to if not present
51094          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
51095          */
51096         function getNullableType(type, flags) {
51097             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
51098             return missing === 0 ? type :
51099                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
51100                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
51101                         getUnionType([type, undefinedType, nullType]);
51102         }
51103         function getOptionalType(type) {
51104             ts.Debug.assert(strictNullChecks);
51105             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
51106         }
51107         function getGlobalNonNullableTypeInstantiation(type) {
51108             if (!deferredGlobalNonNullableTypeAlias) {
51109                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
51110             }
51111             // Use NonNullable global type alias if available to improve quick info/declaration emit
51112             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
51113                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
51114             }
51115             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
51116         }
51117         function getNonNullableType(type) {
51118             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
51119         }
51120         function addOptionalTypeMarker(type) {
51121             return strictNullChecks ? getUnionType([type, optionalType]) : type;
51122         }
51123         function isNotOptionalTypeMarker(type) {
51124             return type !== optionalType;
51125         }
51126         function removeOptionalTypeMarker(type) {
51127             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
51128         }
51129         function propagateOptionalTypeMarker(type, node, wasOptional) {
51130             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
51131         }
51132         function getOptionalExpressionType(exprType, expression) {
51133             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
51134                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
51135                     exprType;
51136         }
51137         /**
51138          * Is source potentially coercible to target type under `==`.
51139          * Assumes that `source` is a constituent of a union, hence
51140          * the boolean literal flag on the LHS, but not on the RHS.
51141          *
51142          * This does not fully replicate the semantics of `==`. The
51143          * intention is to catch cases that are clearly not right.
51144          *
51145          * Comparing (string | number) to number should not remove the
51146          * string element.
51147          *
51148          * Comparing (string | number) to 1 will remove the string
51149          * element, though this is not sound. This is a pragmatic
51150          * choice.
51151          *
51152          * @see narrowTypeByEquality
51153          *
51154          * @param source
51155          * @param target
51156          */
51157         function isCoercibleUnderDoubleEquals(source, target) {
51158             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
51159                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
51160         }
51161         /**
51162          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
51163          * with no call or construct signatures.
51164          */
51165         function isObjectTypeWithInferableIndex(type) {
51166             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
51167                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
51168                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
51169         }
51170         function createSymbolWithType(source, type) {
51171             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
51172             symbol.declarations = source.declarations;
51173             symbol.parent = source.parent;
51174             symbol.type = type;
51175             symbol.target = source;
51176             if (source.valueDeclaration) {
51177                 symbol.valueDeclaration = source.valueDeclaration;
51178             }
51179             var nameType = getSymbolLinks(source).nameType;
51180             if (nameType) {
51181                 symbol.nameType = nameType;
51182             }
51183             return symbol;
51184         }
51185         function transformTypeOfMembers(type, f) {
51186             var members = ts.createSymbolTable();
51187             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51188                 var property = _a[_i];
51189                 var original = getTypeOfSymbol(property);
51190                 var updated = f(original);
51191                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
51192             }
51193             return members;
51194         }
51195         /**
51196          * If the the provided object literal is subject to the excess properties check,
51197          * create a new that is exempt. Recursively mark object literal members as exempt.
51198          * Leave signatures alone since they are not subject to the check.
51199          */
51200         function getRegularTypeOfObjectLiteral(type) {
51201             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
51202                 return type;
51203             }
51204             var regularType = type.regularType;
51205             if (regularType) {
51206                 return regularType;
51207             }
51208             var resolved = type;
51209             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
51210             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
51211             regularNew.flags = resolved.flags;
51212             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
51213             type.regularType = regularNew;
51214             return regularNew;
51215         }
51216         function createWideningContext(parent, propertyName, siblings) {
51217             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
51218         }
51219         function getSiblingsOfContext(context) {
51220             if (!context.siblings) {
51221                 var siblings_1 = [];
51222                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
51223                     var type = _a[_i];
51224                     if (isObjectLiteralType(type)) {
51225                         var prop = getPropertyOfObjectType(type, context.propertyName);
51226                         if (prop) {
51227                             forEachType(getTypeOfSymbol(prop), function (t) {
51228                                 siblings_1.push(t);
51229                             });
51230                         }
51231                     }
51232                 }
51233                 context.siblings = siblings_1;
51234             }
51235             return context.siblings;
51236         }
51237         function getPropertiesOfContext(context) {
51238             if (!context.resolvedProperties) {
51239                 var names = ts.createMap();
51240                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
51241                     var t = _a[_i];
51242                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
51243                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
51244                             var prop = _c[_b];
51245                             names.set(prop.escapedName, prop);
51246                         }
51247                     }
51248                 }
51249                 context.resolvedProperties = ts.arrayFrom(names.values());
51250             }
51251             return context.resolvedProperties;
51252         }
51253         function getWidenedProperty(prop, context) {
51254             if (!(prop.flags & 4 /* Property */)) {
51255                 // Since get accessors already widen their return value there is no need to
51256                 // widen accessor based properties here.
51257                 return prop;
51258             }
51259             var original = getTypeOfSymbol(prop);
51260             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
51261             var widened = getWidenedTypeWithContext(original, propContext);
51262             return widened === original ? prop : createSymbolWithType(prop, widened);
51263         }
51264         function getUndefinedProperty(prop) {
51265             var cached = undefinedProperties.get(prop.escapedName);
51266             if (cached) {
51267                 return cached;
51268             }
51269             var result = createSymbolWithType(prop, undefinedType);
51270             result.flags |= 16777216 /* Optional */;
51271             undefinedProperties.set(prop.escapedName, result);
51272             return result;
51273         }
51274         function getWidenedTypeOfObjectLiteral(type, context) {
51275             var members = ts.createSymbolTable();
51276             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
51277                 var prop = _a[_i];
51278                 members.set(prop.escapedName, getWidenedProperty(prop, context));
51279             }
51280             if (context) {
51281                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
51282                     var prop = _c[_b];
51283                     if (!members.has(prop.escapedName)) {
51284                         members.set(prop.escapedName, getUndefinedProperty(prop));
51285                     }
51286                 }
51287             }
51288             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
51289             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
51290             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
51291             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
51292             return result;
51293         }
51294         function getWidenedType(type) {
51295             return getWidenedTypeWithContext(type, /*context*/ undefined);
51296         }
51297         function getWidenedTypeWithContext(type, context) {
51298             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
51299                 if (context === undefined && type.widened) {
51300                     return type.widened;
51301                 }
51302                 var result = void 0;
51303                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
51304                     result = anyType;
51305                 }
51306                 else if (isObjectLiteralType(type)) {
51307                     result = getWidenedTypeOfObjectLiteral(type, context);
51308                 }
51309                 else if (type.flags & 1048576 /* Union */) {
51310                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
51311                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
51312                     // Widening an empty object literal transitions from a highly restrictive type to
51313                     // a highly inclusive one. For that reason we perform subtype reduction here if the
51314                     // union includes empty object types (e.g. reducing {} | string to just {}).
51315                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
51316                 }
51317                 else if (type.flags & 2097152 /* Intersection */) {
51318                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
51319                 }
51320                 else if (isArrayType(type) || isTupleType(type)) {
51321                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
51322                 }
51323                 if (result && context === undefined) {
51324                     type.widened = result;
51325                 }
51326                 return result || type;
51327             }
51328             return type;
51329         }
51330         /**
51331          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
51332          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
51333          * getWidenedType. But in some cases getWidenedType is called without reporting errors
51334          * (type argument inference is an example).
51335          *
51336          * The return value indicates whether an error was in fact reported. The particular circumstances
51337          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
51338          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
51339          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
51340          */
51341         function reportWideningErrorsInType(type) {
51342             var errorReported = false;
51343             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
51344                 if (type.flags & 1048576 /* Union */) {
51345                     if (ts.some(type.types, isEmptyObjectType)) {
51346                         errorReported = true;
51347                     }
51348                     else {
51349                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
51350                             var t = _a[_i];
51351                             if (reportWideningErrorsInType(t)) {
51352                                 errorReported = true;
51353                             }
51354                         }
51355                     }
51356                 }
51357                 if (isArrayType(type) || isTupleType(type)) {
51358                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
51359                         var t = _c[_b];
51360                         if (reportWideningErrorsInType(t)) {
51361                             errorReported = true;
51362                         }
51363                     }
51364                 }
51365                 if (isObjectLiteralType(type)) {
51366                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
51367                         var p = _e[_d];
51368                         var t = getTypeOfSymbol(p);
51369                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
51370                             if (!reportWideningErrorsInType(t)) {
51371                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
51372                             }
51373                             errorReported = true;
51374                         }
51375                     }
51376                 }
51377             }
51378             return errorReported;
51379         }
51380         function reportImplicitAny(declaration, type, wideningKind) {
51381             var typeAsString = typeToString(getWidenedType(type));
51382             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
51383                 // Only report implicit any errors/suggestions in TS and ts-check JS files
51384                 return;
51385             }
51386             var diagnostic;
51387             switch (declaration.kind) {
51388                 case 209 /* BinaryExpression */:
51389                 case 159 /* PropertyDeclaration */:
51390                 case 158 /* PropertySignature */:
51391                     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;
51392                     break;
51393                 case 156 /* Parameter */:
51394                     var param = declaration;
51395                     if (ts.isIdentifier(param.name) &&
51396                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
51397                         param.parent.parameters.indexOf(param) > -1 &&
51398                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
51399                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
51400                         var newName = "arg" + param.parent.parameters.indexOf(param);
51401                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
51402                         return;
51403                     }
51404                     diagnostic = declaration.dotDotDotToken ?
51405                         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 :
51406                         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;
51407                     break;
51408                 case 191 /* BindingElement */:
51409                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
51410                     if (!noImplicitAny) {
51411                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
51412                         return;
51413                     }
51414                     break;
51415                 case 300 /* JSDocFunctionType */:
51416                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51417                     return;
51418                 case 244 /* FunctionDeclaration */:
51419                 case 161 /* MethodDeclaration */:
51420                 case 160 /* MethodSignature */:
51421                 case 163 /* GetAccessor */:
51422                 case 164 /* SetAccessor */:
51423                 case 201 /* FunctionExpression */:
51424                 case 202 /* ArrowFunction */:
51425                     if (noImplicitAny && !declaration.name) {
51426                         if (wideningKind === 3 /* GeneratorYield */) {
51427                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
51428                         }
51429                         else {
51430                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
51431                         }
51432                         return;
51433                     }
51434                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
51435                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
51436                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
51437                     break;
51438                 case 186 /* MappedType */:
51439                     if (noImplicitAny) {
51440                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
51441                     }
51442                     return;
51443                 default:
51444                     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;
51445             }
51446             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
51447         }
51448         function reportErrorsFromWidening(declaration, type, wideningKind) {
51449             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
51450                 // Report implicit any error within type if possible, otherwise report error on declaration
51451                 if (!reportWideningErrorsInType(type)) {
51452                     reportImplicitAny(declaration, type, wideningKind);
51453                 }
51454             }
51455         }
51456         function applyToParameterTypes(source, target, callback) {
51457             var sourceCount = getParameterCount(source);
51458             var targetCount = getParameterCount(target);
51459             var sourceRestType = getEffectiveRestType(source);
51460             var targetRestType = getEffectiveRestType(target);
51461             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
51462             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
51463             var sourceThisType = getThisTypeOfSignature(source);
51464             if (sourceThisType) {
51465                 var targetThisType = getThisTypeOfSignature(target);
51466                 if (targetThisType) {
51467                     callback(sourceThisType, targetThisType);
51468                 }
51469             }
51470             for (var i = 0; i < paramCount; i++) {
51471                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
51472             }
51473             if (targetRestType) {
51474                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
51475             }
51476         }
51477         function applyToReturnTypes(source, target, callback) {
51478             var sourceTypePredicate = getTypePredicateOfSignature(source);
51479             var targetTypePredicate = getTypePredicateOfSignature(target);
51480             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
51481                 callback(sourceTypePredicate.type, targetTypePredicate.type);
51482             }
51483             else {
51484                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
51485             }
51486         }
51487         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
51488             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
51489         }
51490         function cloneInferenceContext(context, extraFlags) {
51491             if (extraFlags === void 0) { extraFlags = 0; }
51492             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
51493         }
51494         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
51495             var context = {
51496                 inferences: inferences,
51497                 signature: signature,
51498                 flags: flags,
51499                 compareTypes: compareTypes,
51500                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
51501                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
51502             };
51503             return context;
51504         }
51505         function mapToInferredType(context, t, fix) {
51506             var inferences = context.inferences;
51507             for (var i = 0; i < inferences.length; i++) {
51508                 var inference = inferences[i];
51509                 if (t === inference.typeParameter) {
51510                     if (fix && !inference.isFixed) {
51511                         clearCachedInferences(inferences);
51512                         inference.isFixed = true;
51513                     }
51514                     return getInferredType(context, i);
51515                 }
51516             }
51517             return t;
51518         }
51519         function clearCachedInferences(inferences) {
51520             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
51521                 var inference = inferences_1[_i];
51522                 if (!inference.isFixed) {
51523                     inference.inferredType = undefined;
51524                 }
51525             }
51526         }
51527         function createInferenceInfo(typeParameter) {
51528             return {
51529                 typeParameter: typeParameter,
51530                 candidates: undefined,
51531                 contraCandidates: undefined,
51532                 inferredType: undefined,
51533                 priority: undefined,
51534                 topLevel: true,
51535                 isFixed: false
51536             };
51537         }
51538         function cloneInferenceInfo(inference) {
51539             return {
51540                 typeParameter: inference.typeParameter,
51541                 candidates: inference.candidates && inference.candidates.slice(),
51542                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
51543                 inferredType: inference.inferredType,
51544                 priority: inference.priority,
51545                 topLevel: inference.topLevel,
51546                 isFixed: inference.isFixed
51547             };
51548         }
51549         function cloneInferredPartOfContext(context) {
51550             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
51551             return inferences.length ?
51552                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
51553                 undefined;
51554         }
51555         function getMapperFromContext(context) {
51556             return context && context.mapper;
51557         }
51558         // Return true if the given type could possibly reference a type parameter for which
51559         // we perform type inference (i.e. a type parameter of a generic function). We cache
51560         // results for union and intersection types for performance reasons.
51561         function couldContainTypeVariables(type) {
51562             var objectFlags = ts.getObjectFlags(type);
51563             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
51564                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
51565             }
51566             var result = !!(type.flags & 63176704 /* Instantiable */ ||
51567                 objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
51568                 objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
51569                 objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */) ||
51570                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && ts.some(type.types, couldContainTypeVariables));
51571             if (type.flags & 3899393 /* ObjectFlagsType */) {
51572                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
51573             }
51574             return result;
51575         }
51576         function isTypeParameterAtTopLevel(type, typeParameter) {
51577             return !!(type === typeParameter ||
51578                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
51579                 type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), typeParameter) ||
51580                     isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), typeParameter)));
51581         }
51582         /** Create an object with properties named in the string literal type. Every property has type `any` */
51583         function createEmptyObjectTypeFromStringLiteral(type) {
51584             var members = ts.createSymbolTable();
51585             forEachType(type, function (t) {
51586                 if (!(t.flags & 128 /* StringLiteral */)) {
51587                     return;
51588                 }
51589                 var name = ts.escapeLeadingUnderscores(t.value);
51590                 var literalProp = createSymbol(4 /* Property */, name);
51591                 literalProp.type = anyType;
51592                 if (t.symbol) {
51593                     literalProp.declarations = t.symbol.declarations;
51594                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
51595                 }
51596                 members.set(name, literalProp);
51597             });
51598             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
51599             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
51600         }
51601         /**
51602          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
51603          * an object type with the same set of properties as the source type, where the type of each
51604          * property is computed by inferring from the source property type to X for the type
51605          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
51606          */
51607         function inferTypeForHomomorphicMappedType(source, target, constraint) {
51608             var key = source.id + "," + target.id + "," + constraint.id;
51609             if (reverseMappedCache.has(key)) {
51610                 return reverseMappedCache.get(key);
51611             }
51612             reverseMappedCache.set(key, undefined);
51613             var type = createReverseMappedType(source, target, constraint);
51614             reverseMappedCache.set(key, type);
51615             return type;
51616         }
51617         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
51618         // an object literal type with at least one property of an inferable type. For example, an object
51619         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
51620         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
51621         function isPartiallyInferableType(type) {
51622             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
51623                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); });
51624         }
51625         function createReverseMappedType(source, target, constraint) {
51626             // We consider a source type reverse mappable if it has a string index signature or if
51627             // it has one or more properties and is of a partially inferable type.
51628             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
51629                 return undefined;
51630             }
51631             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
51632             // applied to the element type(s).
51633             if (isArrayType(source)) {
51634                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
51635             }
51636             if (isTupleType(source)) {
51637                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
51638                 var minLength = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
51639                     getTypeReferenceArity(source) - (source.target.hasRestElement ? 1 : 0) : source.target.minLength;
51640                 return createTupleType(elementTypes, minLength, source.target.hasRestElement, source.target.readonly, source.target.associatedNames);
51641             }
51642             // For all other object types we infer a new object type where the reverse mapping has been
51643             // applied to the type of each property.
51644             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
51645             reversed.source = source;
51646             reversed.mappedType = target;
51647             reversed.constraintType = constraint;
51648             return reversed;
51649         }
51650         function getTypeOfReverseMappedSymbol(symbol) {
51651             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
51652         }
51653         function inferReverseMappedType(sourceType, target, constraint) {
51654             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
51655             var templateType = getTemplateTypeFromMappedType(target);
51656             var inference = createInferenceInfo(typeParameter);
51657             inferTypes([inference], sourceType, templateType);
51658             return getTypeFromInference(inference) || unknownType;
51659         }
51660         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51661             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
51662             return __generator(this, function (_a) {
51663                 switch (_a.label) {
51664                     case 0:
51665                         properties = getPropertiesOfType(target);
51666                         _i = 0, properties_2 = properties;
51667                         _a.label = 1;
51668                     case 1:
51669                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
51670                         targetProp = properties_2[_i];
51671                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
51672                         if (isStaticPrivateIdentifierProperty(targetProp)) {
51673                             return [3 /*break*/, 5];
51674                         }
51675                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
51676                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
51677                         if (!!sourceProp) return [3 /*break*/, 3];
51678                         return [4 /*yield*/, targetProp];
51679                     case 2:
51680                         _a.sent();
51681                         return [3 /*break*/, 5];
51682                     case 3:
51683                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
51684                         targetType = getTypeOfSymbol(targetProp);
51685                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
51686                         sourceType = getTypeOfSymbol(sourceProp);
51687                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
51688                         return [4 /*yield*/, targetProp];
51689                     case 4:
51690                         _a.sent();
51691                         _a.label = 5;
51692                     case 5:
51693                         _i++;
51694                         return [3 /*break*/, 1];
51695                     case 6: return [2 /*return*/];
51696                 }
51697             });
51698         }
51699         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
51700             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
51701             if (!result.done)
51702                 return result.value;
51703         }
51704         function tupleTypesDefinitelyUnrelated(source, target) {
51705             return target.target.minLength > source.target.minLength ||
51706                 !getRestTypeOfTupleType(target) && (!!getRestTypeOfTupleType(source) || getLengthOfTupleType(target) < getLengthOfTupleType(source));
51707         }
51708         function typesDefinitelyUnrelated(source, target) {
51709             // Two tuple types with incompatible arities are definitely unrelated.
51710             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
51711             return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) ||
51712                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
51713                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
51714         }
51715         function getTypeFromInference(inference) {
51716             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
51717                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
51718                     undefined;
51719         }
51720         function hasSkipDirectInferenceFlag(node) {
51721             return !!getNodeLinks(node).skipDirectInference;
51722         }
51723         function isFromInferenceBlockedSource(type) {
51724             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
51725         }
51726         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
51727             if (priority === void 0) { priority = 0; }
51728             if (contravariant === void 0) { contravariant = false; }
51729             var symbolOrTypeStack;
51730             var visited;
51731             var bivariant = false;
51732             var propagationType;
51733             var inferencePriority = 512 /* MaxValue */;
51734             var allowComplexConstraintInference = true;
51735             inferFromTypes(originalSource, originalTarget);
51736             function inferFromTypes(source, target) {
51737                 if (!couldContainTypeVariables(target)) {
51738                     return;
51739                 }
51740                 if (source === wildcardType) {
51741                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
51742                     // referenced in the target type, so we record it as the propagation type and infer from the
51743                     // target to itself. Then, as we find candidates we substitute the propagation type.
51744                     var savePropagationType = propagationType;
51745                     propagationType = source;
51746                     inferFromTypes(target, target);
51747                     propagationType = savePropagationType;
51748                     return;
51749                 }
51750                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
51751                     // Source and target are types originating in the same generic type alias declaration.
51752                     // Simply infer from source type arguments to target type arguments.
51753                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
51754                     return;
51755                 }
51756                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
51757                     // When source and target are the same union or intersection type, just relate each constituent
51758                     // type to itself.
51759                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
51760                         var t = _a[_i];
51761                         inferFromTypes(t, t);
51762                     }
51763                     return;
51764                 }
51765                 if (target.flags & 1048576 /* Union */) {
51766                     // First, infer between identically matching source and target constituents and remove the
51767                     // matching types.
51768                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
51769                     // Next, infer between closely matching source and target constituents and remove
51770                     // the matching types. Types closely match when they are instantiations of the same
51771                     // object type or instantiations of the same type alias.
51772                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
51773                     if (targets.length === 0) {
51774                         return;
51775                     }
51776                     target = getUnionType(targets);
51777                     if (sources.length === 0) {
51778                         // All source constituents have been matched and there is nothing further to infer from.
51779                         // However, simply making no inferences is undesirable because it could ultimately mean
51780                         // inferring a type parameter constraint. Instead, make a lower priority inference from
51781                         // the full source to whatever remains in the target. For example, when inferring from
51782                         // string to 'string | T', make a lower priority inference of string for T.
51783                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
51784                         return;
51785                     }
51786                     source = getUnionType(sources);
51787                 }
51788                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
51789                     // We reduce intersection types only when they contain naked type parameters. For example, when
51790                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
51791                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
51792                     // string[] on the source side and infer string for T.
51793                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
51794                     // in such scenarios.
51795                     if (!(source.flags & 1048576 /* Union */)) {
51796                         // Infer between identically matching source and target constituents and remove the matching types.
51797                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
51798                         if (sources.length === 0 || targets.length === 0) {
51799                             return;
51800                         }
51801                         source = getIntersectionType(sources);
51802                         target = getIntersectionType(targets);
51803                     }
51804                 }
51805                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
51806                     target = getActualTypeVariable(target);
51807                 }
51808                 if (target.flags & 8650752 /* TypeVariable */) {
51809                     // If target is a type parameter, make an inference, unless the source type contains
51810                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
51811                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
51812                     // it as an inference candidate. Hopefully, a better candidate will come along that does
51813                     // not contain anyFunctionType when we come back to this argument for its second round
51814                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
51815                     // when constructing types from type parameters that had no inference candidates).
51816                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
51817                         (priority & 32 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
51818                         return;
51819                     }
51820                     var inference = getInferenceInfoForType(target);
51821                     if (inference) {
51822                         if (!inference.isFixed) {
51823                             if (inference.priority === undefined || priority < inference.priority) {
51824                                 inference.candidates = undefined;
51825                                 inference.contraCandidates = undefined;
51826                                 inference.topLevel = true;
51827                                 inference.priority = priority;
51828                             }
51829                             if (priority === inference.priority) {
51830                                 var candidate = propagationType || source;
51831                                 // We make contravariant inferences only if we are in a pure contravariant position,
51832                                 // i.e. only if we have not descended into a bivariant position.
51833                                 if (contravariant && !bivariant) {
51834                                     if (!ts.contains(inference.contraCandidates, candidate)) {
51835                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
51836                                         clearCachedInferences(inferences);
51837                                     }
51838                                 }
51839                                 else if (!ts.contains(inference.candidates, candidate)) {
51840                                     inference.candidates = ts.append(inference.candidates, candidate);
51841                                     clearCachedInferences(inferences);
51842                                 }
51843                             }
51844                             if (!(priority & 32 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
51845                                 inference.topLevel = false;
51846                                 clearCachedInferences(inferences);
51847                             }
51848                         }
51849                         inferencePriority = Math.min(inferencePriority, priority);
51850                         return;
51851                     }
51852                     else {
51853                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
51854                         var simplified = getSimplifiedType(target, /*writing*/ false);
51855                         if (simplified !== target) {
51856                             invokeOnce(source, simplified, inferFromTypes);
51857                         }
51858                         else if (target.flags & 8388608 /* IndexedAccess */) {
51859                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
51860                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
51861                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
51862                             if (indexType.flags & 63176704 /* Instantiable */) {
51863                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
51864                                 if (simplified_1 && simplified_1 !== target) {
51865                                     invokeOnce(source, simplified_1, inferFromTypes);
51866                                 }
51867                             }
51868                         }
51869                     }
51870                 }
51871                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
51872                     !(source.node && target.node)) {
51873                     // If source and target are references to the same generic type, infer from type arguments
51874                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
51875                 }
51876                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
51877                     contravariant = !contravariant;
51878                     inferFromTypes(source.type, target.type);
51879                     contravariant = !contravariant;
51880                 }
51881                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
51882                     var empty = createEmptyObjectTypeFromStringLiteral(source);
51883                     contravariant = !contravariant;
51884                     inferWithPriority(empty, target.type, 64 /* LiteralKeyof */);
51885                     contravariant = !contravariant;
51886                 }
51887                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
51888                     inferFromTypes(source.objectType, target.objectType);
51889                     inferFromTypes(source.indexType, target.indexType);
51890                 }
51891                 else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) {
51892                     inferFromTypes(source.checkType, target.checkType);
51893                     inferFromTypes(source.extendsType, target.extendsType);
51894                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
51895                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
51896                 }
51897                 else if (target.flags & 16777216 /* Conditional */) {
51898                     var savePriority = priority;
51899                     priority |= contravariant ? 16 /* ContravariantConditional */ : 0;
51900                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
51901                     inferToMultipleTypes(source, targetTypes, target.flags);
51902                     priority = savePriority;
51903                 }
51904                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
51905                     inferToMultipleTypes(source, target.types, target.flags);
51906                 }
51907                 else if (source.flags & 1048576 /* Union */) {
51908                     // Source is a union or intersection type, infer from each constituent type
51909                     var sourceTypes = source.types;
51910                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
51911                         var sourceType = sourceTypes_2[_e];
51912                         inferFromTypes(sourceType, target);
51913                     }
51914                 }
51915                 else {
51916                     source = getReducedType(source);
51917                     if (!(priority & 128 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 63176704 /* Instantiable */))) {
51918                         var apparentSource = getApparentType(source);
51919                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
51920                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
51921                         // with the simplified source.
51922                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
51923                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
51924                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
51925                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
51926                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
51927                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
51928                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
51929                             // remove this `allowComplexConstraintInference` flag.
51930                             allowComplexConstraintInference = false;
51931                             return inferFromTypes(apparentSource, target);
51932                         }
51933                         source = apparentSource;
51934                     }
51935                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51936                         invokeOnce(source, target, inferFromObjectTypes);
51937                     }
51938                 }
51939                 if (source.flags & 25165824 /* Simplifiable */) {
51940                     var simplified = getSimplifiedType(source, contravariant);
51941                     if (simplified !== source) {
51942                         inferFromTypes(simplified, target);
51943                     }
51944                 }
51945             }
51946             function inferWithPriority(source, target, newPriority) {
51947                 var savePriority = priority;
51948                 priority |= newPriority;
51949                 inferFromTypes(source, target);
51950                 priority = savePriority;
51951             }
51952             function invokeOnce(source, target, action) {
51953                 var key = source.id + "," + target.id;
51954                 var status = visited && visited.get(key);
51955                 if (status !== undefined) {
51956                     inferencePriority = Math.min(inferencePriority, status);
51957                     return;
51958                 }
51959                 (visited || (visited = ts.createMap())).set(key, -1 /* Circularity */);
51960                 var saveInferencePriority = inferencePriority;
51961                 inferencePriority = 512 /* MaxValue */;
51962                 action(source, target);
51963                 visited.set(key, inferencePriority);
51964                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
51965             }
51966             function inferFromMatchingTypes(sources, targets, matches) {
51967                 var matchedSources;
51968                 var matchedTargets;
51969                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
51970                     var t = targets_1[_i];
51971                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
51972                         var s = sources_1[_a];
51973                         if (matches(s, t)) {
51974                             inferFromTypes(s, t);
51975                             matchedSources = ts.appendIfUnique(matchedSources, s);
51976                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
51977                         }
51978                     }
51979                 }
51980                 return [
51981                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
51982                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
51983                 ];
51984             }
51985             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
51986                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
51987                 for (var i = 0; i < count; i++) {
51988                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
51989                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
51990                     }
51991                     else {
51992                         inferFromTypes(sourceTypes[i], targetTypes[i]);
51993                     }
51994                 }
51995             }
51996             function inferFromContravariantTypes(source, target) {
51997                 if (strictFunctionTypes || priority & 256 /* AlwaysStrict */) {
51998                     contravariant = !contravariant;
51999                     inferFromTypes(source, target);
52000                     contravariant = !contravariant;
52001                 }
52002                 else {
52003                     inferFromTypes(source, target);
52004                 }
52005             }
52006             function getInferenceInfoForType(type) {
52007                 if (type.flags & 8650752 /* TypeVariable */) {
52008                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
52009                         var inference = inferences_2[_i];
52010                         if (type === inference.typeParameter) {
52011                             return inference;
52012                         }
52013                     }
52014                 }
52015                 return undefined;
52016             }
52017             function getSingleTypeVariableFromIntersectionTypes(types) {
52018                 var typeVariable;
52019                 for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
52020                     var type = types_14[_i];
52021                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
52022                     if (!t || typeVariable && t !== typeVariable) {
52023                         return undefined;
52024                     }
52025                     typeVariable = t;
52026                 }
52027                 return typeVariable;
52028             }
52029             function inferToMultipleTypes(source, targets, targetFlags) {
52030                 var typeVariableCount = 0;
52031                 if (targetFlags & 1048576 /* Union */) {
52032                     var nakedTypeVariable = void 0;
52033                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
52034                     var matched_1 = new Array(sources.length);
52035                     var inferenceCircularity = false;
52036                     // First infer to types that are not naked type variables. For each source type we
52037                     // track whether inferences were made from that particular type to some target with
52038                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
52039                     // parameter.
52040                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
52041                         var t = targets_2[_i];
52042                         if (getInferenceInfoForType(t)) {
52043                             nakedTypeVariable = t;
52044                             typeVariableCount++;
52045                         }
52046                         else {
52047                             for (var i = 0; i < sources.length; i++) {
52048                                 var saveInferencePriority = inferencePriority;
52049                                 inferencePriority = 512 /* MaxValue */;
52050                                 inferFromTypes(sources[i], t);
52051                                 if (inferencePriority === priority)
52052                                     matched_1[i] = true;
52053                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
52054                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
52055                             }
52056                         }
52057                     }
52058                     if (typeVariableCount === 0) {
52059                         // If every target is an intersection of types containing a single naked type variable,
52060                         // make a lower priority inference to that type variable. This handles inferring from
52061                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
52062                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
52063                         if (intersectionTypeVariable) {
52064                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
52065                         }
52066                         return;
52067                     }
52068                     // If the target has a single naked type variable and no inference circularities were
52069                     // encountered above (meaning we explored the types fully), create a union of the source
52070                     // types from which no inferences have been made so far and infer from that union to the
52071                     // naked type variable.
52072                     if (typeVariableCount === 1 && !inferenceCircularity) {
52073                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
52074                         if (unmatched.length) {
52075                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
52076                             return;
52077                         }
52078                     }
52079                 }
52080                 else {
52081                     // We infer from types that are not naked type variables first so that inferences we
52082                     // make from nested naked type variables and given slightly higher priority by virtue
52083                     // of being first in the candidates array.
52084                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
52085                         var t = targets_3[_a];
52086                         if (getInferenceInfoForType(t)) {
52087                             typeVariableCount++;
52088                         }
52089                         else {
52090                             inferFromTypes(source, t);
52091                         }
52092                     }
52093                 }
52094                 // Inferences directly to naked type variables are given lower priority as they are
52095                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
52096                 // we want to infer string for T, not Promise<string> | string. For intersection types
52097                 // we only infer to single naked type variables.
52098                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
52099                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
52100                         var t = targets_4[_b];
52101                         if (getInferenceInfoForType(t)) {
52102                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
52103                         }
52104                     }
52105                 }
52106             }
52107             function inferToMappedType(source, target, constraintType) {
52108                 if (constraintType.flags & 1048576 /* Union */) {
52109                     var result = false;
52110                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
52111                         var type = _a[_i];
52112                         result = inferToMappedType(source, target, type) || result;
52113                     }
52114                     return result;
52115                 }
52116                 if (constraintType.flags & 4194304 /* Index */) {
52117                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
52118                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
52119                     // type and then make a secondary inference from that type to T. We make a secondary inference
52120                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
52121                     var inference = getInferenceInfoForType(constraintType.type);
52122                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
52123                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
52124                         if (inferredType) {
52125                             // We assign a lower priority to inferences made from types containing non-inferrable
52126                             // types because we may only have a partial result (i.e. we may have failed to make
52127                             // reverse inferences for some properties).
52128                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
52129                                 4 /* PartialHomomorphicMappedType */ :
52130                                 2 /* HomomorphicMappedType */);
52131                         }
52132                     }
52133                     return true;
52134                 }
52135                 if (constraintType.flags & 262144 /* TypeParameter */) {
52136                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
52137                     // parameter. First infer from 'keyof S' to K.
52138                     inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */);
52139                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
52140                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
52141                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
52142                     // Pick<T, K>.
52143                     var extendedConstraint = getConstraintOfType(constraintType);
52144                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
52145                         return true;
52146                     }
52147                     // If no inferences can be made to K's constraint, infer from a union of the property types
52148                     // in the source to the template type X.
52149                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
52150                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
52151                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
52152                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
52153                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
52154                     return true;
52155                 }
52156                 return false;
52157             }
52158             function inferFromObjectTypes(source, target) {
52159                 // If we are already processing another target type with the same associated symbol (such as
52160                 // an instantiation of the same generic type), we do not explore this target as it would yield
52161                 // no further inferences. We exclude the static side of classes from this check since it shares
52162                 // its symbol with the instance side which would lead to false positives.
52163                 var isNonConstructorObject = target.flags & 524288 /* Object */ &&
52164                     !(ts.getObjectFlags(target) & 16 /* Anonymous */ && target.symbol && target.symbol.flags & 32 /* Class */);
52165                 var symbolOrType = isNonConstructorObject ? isTupleType(target) ? target.target : target.symbol : undefined;
52166                 if (symbolOrType) {
52167                     if (ts.contains(symbolOrTypeStack, symbolOrType)) {
52168                         inferencePriority = -1 /* Circularity */;
52169                         return;
52170                     }
52171                     (symbolOrTypeStack || (symbolOrTypeStack = [])).push(symbolOrType);
52172                     inferFromObjectTypesWorker(source, target);
52173                     symbolOrTypeStack.pop();
52174                 }
52175                 else {
52176                     inferFromObjectTypesWorker(source, target);
52177                 }
52178             }
52179             function inferFromObjectTypesWorker(source, target) {
52180                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
52181                     // If source and target are references to the same generic type, infer from type arguments
52182                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
52183                     return;
52184                 }
52185                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
52186                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
52187                     // from S to T and from X to Y.
52188                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
52189                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
52190                 }
52191                 if (ts.getObjectFlags(target) & 32 /* Mapped */) {
52192                     var constraintType = getConstraintTypeFromMappedType(target);
52193                     if (inferToMappedType(source, target, constraintType)) {
52194                         return;
52195                     }
52196                 }
52197                 // Infer from the members of source and target only if the two types are possibly related
52198                 if (!typesDefinitelyUnrelated(source, target)) {
52199                     if (isArrayType(source) || isTupleType(source)) {
52200                         if (isTupleType(target)) {
52201                             var sourceLength = isTupleType(source) ? getLengthOfTupleType(source) : 0;
52202                             var targetLength = getLengthOfTupleType(target);
52203                             var sourceRestType = isTupleType(source) ? getRestTypeOfTupleType(source) : getElementTypeOfArrayType(source);
52204                             var targetRestType = getRestTypeOfTupleType(target);
52205                             var fixedLength = targetLength < sourceLength || sourceRestType ? targetLength : sourceLength;
52206                             for (var i = 0; i < fixedLength; i++) {
52207                                 inferFromTypes(i < sourceLength ? getTypeArguments(source)[i] : sourceRestType, getTypeArguments(target)[i]);
52208                             }
52209                             if (targetRestType) {
52210                                 var types = fixedLength < sourceLength ? getTypeArguments(source).slice(fixedLength, sourceLength) : [];
52211                                 if (sourceRestType) {
52212                                     types.push(sourceRestType);
52213                                 }
52214                                 if (types.length) {
52215                                     inferFromTypes(getUnionType(types), targetRestType);
52216                                 }
52217                             }
52218                             return;
52219                         }
52220                         if (isArrayType(target)) {
52221                             inferFromIndexTypes(source, target);
52222                             return;
52223                         }
52224                     }
52225                     inferFromProperties(source, target);
52226                     inferFromSignatures(source, target, 0 /* Call */);
52227                     inferFromSignatures(source, target, 1 /* Construct */);
52228                     inferFromIndexTypes(source, target);
52229                 }
52230             }
52231             function inferFromProperties(source, target) {
52232                 var properties = getPropertiesOfObjectType(target);
52233                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
52234                     var targetProp = properties_3[_i];
52235                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
52236                     if (sourceProp) {
52237                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
52238                     }
52239                 }
52240             }
52241             function inferFromSignatures(source, target, kind) {
52242                 var sourceSignatures = getSignaturesOfType(source, kind);
52243                 var targetSignatures = getSignaturesOfType(target, kind);
52244                 var sourceLen = sourceSignatures.length;
52245                 var targetLen = targetSignatures.length;
52246                 var len = sourceLen < targetLen ? sourceLen : targetLen;
52247                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
52248                 for (var i = 0; i < len; i++) {
52249                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
52250                 }
52251             }
52252             function inferFromSignature(source, target, skipParameters) {
52253                 if (!skipParameters) {
52254                     var saveBivariant = bivariant;
52255                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
52256                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
52257                     bivariant = bivariant || kind === 161 /* MethodDeclaration */ || kind === 160 /* MethodSignature */ || kind === 162 /* Constructor */;
52258                     applyToParameterTypes(source, target, inferFromContravariantTypes);
52259                     bivariant = saveBivariant;
52260                 }
52261                 applyToReturnTypes(source, target, inferFromTypes);
52262             }
52263             function inferFromIndexTypes(source, target) {
52264                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
52265                 if (targetStringIndexType) {
52266                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
52267                         getImplicitIndexTypeOfType(source, 0 /* String */);
52268                     if (sourceIndexType) {
52269                         inferFromTypes(sourceIndexType, targetStringIndexType);
52270                     }
52271                 }
52272                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
52273                 if (targetNumberIndexType) {
52274                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
52275                         getIndexTypeOfType(source, 0 /* String */) ||
52276                         getImplicitIndexTypeOfType(source, 1 /* Number */);
52277                     if (sourceIndexType) {
52278                         inferFromTypes(sourceIndexType, targetNumberIndexType);
52279                     }
52280                 }
52281             }
52282         }
52283         function isTypeOrBaseIdenticalTo(s, t) {
52284             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
52285         }
52286         function isTypeCloselyMatchedBy(s, t) {
52287             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
52288                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
52289         }
52290         function hasPrimitiveConstraint(type) {
52291             var constraint = getConstraintOfTypeParameter(type);
52292             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */);
52293         }
52294         function isObjectLiteralType(type) {
52295             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
52296         }
52297         function isObjectOrArrayLiteralType(type) {
52298             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
52299         }
52300         function unionObjectAndArrayLiteralCandidates(candidates) {
52301             if (candidates.length > 1) {
52302                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
52303                 if (objectLiterals.length) {
52304                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
52305                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
52306                 }
52307             }
52308             return candidates;
52309         }
52310         function getContravariantInference(inference) {
52311             return inference.priority & 104 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
52312         }
52313         function getCovariantInference(inference, signature) {
52314             // Extract all object and array literal types and replace them with a single widened and normalized type.
52315             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
52316             // We widen inferred literal types if
52317             // all inferences were made to top-level occurrences of the type parameter, and
52318             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
52319             // the type parameter was fixed during inference or does not occur at top-level in the return type.
52320             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
52321             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
52322                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
52323             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
52324                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
52325                     candidates;
52326             // If all inferences were made from a position that implies a combined result, infer a union type.
52327             // Otherwise, infer a common supertype.
52328             var unwidenedType = inference.priority & 104 /* PriorityImpliesCombination */ ?
52329                 getUnionType(baseCandidates, 2 /* Subtype */) :
52330                 getCommonSupertype(baseCandidates);
52331             return getWidenedType(unwidenedType);
52332         }
52333         function getInferredType(context, index) {
52334             var inference = context.inferences[index];
52335             if (!inference.inferredType) {
52336                 var inferredType = void 0;
52337                 var signature = context.signature;
52338                 if (signature) {
52339                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
52340                     if (inference.contraCandidates) {
52341                         var inferredContravariantType = getContravariantInference(inference);
52342                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
52343                         // unless the co-variant inference is a subtype and not 'never'.
52344                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
52345                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
52346                             inferredCovariantType : inferredContravariantType;
52347                     }
52348                     else if (inferredCovariantType) {
52349                         inferredType = inferredCovariantType;
52350                     }
52351                     else if (context.flags & 1 /* NoDefault */) {
52352                         // We use silentNeverType as the wildcard that signals no inferences.
52353                         inferredType = silentNeverType;
52354                     }
52355                     else {
52356                         // Infer either the default or the empty object type when no inferences were
52357                         // made. It is important to remember that in this case, inference still
52358                         // succeeds, meaning there is no error for not having inference candidates. An
52359                         // inference error only occurs when there are *conflicting* candidates, i.e.
52360                         // candidates with no common supertype.
52361                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
52362                         if (defaultType) {
52363                             // Instantiate the default type. Any forward reference to a type
52364                             // parameter should be instantiated to the empty object type.
52365                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
52366                         }
52367                     }
52368                 }
52369                 else {
52370                     inferredType = getTypeFromInference(inference);
52371                 }
52372                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
52373                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
52374                 if (constraint) {
52375                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
52376                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
52377                         inference.inferredType = inferredType = instantiatedConstraint;
52378                     }
52379                 }
52380             }
52381             return inference.inferredType;
52382         }
52383         function getDefaultTypeArgumentType(isInJavaScriptFile) {
52384             return isInJavaScriptFile ? anyType : unknownType;
52385         }
52386         function getInferredTypes(context) {
52387             var result = [];
52388             for (var i = 0; i < context.inferences.length; i++) {
52389                 result.push(getInferredType(context, i));
52390             }
52391             return result;
52392         }
52393         // EXPRESSION TYPE CHECKING
52394         function getCannotFindNameDiagnosticForName(node) {
52395             switch (node.escapedText) {
52396                 case "document":
52397                 case "console":
52398                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
52399                 case "$":
52400                     return compilerOptions.types
52401                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
52402                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery;
52403                 case "describe":
52404                 case "suite":
52405                 case "it":
52406                 case "test":
52407                     return compilerOptions.types
52408                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
52409                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha;
52410                 case "process":
52411                 case "require":
52412                 case "Buffer":
52413                 case "module":
52414                     return compilerOptions.types
52415                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
52416                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode;
52417                 case "Map":
52418                 case "Set":
52419                 case "Promise":
52420                 case "Symbol":
52421                 case "WeakMap":
52422                 case "WeakSet":
52423                 case "Iterator":
52424                 case "AsyncIterator":
52425                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later;
52426                 default:
52427                     if (node.parent.kind === 282 /* ShorthandPropertyAssignment */) {
52428                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
52429                     }
52430                     else {
52431                         return ts.Diagnostics.Cannot_find_name_0;
52432                     }
52433             }
52434         }
52435         function getResolvedSymbol(node) {
52436             var links = getNodeLinks(node);
52437             if (!links.resolvedSymbol) {
52438                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
52439                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
52440                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
52441             }
52442             return links.resolvedSymbol;
52443         }
52444         function isInTypeQuery(node) {
52445             // TypeScript 1.0 spec (April 2014): 3.6.3
52446             // A type query consists of the keyword typeof followed by an expression.
52447             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
52448             return !!ts.findAncestor(node, function (n) { return n.kind === 172 /* TypeQuery */ ? true : n.kind === 75 /* Identifier */ || n.kind === 153 /* QualifiedName */ ? false : "quit"; });
52449         }
52450         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
52451         // separated by dots). The key consists of the id of the symbol referenced by the
52452         // leftmost identifier followed by zero or more property names separated by dots.
52453         // The result is undefined if the reference isn't a dotted name. We prefix nodes
52454         // occurring in an apparent type position with '@' because the control flow type
52455         // of such nodes may be based on the apparent type instead of the declared type.
52456         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
52457             switch (node.kind) {
52458                 case 75 /* Identifier */:
52459                     var symbol = getResolvedSymbol(node);
52460                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
52461                 case 104 /* ThisKeyword */:
52462                     return "0";
52463                 case 218 /* NonNullExpression */:
52464                 case 200 /* ParenthesizedExpression */:
52465                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52466                 case 194 /* PropertyAccessExpression */:
52467                 case 195 /* ElementAccessExpression */:
52468                     var propName = getAccessedPropertyName(node);
52469                     if (propName !== undefined) {
52470                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
52471                         return key && key + "." + propName;
52472                     }
52473             }
52474             return undefined;
52475         }
52476         function isMatchingReference(source, target) {
52477             switch (target.kind) {
52478                 case 200 /* ParenthesizedExpression */:
52479                 case 218 /* NonNullExpression */:
52480                     return isMatchingReference(source, target.expression);
52481             }
52482             switch (source.kind) {
52483                 case 75 /* Identifier */:
52484                     return target.kind === 75 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
52485                         (target.kind === 242 /* VariableDeclaration */ || target.kind === 191 /* BindingElement */) &&
52486                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
52487                 case 104 /* ThisKeyword */:
52488                     return target.kind === 104 /* ThisKeyword */;
52489                 case 102 /* SuperKeyword */:
52490                     return target.kind === 102 /* SuperKeyword */;
52491                 case 218 /* NonNullExpression */:
52492                 case 200 /* ParenthesizedExpression */:
52493                     return isMatchingReference(source.expression, target);
52494                 case 194 /* PropertyAccessExpression */:
52495                 case 195 /* ElementAccessExpression */:
52496                     return ts.isAccessExpression(target) &&
52497                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
52498                         isMatchingReference(source.expression, target.expression);
52499             }
52500             return false;
52501         }
52502         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
52503         function containsTruthyCheck(source, target) {
52504             return isMatchingReference(source, target) ||
52505                 (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
52506                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
52507         }
52508         function getAccessedPropertyName(access) {
52509             return access.kind === 194 /* PropertyAccessExpression */ ? access.name.escapedText :
52510                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
52511                     undefined;
52512         }
52513         function containsMatchingReference(source, target) {
52514             while (ts.isAccessExpression(source)) {
52515                 source = source.expression;
52516                 if (isMatchingReference(source, target)) {
52517                     return true;
52518                 }
52519             }
52520             return false;
52521         }
52522         function optionalChainContainsReference(source, target) {
52523             while (ts.isOptionalChain(source)) {
52524                 source = source.expression;
52525                 if (isMatchingReference(source, target)) {
52526                     return true;
52527                 }
52528             }
52529             return false;
52530         }
52531         function isDiscriminantProperty(type, name) {
52532             if (type && type.flags & 1048576 /* Union */) {
52533                 var prop = getUnionOrIntersectionProperty(type, name);
52534                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
52535                     if (prop.isDiscriminantProperty === undefined) {
52536                         prop.isDiscriminantProperty =
52537                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
52538                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 63176704 /* Instantiable */);
52539                     }
52540                     return !!prop.isDiscriminantProperty;
52541                 }
52542             }
52543             return false;
52544         }
52545         function findDiscriminantProperties(sourceProperties, target) {
52546             var result;
52547             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
52548                 var sourceProperty = sourceProperties_2[_i];
52549                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
52550                     if (result) {
52551                         result.push(sourceProperty);
52552                         continue;
52553                     }
52554                     result = [sourceProperty];
52555                 }
52556             }
52557             return result;
52558         }
52559         function isOrContainsMatchingReference(source, target) {
52560             return isMatchingReference(source, target) || containsMatchingReference(source, target);
52561         }
52562         function hasMatchingArgument(callExpression, reference) {
52563             if (callExpression.arguments) {
52564                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
52565                     var argument = _a[_i];
52566                     if (isOrContainsMatchingReference(reference, argument)) {
52567                         return true;
52568                     }
52569                 }
52570             }
52571             if (callExpression.expression.kind === 194 /* PropertyAccessExpression */ &&
52572                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
52573                 return true;
52574             }
52575             return false;
52576         }
52577         function getFlowNodeId(flow) {
52578             if (!flow.id || flow.id < 0) {
52579                 flow.id = nextFlowId;
52580                 nextFlowId++;
52581             }
52582             return flow.id;
52583         }
52584         function typeMaybeAssignableTo(source, target) {
52585             if (!(source.flags & 1048576 /* Union */)) {
52586                 return isTypeAssignableTo(source, target);
52587             }
52588             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52589                 var t = _a[_i];
52590                 if (isTypeAssignableTo(t, target)) {
52591                     return true;
52592                 }
52593             }
52594             return false;
52595         }
52596         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
52597         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
52598         // we remove type string.
52599         function getAssignmentReducedType(declaredType, assignedType) {
52600             if (declaredType !== assignedType) {
52601                 if (assignedType.flags & 131072 /* Never */) {
52602                     return assignedType;
52603                 }
52604                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
52605                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
52606                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
52607                 }
52608                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
52609                 // For now, when that happens, we give up and don't narrow at all.  (This also
52610                 // means we'll never narrow for erroneous assignments where the assigned type
52611                 // is not assignable to the declared type.)
52612                 if (isTypeAssignableTo(assignedType, reducedType)) {
52613                     return reducedType;
52614                 }
52615             }
52616             return declaredType;
52617         }
52618         function getTypeFactsOfTypes(types) {
52619             var result = 0 /* None */;
52620             for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
52621                 var t = types_15[_i];
52622                 result |= getTypeFacts(t);
52623             }
52624             return result;
52625         }
52626         function isFunctionObjectType(type) {
52627             // We do a quick check for a "bind" property before performing the more expensive subtype
52628             // check. This gives us a quicker out in the common case where an object type is not a function.
52629             var resolved = resolveStructuredTypeMembers(type);
52630             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
52631                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
52632         }
52633         function getTypeFacts(type) {
52634             var flags = type.flags;
52635             if (flags & 4 /* String */) {
52636                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
52637             }
52638             if (flags & 128 /* StringLiteral */) {
52639                 var isEmpty = type.value === "";
52640                 return strictNullChecks ?
52641                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
52642                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
52643             }
52644             if (flags & (8 /* Number */ | 32 /* Enum */)) {
52645                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
52646             }
52647             if (flags & 256 /* NumberLiteral */) {
52648                 var isZero = type.value === 0;
52649                 return strictNullChecks ?
52650                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
52651                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
52652             }
52653             if (flags & 64 /* BigInt */) {
52654                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
52655             }
52656             if (flags & 2048 /* BigIntLiteral */) {
52657                 var isZero = isZeroBigInt(type);
52658                 return strictNullChecks ?
52659                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
52660                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
52661             }
52662             if (flags & 16 /* Boolean */) {
52663                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
52664             }
52665             if (flags & 528 /* BooleanLike */) {
52666                 return strictNullChecks ?
52667                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
52668                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
52669             }
52670             if (flags & 524288 /* Object */) {
52671                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
52672                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
52673                     isFunctionObjectType(type) ?
52674                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
52675                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52676             }
52677             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
52678                 return 9830144 /* UndefinedFacts */;
52679             }
52680             if (flags & 65536 /* Null */) {
52681                 return 9363232 /* NullFacts */;
52682             }
52683             if (flags & 12288 /* ESSymbolLike */) {
52684                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
52685             }
52686             if (flags & 67108864 /* NonPrimitive */) {
52687                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
52688             }
52689             if (flags & 131072 /* Never */) {
52690                 return 0 /* None */;
52691             }
52692             if (flags & 63176704 /* Instantiable */) {
52693                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
52694             }
52695             if (flags & 3145728 /* UnionOrIntersection */) {
52696                 return getTypeFactsOfTypes(type.types);
52697             }
52698             return 16777215 /* All */;
52699         }
52700         function getTypeWithFacts(type, include) {
52701             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
52702         }
52703         function getTypeWithDefault(type, defaultExpression) {
52704             if (defaultExpression) {
52705                 var defaultType = getTypeOfExpression(defaultExpression);
52706                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
52707             }
52708             return type;
52709         }
52710         function getTypeOfDestructuredProperty(type, name) {
52711             var nameType = getLiteralTypeFromPropertyName(name);
52712             if (!isTypeUsableAsPropertyName(nameType))
52713                 return errorType;
52714             var text = getPropertyNameFromType(nameType);
52715             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
52716                 isNumericLiteralName(text) && getIndexTypeOfType(type, 1 /* Number */) ||
52717                 getIndexTypeOfType(type, 0 /* String */) ||
52718                 errorType;
52719         }
52720         function getTypeOfDestructuredArrayElement(type, index) {
52721             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
52722                 checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) ||
52723                 errorType;
52724         }
52725         function getTypeOfDestructuredSpreadExpression(type) {
52726             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
52727         }
52728         function getAssignedTypeOfBinaryExpression(node) {
52729             var isDestructuringDefaultAssignment = node.parent.kind === 192 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
52730                 node.parent.kind === 281 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
52731             return isDestructuringDefaultAssignment ?
52732                 getTypeWithDefault(getAssignedType(node), node.right) :
52733                 getTypeOfExpression(node.right);
52734         }
52735         function isDestructuringAssignmentTarget(parent) {
52736             return parent.parent.kind === 209 /* BinaryExpression */ && parent.parent.left === parent ||
52737                 parent.parent.kind === 232 /* ForOfStatement */ && parent.parent.initializer === parent;
52738         }
52739         function getAssignedTypeOfArrayLiteralElement(node, element) {
52740             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
52741         }
52742         function getAssignedTypeOfSpreadExpression(node) {
52743             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
52744         }
52745         function getAssignedTypeOfPropertyAssignment(node) {
52746             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
52747         }
52748         function getAssignedTypeOfShorthandPropertyAssignment(node) {
52749             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
52750         }
52751         function getAssignedType(node) {
52752             var parent = node.parent;
52753             switch (parent.kind) {
52754                 case 231 /* ForInStatement */:
52755                     return stringType;
52756                 case 232 /* ForOfStatement */:
52757                     return checkRightHandSideOfForOf(parent) || errorType;
52758                 case 209 /* BinaryExpression */:
52759                     return getAssignedTypeOfBinaryExpression(parent);
52760                 case 203 /* DeleteExpression */:
52761                     return undefinedType;
52762                 case 192 /* ArrayLiteralExpression */:
52763                     return getAssignedTypeOfArrayLiteralElement(parent, node);
52764                 case 213 /* SpreadElement */:
52765                     return getAssignedTypeOfSpreadExpression(parent);
52766                 case 281 /* PropertyAssignment */:
52767                     return getAssignedTypeOfPropertyAssignment(parent);
52768                 case 282 /* ShorthandPropertyAssignment */:
52769                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
52770             }
52771             return errorType;
52772         }
52773         function getInitialTypeOfBindingElement(node) {
52774             var pattern = node.parent;
52775             var parentType = getInitialType(pattern.parent);
52776             var type = pattern.kind === 189 /* ObjectBindingPattern */ ?
52777                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
52778                 !node.dotDotDotToken ?
52779                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
52780                     getTypeOfDestructuredSpreadExpression(parentType);
52781             return getTypeWithDefault(type, node.initializer);
52782         }
52783         function getTypeOfInitializer(node) {
52784             // Return the cached type if one is available. If the type of the variable was inferred
52785             // from its initializer, we'll already have cached the type. Otherwise we compute it now
52786             // without caching such that transient types are reflected.
52787             var links = getNodeLinks(node);
52788             return links.resolvedType || getTypeOfExpression(node);
52789         }
52790         function getInitialTypeOfVariableDeclaration(node) {
52791             if (node.initializer) {
52792                 return getTypeOfInitializer(node.initializer);
52793             }
52794             if (node.parent.parent.kind === 231 /* ForInStatement */) {
52795                 return stringType;
52796             }
52797             if (node.parent.parent.kind === 232 /* ForOfStatement */) {
52798                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
52799             }
52800             return errorType;
52801         }
52802         function getInitialType(node) {
52803             return node.kind === 242 /* VariableDeclaration */ ?
52804                 getInitialTypeOfVariableDeclaration(node) :
52805                 getInitialTypeOfBindingElement(node);
52806         }
52807         function isEmptyArrayAssignment(node) {
52808             return node.kind === 242 /* VariableDeclaration */ && node.initializer &&
52809                 isEmptyArrayLiteral(node.initializer) ||
52810                 node.kind !== 191 /* BindingElement */ && node.parent.kind === 209 /* BinaryExpression */ &&
52811                     isEmptyArrayLiteral(node.parent.right);
52812         }
52813         function getReferenceCandidate(node) {
52814             switch (node.kind) {
52815                 case 200 /* ParenthesizedExpression */:
52816                     return getReferenceCandidate(node.expression);
52817                 case 209 /* BinaryExpression */:
52818                     switch (node.operatorToken.kind) {
52819                         case 62 /* EqualsToken */:
52820                             return getReferenceCandidate(node.left);
52821                         case 27 /* CommaToken */:
52822                             return getReferenceCandidate(node.right);
52823                     }
52824             }
52825             return node;
52826         }
52827         function getReferenceRoot(node) {
52828             var parent = node.parent;
52829             return parent.kind === 200 /* ParenthesizedExpression */ ||
52830                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
52831                 parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
52832                 getReferenceRoot(parent) : node;
52833         }
52834         function getTypeOfSwitchClause(clause) {
52835             if (clause.kind === 277 /* CaseClause */) {
52836                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
52837             }
52838             return neverType;
52839         }
52840         function getSwitchClauseTypes(switchStatement) {
52841             var links = getNodeLinks(switchStatement);
52842             if (!links.switchTypes) {
52843                 links.switchTypes = [];
52844                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52845                     var clause = _a[_i];
52846                     links.switchTypes.push(getTypeOfSwitchClause(clause));
52847                 }
52848             }
52849             return links.switchTypes;
52850         }
52851         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
52852             var witnesses = [];
52853             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
52854                 var clause = _a[_i];
52855                 if (clause.kind === 277 /* CaseClause */) {
52856                     if (ts.isStringLiteralLike(clause.expression)) {
52857                         witnesses.push(clause.expression.text);
52858                         continue;
52859                     }
52860                     return ts.emptyArray;
52861                 }
52862                 if (retainDefault)
52863                     witnesses.push(/*explicitDefaultStatement*/ undefined);
52864             }
52865             return witnesses;
52866         }
52867         function eachTypeContainedIn(source, types) {
52868             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
52869         }
52870         function isTypeSubsetOf(source, target) {
52871             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
52872         }
52873         function isTypeSubsetOfUnion(source, target) {
52874             if (source.flags & 1048576 /* Union */) {
52875                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
52876                     var t = _a[_i];
52877                     if (!containsType(target.types, t)) {
52878                         return false;
52879                     }
52880                 }
52881                 return true;
52882             }
52883             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
52884                 return true;
52885             }
52886             return containsType(target.types, source);
52887         }
52888         function forEachType(type, f) {
52889             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
52890         }
52891         function everyType(type, f) {
52892             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
52893         }
52894         function filterType(type, f) {
52895             if (type.flags & 1048576 /* Union */) {
52896                 var types = type.types;
52897                 var filtered = ts.filter(types, f);
52898                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
52899             }
52900             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
52901         }
52902         function countTypes(type) {
52903             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
52904         }
52905         function mapType(type, mapper, noReductions) {
52906             if (type.flags & 131072 /* Never */) {
52907                 return type;
52908             }
52909             if (!(type.flags & 1048576 /* Union */)) {
52910                 return mapper(type);
52911             }
52912             var mappedTypes;
52913             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
52914                 var t = _a[_i];
52915                 var mapped = mapper(t);
52916                 if (mapped) {
52917                     if (!mappedTypes) {
52918                         mappedTypes = [mapped];
52919                     }
52920                     else {
52921                         mappedTypes.push(mapped);
52922                     }
52923                 }
52924             }
52925             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
52926         }
52927         function extractTypesOfKind(type, kind) {
52928             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
52929         }
52930         // Return a new type in which occurrences of the string and number primitive types in
52931         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
52932         // literals in typeWithLiterals, respectively.
52933         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
52934             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
52935                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
52936                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
52937                 return mapType(typeWithPrimitives, function (t) {
52938                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
52939                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
52940                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
52941                 });
52942             }
52943             return typeWithPrimitives;
52944         }
52945         function isIncomplete(flowType) {
52946             return flowType.flags === 0;
52947         }
52948         function getTypeFromFlowType(flowType) {
52949             return flowType.flags === 0 ? flowType.type : flowType;
52950         }
52951         function createFlowType(type, incomplete) {
52952             return incomplete ? { flags: 0, type: type } : type;
52953         }
52954         // An evolving array type tracks the element types that have so far been seen in an
52955         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
52956         // array types are ultimately converted into manifest array types (using getFinalArrayType)
52957         // and never escape the getFlowTypeOfReference function.
52958         function createEvolvingArrayType(elementType) {
52959             var result = createObjectType(256 /* EvolvingArray */);
52960             result.elementType = elementType;
52961             return result;
52962         }
52963         function getEvolvingArrayType(elementType) {
52964             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
52965         }
52966         // When adding evolving array element types we do not perform subtype reduction. Instead,
52967         // we defer subtype reduction until the evolving array type is finalized into a manifest
52968         // array type.
52969         function addEvolvingArrayElementType(evolvingArrayType, node) {
52970             var elementType = getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node));
52971             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
52972         }
52973         function createFinalArrayType(elementType) {
52974             return elementType.flags & 131072 /* Never */ ?
52975                 autoArrayType :
52976                 createArrayType(elementType.flags & 1048576 /* Union */ ?
52977                     getUnionType(elementType.types, 2 /* Subtype */) :
52978                     elementType);
52979         }
52980         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
52981         function getFinalArrayType(evolvingArrayType) {
52982             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
52983         }
52984         function finalizeEvolvingArrayType(type) {
52985             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
52986         }
52987         function getElementTypeOfEvolvingArrayType(type) {
52988             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
52989         }
52990         function isEvolvingArrayTypeList(types) {
52991             var hasEvolvingArrayType = false;
52992             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
52993                 var t = types_16[_i];
52994                 if (!(t.flags & 131072 /* Never */)) {
52995                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
52996                         return false;
52997                     }
52998                     hasEvolvingArrayType = true;
52999                 }
53000             }
53001             return hasEvolvingArrayType;
53002         }
53003         // At flow control branch or loop junctions, if the type along every antecedent code path
53004         // is an evolving array type, we construct a combined evolving array type. Otherwise we
53005         // finalize all evolving array types.
53006         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
53007             return isEvolvingArrayTypeList(types) ?
53008                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
53009                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
53010         }
53011         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
53012         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
53013         function isEvolvingArrayOperationTarget(node) {
53014             var root = getReferenceRoot(node);
53015             var parent = root.parent;
53016             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
53017                 parent.parent.kind === 196 /* CallExpression */
53018                     && ts.isIdentifier(parent.name)
53019                     && ts.isPushOrUnshiftIdentifier(parent.name));
53020             var isElementAssignment = parent.kind === 195 /* ElementAccessExpression */ &&
53021                 parent.expression === root &&
53022                 parent.parent.kind === 209 /* BinaryExpression */ &&
53023                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
53024                 parent.parent.left === parent &&
53025                 !ts.isAssignmentTarget(parent.parent) &&
53026                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
53027             return isLengthPushOrUnshift || isElementAssignment;
53028         }
53029         function isDeclarationWithExplicitTypeAnnotation(declaration) {
53030             return (declaration.kind === 242 /* VariableDeclaration */ || declaration.kind === 156 /* Parameter */ ||
53031                 declaration.kind === 159 /* PropertyDeclaration */ || declaration.kind === 158 /* PropertySignature */) &&
53032                 !!ts.getEffectiveTypeAnnotationNode(declaration);
53033         }
53034         function getExplicitTypeOfSymbol(symbol, diagnostic) {
53035             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
53036                 return getTypeOfSymbol(symbol);
53037             }
53038             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
53039                 var declaration = symbol.valueDeclaration;
53040                 if (declaration) {
53041                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
53042                         return getTypeOfSymbol(symbol);
53043                     }
53044                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 232 /* ForOfStatement */) {
53045                         var statement = declaration.parent.parent;
53046                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
53047                         if (expressionType) {
53048                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
53049                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
53050                         }
53051                     }
53052                     if (diagnostic) {
53053                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
53054                     }
53055                 }
53056             }
53057         }
53058         // We require the dotted function name in an assertion expression to be comprised of identifiers
53059         // that reference function, method, class or value module symbols; or variable, property or
53060         // parameter symbols with declarations that have explicit type annotations. Such references are
53061         // resolvable with no possibility of triggering circularities in control flow analysis.
53062         function getTypeOfDottedName(node, diagnostic) {
53063             if (!(node.flags & 16777216 /* InWithStatement */)) {
53064                 switch (node.kind) {
53065                     case 75 /* Identifier */:
53066                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
53067                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
53068                     case 104 /* ThisKeyword */:
53069                         return getExplicitThisType(node);
53070                     case 102 /* SuperKeyword */:
53071                         return checkSuperExpression(node);
53072                     case 194 /* PropertyAccessExpression */:
53073                         var type = getTypeOfDottedName(node.expression, diagnostic);
53074                         var prop = type && getPropertyOfType(type, node.name.escapedText);
53075                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
53076                     case 200 /* ParenthesizedExpression */:
53077                         return getTypeOfDottedName(node.expression, diagnostic);
53078                 }
53079             }
53080         }
53081         function getEffectsSignature(node) {
53082             var links = getNodeLinks(node);
53083             var signature = links.effectsSignature;
53084             if (signature === undefined) {
53085                 // A call expression parented by an expression statement is a potential assertion. Other call
53086                 // expressions are potential type predicate function calls. In order to avoid triggering
53087                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
53088                 // target expression of an assertion.
53089                 var funcType = void 0;
53090                 if (node.parent.kind === 226 /* ExpressionStatement */) {
53091                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
53092                 }
53093                 else if (node.expression.kind !== 102 /* SuperKeyword */) {
53094                     if (ts.isOptionalChain(node)) {
53095                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
53096                     }
53097                     else {
53098                         funcType = checkNonNullExpression(node.expression);
53099                     }
53100                 }
53101                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
53102                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
53103                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
53104                         undefined;
53105                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
53106             }
53107             return signature === unknownSignature ? undefined : signature;
53108         }
53109         function hasTypePredicateOrNeverReturnType(signature) {
53110             return !!(getTypePredicateOfSignature(signature) ||
53111                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
53112         }
53113         function getTypePredicateArgument(predicate, callExpression) {
53114             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
53115                 return callExpression.arguments[predicate.parameterIndex];
53116             }
53117             var invokedExpression = ts.skipParentheses(callExpression.expression);
53118             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
53119         }
53120         function reportFlowControlError(node) {
53121             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
53122             var sourceFile = ts.getSourceFileOfNode(node);
53123             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
53124             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
53125         }
53126         function isReachableFlowNode(flow) {
53127             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
53128             lastFlowNode = flow;
53129             lastFlowNodeReachable = result;
53130             return result;
53131         }
53132         function isFalseExpression(expr) {
53133             var node = ts.skipParentheses(expr);
53134             return node.kind === 91 /* FalseKeyword */ || node.kind === 209 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
53135                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
53136         }
53137         function isReachableFlowNodeWorker(flow, noCacheCheck) {
53138             while (true) {
53139                 if (flow === lastFlowNode) {
53140                     return lastFlowNodeReachable;
53141                 }
53142                 var flags = flow.flags;
53143                 if (flags & 4096 /* Shared */) {
53144                     if (!noCacheCheck) {
53145                         var id = getFlowNodeId(flow);
53146                         var reachable = flowNodeReachable[id];
53147                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
53148                     }
53149                     noCacheCheck = false;
53150                 }
53151                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
53152                     flow = flow.antecedent;
53153                 }
53154                 else if (flags & 512 /* Call */) {
53155                     var signature = getEffectsSignature(flow.node);
53156                     if (signature) {
53157                         var predicate = getTypePredicateOfSignature(signature);
53158                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */) {
53159                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
53160                             if (predicateArgument && isFalseExpression(predicateArgument)) {
53161                                 return false;
53162                             }
53163                         }
53164                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53165                             return false;
53166                         }
53167                     }
53168                     flow = flow.antecedent;
53169                 }
53170                 else if (flags & 4 /* BranchLabel */) {
53171                     // A branching point is reachable if any branch is reachable.
53172                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
53173                 }
53174                 else if (flags & 8 /* LoopLabel */) {
53175                     // A loop is reachable if the control flow path that leads to the top is reachable.
53176                     flow = flow.antecedents[0];
53177                 }
53178                 else if (flags & 128 /* SwitchClause */) {
53179                     // The control flow path representing an unmatched value in a switch statement with
53180                     // no default clause is unreachable if the switch statement is exhaustive.
53181                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
53182                         return false;
53183                     }
53184                     flow = flow.antecedent;
53185                 }
53186                 else if (flags & 1024 /* ReduceLabel */) {
53187                     // Cache is unreliable once we start adjusting labels
53188                     lastFlowNode = undefined;
53189                     var target = flow.target;
53190                     var saveAntecedents = target.antecedents;
53191                     target.antecedents = flow.antecedents;
53192                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
53193                     target.antecedents = saveAntecedents;
53194                     return result;
53195                 }
53196                 else {
53197                     return !(flags & 1 /* Unreachable */);
53198                 }
53199             }
53200         }
53201         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
53202             if (initialType === void 0) { initialType = declaredType; }
53203             var key;
53204             var keySet = false;
53205             var flowDepth = 0;
53206             if (flowAnalysisDisabled) {
53207                 return errorType;
53208             }
53209             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 133970943 /* Narrowable */)) {
53210                 return declaredType;
53211             }
53212             flowInvocationCount++;
53213             var sharedFlowStart = sharedFlowCount;
53214             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
53215             sharedFlowCount = sharedFlowStart;
53216             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
53217             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
53218             // on empty arrays are possible without implicit any errors and new element types can be inferred without
53219             // type mismatch errors.
53220             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
53221             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 218 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
53222                 return declaredType;
53223             }
53224             return resultType;
53225             function getOrSetCacheKey() {
53226                 if (keySet) {
53227                     return key;
53228                 }
53229                 keySet = true;
53230                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
53231             }
53232             function getTypeAtFlowNode(flow) {
53233                 if (flowDepth === 2000) {
53234                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
53235                     // and disable further control flow analysis in the containing function or module body.
53236                     flowAnalysisDisabled = true;
53237                     reportFlowControlError(reference);
53238                     return errorType;
53239                 }
53240                 flowDepth++;
53241                 while (true) {
53242                     var flags = flow.flags;
53243                     if (flags & 4096 /* Shared */) {
53244                         // We cache results of flow type resolution for shared nodes that were previously visited in
53245                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
53246                         // antecedent of more than one node.
53247                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
53248                             if (sharedFlowNodes[i] === flow) {
53249                                 flowDepth--;
53250                                 return sharedFlowTypes[i];
53251                             }
53252                         }
53253                     }
53254                     var type = void 0;
53255                     if (flags & 16 /* Assignment */) {
53256                         type = getTypeAtFlowAssignment(flow);
53257                         if (!type) {
53258                             flow = flow.antecedent;
53259                             continue;
53260                         }
53261                     }
53262                     else if (flags & 512 /* Call */) {
53263                         type = getTypeAtFlowCall(flow);
53264                         if (!type) {
53265                             flow = flow.antecedent;
53266                             continue;
53267                         }
53268                     }
53269                     else if (flags & 96 /* Condition */) {
53270                         type = getTypeAtFlowCondition(flow);
53271                     }
53272                     else if (flags & 128 /* SwitchClause */) {
53273                         type = getTypeAtSwitchClause(flow);
53274                     }
53275                     else if (flags & 12 /* Label */) {
53276                         if (flow.antecedents.length === 1) {
53277                             flow = flow.antecedents[0];
53278                             continue;
53279                         }
53280                         type = flags & 4 /* BranchLabel */ ?
53281                             getTypeAtFlowBranchLabel(flow) :
53282                             getTypeAtFlowLoopLabel(flow);
53283                     }
53284                     else if (flags & 256 /* ArrayMutation */) {
53285                         type = getTypeAtFlowArrayMutation(flow);
53286                         if (!type) {
53287                             flow = flow.antecedent;
53288                             continue;
53289                         }
53290                     }
53291                     else if (flags & 1024 /* ReduceLabel */) {
53292                         var target = flow.target;
53293                         var saveAntecedents = target.antecedents;
53294                         target.antecedents = flow.antecedents;
53295                         type = getTypeAtFlowNode(flow.antecedent);
53296                         target.antecedents = saveAntecedents;
53297                     }
53298                     else if (flags & 2 /* Start */) {
53299                         // Check if we should continue with the control flow of the containing function.
53300                         var container = flow.node;
53301                         if (container && container !== flowContainer &&
53302                             reference.kind !== 194 /* PropertyAccessExpression */ &&
53303                             reference.kind !== 195 /* ElementAccessExpression */ &&
53304                             reference.kind !== 104 /* ThisKeyword */) {
53305                             flow = container.flowNode;
53306                             continue;
53307                         }
53308                         // At the top of the flow we have the initial type.
53309                         type = initialType;
53310                     }
53311                     else {
53312                         // Unreachable code errors are reported in the binding phase. Here we
53313                         // simply return the non-auto declared type to reduce follow-on errors.
53314                         type = convertAutoToAny(declaredType);
53315                     }
53316                     if (flags & 4096 /* Shared */) {
53317                         // Record visited node and the associated type in the cache.
53318                         sharedFlowNodes[sharedFlowCount] = flow;
53319                         sharedFlowTypes[sharedFlowCount] = type;
53320                         sharedFlowCount++;
53321                     }
53322                     flowDepth--;
53323                     return type;
53324                 }
53325             }
53326             function getInitialOrAssignedType(flow) {
53327                 var node = flow.node;
53328                 return getConstraintForLocation(node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */ ?
53329                     getInitialType(node) :
53330                     getAssignedType(node), reference);
53331             }
53332             function getTypeAtFlowAssignment(flow) {
53333                 var node = flow.node;
53334                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
53335                 // only need to evaluate the assigned type if the declared type is a union type.
53336                 if (isMatchingReference(reference, node)) {
53337                     if (!isReachableFlowNode(flow)) {
53338                         return unreachableNeverType;
53339                     }
53340                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
53341                         var flowType = getTypeAtFlowNode(flow.antecedent);
53342                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
53343                     }
53344                     if (declaredType === autoType || declaredType === autoArrayType) {
53345                         if (isEmptyArrayAssignment(node)) {
53346                             return getEvolvingArrayType(neverType);
53347                         }
53348                         var assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(flow));
53349                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
53350                     }
53351                     if (declaredType.flags & 1048576 /* Union */) {
53352                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
53353                     }
53354                     return declaredType;
53355                 }
53356                 // We didn't have a direct match. However, if the reference is a dotted name, this
53357                 // may be an assignment to a left hand part of the reference. For example, for a
53358                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
53359                 // return the declared type.
53360                 if (containsMatchingReference(reference, node)) {
53361                     if (!isReachableFlowNode(flow)) {
53362                         return unreachableNeverType;
53363                     }
53364                     // A matching dotted name might also be an expando property on a function *expression*,
53365                     // in which case we continue control flow analysis back to the function's declaration
53366                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
53367                         var init = ts.getDeclaredExpandoInitializer(node);
53368                         if (init && (init.kind === 201 /* FunctionExpression */ || init.kind === 202 /* ArrowFunction */)) {
53369                             return getTypeAtFlowNode(flow.antecedent);
53370                         }
53371                     }
53372                     return declaredType;
53373                 }
53374                 // for (const _ in ref) acts as a nonnull on ref
53375                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 231 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
53376                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
53377                 }
53378                 // Assignment doesn't affect reference
53379                 return undefined;
53380             }
53381             function narrowTypeByAssertion(type, expr) {
53382                 var node = ts.skipParentheses(expr);
53383                 if (node.kind === 91 /* FalseKeyword */) {
53384                     return unreachableNeverType;
53385                 }
53386                 if (node.kind === 209 /* BinaryExpression */) {
53387                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
53388                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
53389                     }
53390                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
53391                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
53392                     }
53393                 }
53394                 return narrowType(type, node, /*assumeTrue*/ true);
53395             }
53396             function getTypeAtFlowCall(flow) {
53397                 var signature = getEffectsSignature(flow.node);
53398                 if (signature) {
53399                     var predicate = getTypePredicateOfSignature(signature);
53400                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
53401                         var flowType = getTypeAtFlowNode(flow.antecedent);
53402                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
53403                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
53404                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
53405                                 type;
53406                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
53407                     }
53408                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
53409                         return unreachableNeverType;
53410                     }
53411                 }
53412                 return undefined;
53413             }
53414             function getTypeAtFlowArrayMutation(flow) {
53415                 if (declaredType === autoType || declaredType === autoArrayType) {
53416                     var node = flow.node;
53417                     var expr = node.kind === 196 /* CallExpression */ ?
53418                         node.expression.expression :
53419                         node.left.expression;
53420                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
53421                         var flowType = getTypeAtFlowNode(flow.antecedent);
53422                         var type = getTypeFromFlowType(flowType);
53423                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
53424                             var evolvedType_1 = type;
53425                             if (node.kind === 196 /* CallExpression */) {
53426                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
53427                                     var arg = _a[_i];
53428                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
53429                                 }
53430                             }
53431                             else {
53432                                 // 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)
53433                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
53434                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
53435                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
53436                                 }
53437                             }
53438                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
53439                         }
53440                         return flowType;
53441                     }
53442                 }
53443                 return undefined;
53444             }
53445             function getTypeAtFlowCondition(flow) {
53446                 var flowType = getTypeAtFlowNode(flow.antecedent);
53447                 var type = getTypeFromFlowType(flowType);
53448                 if (type.flags & 131072 /* Never */) {
53449                     return flowType;
53450                 }
53451                 // If we have an antecedent type (meaning we're reachable in some way), we first
53452                 // attempt to narrow the antecedent type. If that produces the never type, and if
53453                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
53454                 // take the type guard as an indication that control *could* reach here once we
53455                 // have the complete type. We proceed by switching to the silent never type which
53456                 // doesn't report errors when operators are applied to it. Note that this is the
53457                 // *only* place a silent never type is ever generated.
53458                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
53459                 var nonEvolvingType = finalizeEvolvingArrayType(type);
53460                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
53461                 if (narrowedType === nonEvolvingType) {
53462                     return flowType;
53463                 }
53464                 var incomplete = isIncomplete(flowType);
53465                 var resultType = incomplete && narrowedType.flags & 131072 /* Never */ ? silentNeverType : narrowedType;
53466                 return createFlowType(resultType, incomplete);
53467             }
53468             function getTypeAtSwitchClause(flow) {
53469                 var expr = flow.switchStatement.expression;
53470                 var flowType = getTypeAtFlowNode(flow.antecedent);
53471                 var type = getTypeFromFlowType(flowType);
53472                 if (isMatchingReference(reference, expr)) {
53473                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53474                 }
53475                 else if (expr.kind === 204 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
53476                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
53477                 }
53478                 else {
53479                     if (strictNullChecks) {
53480                         if (optionalChainContainsReference(expr, reference)) {
53481                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
53482                         }
53483                         else if (expr.kind === 204 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
53484                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
53485                         }
53486                     }
53487                     if (isMatchingReferenceDiscriminant(expr, type)) {
53488                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
53489                     }
53490                 }
53491                 return createFlowType(type, isIncomplete(flowType));
53492             }
53493             function getTypeAtFlowBranchLabel(flow) {
53494                 var antecedentTypes = [];
53495                 var subtypeReduction = false;
53496                 var seenIncomplete = false;
53497                 var bypassFlow;
53498                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53499                     var antecedent = _a[_i];
53500                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
53501                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
53502                         bypassFlow = antecedent;
53503                         continue;
53504                     }
53505                     var flowType = getTypeAtFlowNode(antecedent);
53506                     var type = getTypeFromFlowType(flowType);
53507                     // If the type at a particular antecedent path is the declared type and the
53508                     // reference is known to always be assigned (i.e. when declared and initial types
53509                     // are the same), there is no reason to process more antecedents since the only
53510                     // possible outcome is subtypes that will be removed in the final union type anyway.
53511                     if (type === declaredType && declaredType === initialType) {
53512                         return type;
53513                     }
53514                     ts.pushIfUnique(antecedentTypes, type);
53515                     // If an antecedent type is not a subset of the declared type, we need to perform
53516                     // subtype reduction. This happens when a "foreign" type is injected into the control
53517                     // flow using the instanceof operator or a user defined type predicate.
53518                     if (!isTypeSubsetOf(type, declaredType)) {
53519                         subtypeReduction = true;
53520                     }
53521                     if (isIncomplete(flowType)) {
53522                         seenIncomplete = true;
53523                     }
53524                 }
53525                 if (bypassFlow) {
53526                     var flowType = getTypeAtFlowNode(bypassFlow);
53527                     var type = getTypeFromFlowType(flowType);
53528                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
53529                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
53530                     // the risk of circularities, we only want to perform them when they make a difference.
53531                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
53532                         if (type === declaredType && declaredType === initialType) {
53533                             return type;
53534                         }
53535                         antecedentTypes.push(type);
53536                         if (!isTypeSubsetOf(type, declaredType)) {
53537                             subtypeReduction = true;
53538                         }
53539                         if (isIncomplete(flowType)) {
53540                             seenIncomplete = true;
53541                         }
53542                     }
53543                 }
53544                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
53545             }
53546             function getTypeAtFlowLoopLabel(flow) {
53547                 // If we have previously computed the control flow type for the reference at
53548                 // this flow loop junction, return the cached type.
53549                 var id = getFlowNodeId(flow);
53550                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = ts.createMap());
53551                 var key = getOrSetCacheKey();
53552                 if (!key) {
53553                     // No cache key is generated when binding patterns are in unnarrowable situations
53554                     return declaredType;
53555                 }
53556                 var cached = cache.get(key);
53557                 if (cached) {
53558                     return cached;
53559                 }
53560                 // If this flow loop junction and reference are already being processed, return
53561                 // the union of the types computed for each branch so far, marked as incomplete.
53562                 // It is possible to see an empty array in cases where loops are nested and the
53563                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
53564                 // In such cases we restart the analysis of the inner loop, which will then see
53565                 // a non-empty in-process array for the outer loop and eventually terminate because
53566                 // the first antecedent of a loop junction is always the non-looping control flow
53567                 // path that leads to the top.
53568                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
53569                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
53570                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
53571                     }
53572                 }
53573                 // Add the flow loop junction and reference to the in-process stack and analyze
53574                 // each antecedent code path.
53575                 var antecedentTypes = [];
53576                 var subtypeReduction = false;
53577                 var firstAntecedentType;
53578                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
53579                     var antecedent = _a[_i];
53580                     var flowType = void 0;
53581                     if (!firstAntecedentType) {
53582                         // The first antecedent of a loop junction is always the non-looping control
53583                         // flow path that leads to the top.
53584                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
53585                     }
53586                     else {
53587                         // All but the first antecedent are the looping control flow paths that lead
53588                         // back to the loop junction. We track these on the flow loop stack.
53589                         flowLoopNodes[flowLoopCount] = flow;
53590                         flowLoopKeys[flowLoopCount] = key;
53591                         flowLoopTypes[flowLoopCount] = antecedentTypes;
53592                         flowLoopCount++;
53593                         var saveFlowTypeCache = flowTypeCache;
53594                         flowTypeCache = undefined;
53595                         flowType = getTypeAtFlowNode(antecedent);
53596                         flowTypeCache = saveFlowTypeCache;
53597                         flowLoopCount--;
53598                         // If we see a value appear in the cache it is a sign that control flow analysis
53599                         // was restarted and completed by checkExpressionCached. We can simply pick up
53600                         // the resulting type and bail out.
53601                         var cached_1 = cache.get(key);
53602                         if (cached_1) {
53603                             return cached_1;
53604                         }
53605                     }
53606                     var type = getTypeFromFlowType(flowType);
53607                     ts.pushIfUnique(antecedentTypes, type);
53608                     // If an antecedent type is not a subset of the declared type, we need to perform
53609                     // subtype reduction. This happens when a "foreign" type is injected into the control
53610                     // flow using the instanceof operator or a user defined type predicate.
53611                     if (!isTypeSubsetOf(type, declaredType)) {
53612                         subtypeReduction = true;
53613                     }
53614                     // If the type at a particular antecedent path is the declared type there is no
53615                     // reason to process more antecedents since the only possible outcome is subtypes
53616                     // that will be removed in the final union type anyway.
53617                     if (type === declaredType) {
53618                         break;
53619                     }
53620                 }
53621                 // The result is incomplete if the first antecedent (the non-looping control flow path)
53622                 // is incomplete.
53623                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
53624                 if (isIncomplete(firstAntecedentType)) {
53625                     return createFlowType(result, /*incomplete*/ true);
53626                 }
53627                 cache.set(key, result);
53628                 return result;
53629             }
53630             function isMatchingReferenceDiscriminant(expr, computedType) {
53631                 if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
53632                     return false;
53633                 }
53634                 var name = getAccessedPropertyName(expr);
53635                 if (name === undefined) {
53636                     return false;
53637                 }
53638                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name);
53639             }
53640             function narrowTypeByDiscriminant(type, access, narrowType) {
53641                 var propName = getAccessedPropertyName(access);
53642                 if (propName === undefined) {
53643                     return type;
53644                 }
53645                 var propType = getTypeOfPropertyOfType(type, propName);
53646                 if (!propType) {
53647                     return type;
53648                 }
53649                 var narrowedPropType = narrowType(propType);
53650                 return filterType(type, function (t) {
53651                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
53652                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
53653                 });
53654             }
53655             function narrowTypeByTruthiness(type, expr, assumeTrue) {
53656                 if (isMatchingReference(reference, expr)) {
53657                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
53658                 }
53659                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
53660                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53661                 }
53662                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
53663                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
53664                 }
53665                 return type;
53666             }
53667             function isTypePresencePossible(type, propName, assumeTrue) {
53668                 if (getIndexInfoOfType(type, 0 /* String */)) {
53669                     return true;
53670                 }
53671                 var prop = getPropertyOfType(type, propName);
53672                 if (prop) {
53673                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
53674                 }
53675                 return !assumeTrue;
53676             }
53677             function narrowByInKeyword(type, literal, assumeTrue) {
53678                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */) || isThisTypeParameter(type)) {
53679                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
53680                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
53681                 }
53682                 return type;
53683             }
53684             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
53685                 switch (expr.operatorToken.kind) {
53686                     case 62 /* EqualsToken */:
53687                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
53688                     case 34 /* EqualsEqualsToken */:
53689                     case 35 /* ExclamationEqualsToken */:
53690                     case 36 /* EqualsEqualsEqualsToken */:
53691                     case 37 /* ExclamationEqualsEqualsToken */:
53692                         var operator_1 = expr.operatorToken.kind;
53693                         var left_1 = getReferenceCandidate(expr.left);
53694                         var right_1 = getReferenceCandidate(expr.right);
53695                         if (left_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
53696                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
53697                         }
53698                         if (right_1.kind === 204 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
53699                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
53700                         }
53701                         if (isMatchingReference(reference, left_1)) {
53702                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
53703                         }
53704                         if (isMatchingReference(reference, right_1)) {
53705                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
53706                         }
53707                         if (strictNullChecks) {
53708                             if (optionalChainContainsReference(left_1, reference)) {
53709                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
53710                             }
53711                             else if (optionalChainContainsReference(right_1, reference)) {
53712                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
53713                             }
53714                         }
53715                         if (isMatchingReferenceDiscriminant(left_1, declaredType)) {
53716                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
53717                         }
53718                         if (isMatchingReferenceDiscriminant(right_1, declaredType)) {
53719                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
53720                         }
53721                         if (isMatchingConstructorReference(left_1)) {
53722                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
53723                         }
53724                         if (isMatchingConstructorReference(right_1)) {
53725                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
53726                         }
53727                         break;
53728                     case 98 /* InstanceOfKeyword */:
53729                         return narrowTypeByInstanceof(type, expr, assumeTrue);
53730                     case 97 /* InKeyword */:
53731                         var target = getReferenceCandidate(expr.right);
53732                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
53733                             return narrowByInKeyword(type, expr.left, assumeTrue);
53734                         }
53735                         break;
53736                     case 27 /* CommaToken */:
53737                         return narrowType(type, expr.right, assumeTrue);
53738                 }
53739                 return type;
53740             }
53741             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
53742                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
53743                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
53744                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
53745                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
53746                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
53747                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
53748                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
53749                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
53750                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
53751                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
53752                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
53753                 var valueType = getTypeOfExpression(value);
53754                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
53755                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
53756                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
53757                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53758             }
53759             function narrowTypeByEquality(type, operator, value, assumeTrue) {
53760                 if (type.flags & 1 /* Any */) {
53761                     return type;
53762                 }
53763                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53764                     assumeTrue = !assumeTrue;
53765                 }
53766                 var valueType = getTypeOfExpression(value);
53767                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
53768                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53769                         return valueType;
53770                     }
53771                     if (valueType.flags & 524288 /* Object */) {
53772                         return nonPrimitiveType;
53773                     }
53774                     return type;
53775                 }
53776                 if (valueType.flags & 98304 /* Nullable */) {
53777                     if (!strictNullChecks) {
53778                         return type;
53779                     }
53780                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
53781                     var facts = doubleEquals ?
53782                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
53783                         valueType.flags & 65536 /* Null */ ?
53784                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
53785                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
53786                     return getTypeWithFacts(type, facts);
53787                 }
53788                 if (type.flags & 67637251 /* NotUnionOrUnit */) {
53789                     return type;
53790                 }
53791                 if (assumeTrue) {
53792                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
53793                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
53794                         function (t) { return areTypesComparable(t, valueType); };
53795                     var narrowedType = filterType(type, filterFn);
53796                     return narrowedType.flags & 131072 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType);
53797                 }
53798                 if (isUnitType(valueType)) {
53799                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
53800                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
53801                 }
53802                 return type;
53803             }
53804             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
53805                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
53806                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
53807                     assumeTrue = !assumeTrue;
53808                 }
53809                 var target = getReferenceCandidate(typeOfExpr.expression);
53810                 if (!isMatchingReference(reference, target)) {
53811                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
53812                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
53813                     }
53814                     return type;
53815                 }
53816                 if (type.flags & 1 /* Any */ && literal.text === "function") {
53817                     return type;
53818                 }
53819                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
53820                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
53821                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
53822                     if (typeOfExpr.parent.parent.kind === 209 /* BinaryExpression */) {
53823                         var expr = typeOfExpr.parent.parent;
53824                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
53825                             return nonPrimitiveType;
53826                         }
53827                     }
53828                     return getUnionType([nonPrimitiveType, nullType]);
53829                 }
53830                 var facts = assumeTrue ?
53831                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
53832                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
53833                 return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts);
53834                 function narrowTypeForTypeof(type) {
53835                     // We narrow a non-union type to an exact primitive type if the non-union type
53836                     // is a supertype of that primitive type. For example, type 'any' can be narrowed
53837                     // to one of the primitive types.
53838                     var targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text);
53839                     if (targetType) {
53840                         if (isTypeSubtypeOf(type, targetType)) {
53841                             return type;
53842                         }
53843                         if (isTypeSubtypeOf(targetType, type)) {
53844                             return targetType;
53845                         }
53846                         if (type.flags & 63176704 /* Instantiable */) {
53847                             var constraint = getBaseConstraintOfType(type) || anyType;
53848                             if (isTypeSubtypeOf(targetType, constraint)) {
53849                                 return getIntersectionType([type, targetType]);
53850                             }
53851                         }
53852                     }
53853                     return type;
53854                 }
53855             }
53856             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
53857                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
53858                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
53859             }
53860             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
53861                 // We only narrow if all case expressions specify
53862                 // values with unit types, except for the case where
53863                 // `type` is unknown. In this instance we map object
53864                 // types to the nonPrimitive type and narrow with that.
53865                 var switchTypes = getSwitchClauseTypes(switchStatement);
53866                 if (!switchTypes.length) {
53867                     return type;
53868                 }
53869                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
53870                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
53871                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
53872                     var groundClauseTypes = void 0;
53873                     for (var i = 0; i < clauseTypes.length; i += 1) {
53874                         var t = clauseTypes[i];
53875                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
53876                             if (groundClauseTypes !== undefined) {
53877                                 groundClauseTypes.push(t);
53878                             }
53879                         }
53880                         else if (t.flags & 524288 /* Object */) {
53881                             if (groundClauseTypes === undefined) {
53882                                 groundClauseTypes = clauseTypes.slice(0, i);
53883                             }
53884                             groundClauseTypes.push(nonPrimitiveType);
53885                         }
53886                         else {
53887                             return type;
53888                         }
53889                     }
53890                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
53891                 }
53892                 var discriminantType = getUnionType(clauseTypes);
53893                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
53894                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
53895                 if (!hasDefaultClause) {
53896                     return caseType;
53897                 }
53898                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
53899                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
53900             }
53901             function getImpliedTypeFromTypeofCase(type, text) {
53902                 switch (text) {
53903                     case "function":
53904                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
53905                     case "object":
53906                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
53907                     default:
53908                         return typeofTypesByName.get(text) || type;
53909                 }
53910             }
53911             function narrowTypeForTypeofSwitch(candidate) {
53912                 return function (type) {
53913                     if (isTypeSubtypeOf(candidate, type)) {
53914                         return candidate;
53915                     }
53916                     if (type.flags & 63176704 /* Instantiable */) {
53917                         var constraint = getBaseConstraintOfType(type) || anyType;
53918                         if (isTypeSubtypeOf(candidate, constraint)) {
53919                             return getIntersectionType([type, candidate]);
53920                         }
53921                     }
53922                     return type;
53923                 };
53924             }
53925             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
53926                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
53927                 if (!switchWitnesses.length) {
53928                     return type;
53929                 }
53930                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
53931                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
53932                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
53933                 var clauseWitnesses;
53934                 var switchFacts;
53935                 if (defaultCaseLocation > -1) {
53936                     // We no longer need the undefined denoting an
53937                     // explicit default case. Remove the undefined and
53938                     // fix-up clauseStart and clauseEnd.  This means
53939                     // that we don't have to worry about undefined
53940                     // in the witness array.
53941                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
53942                     // The adjusted clause start and end after removing the `default` statement.
53943                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
53944                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
53945                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
53946                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
53947                 }
53948                 else {
53949                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
53950                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
53951                 }
53952                 if (hasDefaultClause) {
53953                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
53954                 }
53955                 /*
53956                   The implied type is the raw type suggested by a
53957                   value being caught in this clause.
53958
53959                   When the clause contains a default case we ignore
53960                   the implied type and try to narrow using any facts
53961                   we can learn: see `switchFacts`.
53962
53963                   Example:
53964                   switch (typeof x) {
53965                       case 'number':
53966                       case 'string': break;
53967                       default: break;
53968                       case 'number':
53969                       case 'boolean': break
53970                   }
53971
53972                   In the first clause (case `number` and `string`) the
53973                   implied type is number | string.
53974
53975                   In the default clause we de not compute an implied type.
53976
53977                   In the third clause (case `number` and `boolean`)
53978                   the naive implied type is number | boolean, however
53979                   we use the type facts to narrow the implied type to
53980                   boolean. We know that number cannot be selected
53981                   because it is caught in the first clause.
53982                 */
53983                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofCase(type, text); })), switchFacts);
53984                 if (impliedType.flags & 1048576 /* Union */) {
53985                     impliedType = getAssignmentReducedType(impliedType, getBaseConstraintOrType(type));
53986                 }
53987                 return getTypeWithFacts(mapType(type, narrowTypeForTypeofSwitch(impliedType)), switchFacts);
53988             }
53989             function isMatchingConstructorReference(expr) {
53990                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
53991                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
53992                     isMatchingReference(reference, expr.expression);
53993             }
53994             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
53995                 // Do not narrow when checking inequality.
53996                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
53997                     return type;
53998                 }
53999                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
54000                 var identifierType = getTypeOfExpression(identifier);
54001                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
54002                     return type;
54003                 }
54004                 // Get the prototype property of the type identifier so we can find out its type.
54005                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
54006                 if (!prototypeProperty) {
54007                     return type;
54008                 }
54009                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
54010                 var prototypeType = getTypeOfSymbol(prototypeProperty);
54011                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
54012                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
54013                     return type;
54014                 }
54015                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
54016                 if (isTypeAny(type)) {
54017                     return candidate;
54018                 }
54019                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
54020                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
54021                 function isConstructedBy(source, target) {
54022                     // If either the source or target type are a class type then we need to check that they are the same exact type.
54023                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
54024                     // that defines the same set of properties as class `A`, in that case they are structurally the same
54025                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
54026                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
54027                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
54028                         return source.symbol === target.symbol;
54029                     }
54030                     // For all other types just check that the `source` type is a subtype of the `target` type.
54031                     return isTypeSubtypeOf(source, target);
54032                 }
54033             }
54034             function narrowTypeByInstanceof(type, expr, assumeTrue) {
54035                 var left = getReferenceCandidate(expr.left);
54036                 if (!isMatchingReference(reference, left)) {
54037                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
54038                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54039                     }
54040                     return type;
54041                 }
54042                 // Check that right operand is a function type with a prototype property
54043                 var rightType = getTypeOfExpression(expr.right);
54044                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
54045                     return type;
54046                 }
54047                 var targetType;
54048                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
54049                 if (prototypeProperty) {
54050                     // Target type is type of the prototype property
54051                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
54052                     if (!isTypeAny(prototypePropertyType)) {
54053                         targetType = prototypePropertyType;
54054                     }
54055                 }
54056                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
54057                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
54058                     return type;
54059                 }
54060                 if (!targetType) {
54061                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
54062                     targetType = constructSignatures.length ?
54063                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
54064                         emptyObjectType;
54065                 }
54066                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
54067             }
54068             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
54069                 if (!assumeTrue) {
54070                     return filterType(type, function (t) { return !isRelated(t, candidate); });
54071                 }
54072                 // If the current type is a union type, remove all constituents that couldn't be instances of
54073                 // the candidate type. If one or more constituents remain, return a union of those.
54074                 if (type.flags & 1048576 /* Union */) {
54075                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
54076                     if (!(assignableType.flags & 131072 /* Never */)) {
54077                         return assignableType;
54078                     }
54079                 }
54080                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
54081                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
54082                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
54083                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
54084                 // two types.
54085                 return isTypeSubtypeOf(candidate, type) ? candidate :
54086                     isTypeAssignableTo(type, candidate) ? type :
54087                         isTypeAssignableTo(candidate, type) ? candidate :
54088                             getIntersectionType([type, candidate]);
54089             }
54090             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
54091                 if (hasMatchingArgument(callExpression, reference)) {
54092                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
54093                     var predicate = signature && getTypePredicateOfSignature(signature);
54094                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
54095                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
54096                     }
54097                 }
54098                 return type;
54099             }
54100             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
54101                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
54102                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
54103                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
54104                     if (predicateArgument) {
54105                         if (isMatchingReference(reference, predicateArgument)) {
54106                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
54107                         }
54108                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
54109                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
54110                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
54111                         }
54112                         if (isMatchingReferenceDiscriminant(predicateArgument, declaredType)) {
54113                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
54114                         }
54115                     }
54116                 }
54117                 return type;
54118             }
54119             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
54120             // will be a subtype or the same type as the argument.
54121             function narrowType(type, expr, assumeTrue) {
54122                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
54123                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
54124                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
54125                     return narrowTypeByOptionality(type, expr, assumeTrue);
54126                 }
54127                 switch (expr.kind) {
54128                     case 75 /* Identifier */:
54129                     case 104 /* ThisKeyword */:
54130                     case 102 /* SuperKeyword */:
54131                     case 194 /* PropertyAccessExpression */:
54132                     case 195 /* ElementAccessExpression */:
54133                         return narrowTypeByTruthiness(type, expr, assumeTrue);
54134                     case 196 /* CallExpression */:
54135                         return narrowTypeByCallExpression(type, expr, assumeTrue);
54136                     case 200 /* ParenthesizedExpression */:
54137                         return narrowType(type, expr.expression, assumeTrue);
54138                     case 209 /* BinaryExpression */:
54139                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
54140                     case 207 /* PrefixUnaryExpression */:
54141                         if (expr.operator === 53 /* ExclamationToken */) {
54142                             return narrowType(type, expr.operand, !assumeTrue);
54143                         }
54144                         break;
54145                 }
54146                 return type;
54147             }
54148             function narrowTypeByOptionality(type, expr, assumePresent) {
54149                 if (isMatchingReference(reference, expr)) {
54150                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
54151                 }
54152                 if (isMatchingReferenceDiscriminant(expr, declaredType)) {
54153                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
54154                 }
54155                 return type;
54156             }
54157         }
54158         function getTypeOfSymbolAtLocation(symbol, location) {
54159             symbol = symbol.exportSymbol || symbol;
54160             // If we have an identifier or a property access at the given location, if the location is
54161             // an dotted name expression, and if the location is not an assignment target, obtain the type
54162             // of the expression (which will reflect control flow analysis). If the expression indeed
54163             // resolved to the given symbol, return the narrowed type.
54164             if (location.kind === 75 /* Identifier */) {
54165                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
54166                     location = location.parent;
54167                 }
54168                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
54169                     var type = getTypeOfExpression(location);
54170                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
54171                         return type;
54172                     }
54173                 }
54174             }
54175             // The location isn't a reference to the given symbol, meaning we're being asked
54176             // a hypothetical question of what type the symbol would have if there was a reference
54177             // to it at the given location. Since we have no control flow information for the
54178             // hypothetical reference (control flow information is created and attached by the
54179             // binder), we simply return the declared type of the symbol.
54180             return getTypeOfSymbol(symbol);
54181         }
54182         function getControlFlowContainer(node) {
54183             return ts.findAncestor(node.parent, function (node) {
54184                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
54185                     node.kind === 250 /* ModuleBlock */ ||
54186                     node.kind === 290 /* SourceFile */ ||
54187                     node.kind === 159 /* PropertyDeclaration */;
54188             });
54189         }
54190         // Check if a parameter is assigned anywhere within its declaring function.
54191         function isParameterAssigned(symbol) {
54192             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
54193             var links = getNodeLinks(func);
54194             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
54195                 links.flags |= 8388608 /* AssignmentsMarked */;
54196                 if (!hasParentWithAssignmentsMarked(func)) {
54197                     markParameterAssignments(func);
54198                 }
54199             }
54200             return symbol.isAssigned || false;
54201         }
54202         function hasParentWithAssignmentsMarked(node) {
54203             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
54204         }
54205         function markParameterAssignments(node) {
54206             if (node.kind === 75 /* Identifier */) {
54207                 if (ts.isAssignmentTarget(node)) {
54208                     var symbol = getResolvedSymbol(node);
54209                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 156 /* Parameter */) {
54210                         symbol.isAssigned = true;
54211                     }
54212                 }
54213             }
54214             else {
54215                 ts.forEachChild(node, markParameterAssignments);
54216             }
54217         }
54218         function isConstVariable(symbol) {
54219             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
54220         }
54221         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
54222         function removeOptionalityFromDeclaredType(declaredType, declaration) {
54223             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
54224                 var annotationIncludesUndefined = strictNullChecks &&
54225                     declaration.kind === 156 /* Parameter */ &&
54226                     declaration.initializer &&
54227                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
54228                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
54229                 popTypeResolution();
54230                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
54231             }
54232             else {
54233                 reportCircularityError(declaration.symbol);
54234                 return declaredType;
54235             }
54236         }
54237         function isConstraintPosition(node) {
54238             var parent = node.parent;
54239             return parent.kind === 194 /* PropertyAccessExpression */ ||
54240                 parent.kind === 196 /* CallExpression */ && parent.expression === node ||
54241                 parent.kind === 195 /* ElementAccessExpression */ && parent.expression === node ||
54242                 parent.kind === 191 /* BindingElement */ && parent.name === node && !!parent.initializer;
54243         }
54244         function typeHasNullableConstraint(type) {
54245             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
54246         }
54247         function getConstraintForLocation(type, node) {
54248             // When a node is the left hand expression of a property access, element access, or call expression,
54249             // and the type of the node includes type variables with constraints that are nullable, we fetch the
54250             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
54251             // the constraint type.
54252             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
54253                 return mapType(getWidenedType(type), getBaseConstraintOrType);
54254             }
54255             return type;
54256         }
54257         function isExportOrExportExpression(location) {
54258             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
54259         }
54260         function markAliasReferenced(symbol, location) {
54261             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
54262                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
54263                     markAliasSymbolAsReferenced(symbol);
54264                 }
54265                 else {
54266                     markConstEnumAliasAsReferenced(symbol);
54267                 }
54268             }
54269         }
54270         function checkIdentifier(node) {
54271             var symbol = getResolvedSymbol(node);
54272             if (symbol === unknownSymbol) {
54273                 return errorType;
54274             }
54275             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
54276             // Although in down-level emit of arrow function, we emit it using function expression which means that
54277             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
54278             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
54279             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
54280             // can explicitly bound arguments objects
54281             if (symbol === argumentsSymbol) {
54282                 var container = ts.getContainingFunction(node);
54283                 if (languageVersion < 2 /* ES2015 */) {
54284                     if (container.kind === 202 /* ArrowFunction */) {
54285                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
54286                     }
54287                     else if (ts.hasModifier(container, 256 /* Async */)) {
54288                         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);
54289                     }
54290                 }
54291                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
54292                 return getTypeOfSymbol(symbol);
54293             }
54294             // We should only mark aliases as referenced if there isn't a local value declaration
54295             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
54296             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
54297                 markAliasReferenced(symbol, node);
54298             }
54299             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
54300             var declaration = localOrExportSymbol.valueDeclaration;
54301             if (localOrExportSymbol.flags & 32 /* Class */) {
54302                 // Due to the emit for class decorators, any reference to the class from inside of the class body
54303                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
54304                 // behavior of class names in ES6.
54305                 if (declaration.kind === 245 /* ClassDeclaration */
54306                     && ts.nodeIsDecorated(declaration)) {
54307                     var container = ts.getContainingClass(node);
54308                     while (container !== undefined) {
54309                         if (container === declaration && container.name !== node) {
54310                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54311                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54312                             break;
54313                         }
54314                         container = ts.getContainingClass(container);
54315                     }
54316                 }
54317                 else if (declaration.kind === 214 /* ClassExpression */) {
54318                     // When we emit a class expression with static members that contain a reference
54319                     // to the constructor in the initializer, we will need to substitute that
54320                     // binding with an alias as the class name is not in scope.
54321                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54322                     while (container.kind !== 290 /* SourceFile */) {
54323                         if (container.parent === declaration) {
54324                             if (container.kind === 159 /* PropertyDeclaration */ && ts.hasModifier(container, 32 /* Static */)) {
54325                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
54326                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
54327                             }
54328                             break;
54329                         }
54330                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
54331                     }
54332                 }
54333             }
54334             checkNestedBlockScopedBinding(node, symbol);
54335             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
54336             var assignmentKind = ts.getAssignmentTargetKind(node);
54337             if (assignmentKind) {
54338                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
54339                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
54340                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
54341                     return errorType;
54342                 }
54343                 if (isReadonlySymbol(localOrExportSymbol)) {
54344                     if (localOrExportSymbol.flags & 3 /* Variable */) {
54345                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
54346                     }
54347                     else {
54348                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
54349                     }
54350                     return errorType;
54351                 }
54352             }
54353             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
54354             // We only narrow variables and parameters occurring in a non-assignment position. For all other
54355             // entities we simply return the declared type.
54356             if (localOrExportSymbol.flags & 3 /* Variable */) {
54357                 if (assignmentKind === 1 /* Definite */) {
54358                     return type;
54359                 }
54360             }
54361             else if (isAlias) {
54362                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
54363             }
54364             else {
54365                 return type;
54366             }
54367             if (!declaration) {
54368                 return type;
54369             }
54370             // The declaration container is the innermost function that encloses the declaration of the variable
54371             // or parameter. The flow container is the innermost function starting with which we analyze the control
54372             // flow graph to determine the control flow based type.
54373             var isParameter = ts.getRootDeclaration(declaration).kind === 156 /* Parameter */;
54374             var declarationContainer = getControlFlowContainer(declaration);
54375             var flowContainer = getControlFlowContainer(node);
54376             var isOuterVariable = flowContainer !== declarationContainer;
54377             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
54378             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
54379             // When the control flow originates in a function expression or arrow function and we are referencing
54380             // a const variable or parameter from an outer function, we extend the origin of the control flow
54381             // analysis to include the immediately enclosing function.
54382             while (flowContainer !== declarationContainer && (flowContainer.kind === 201 /* FunctionExpression */ ||
54383                 flowContainer.kind === 202 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
54384                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
54385                 flowContainer = getControlFlowContainer(flowContainer);
54386             }
54387             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
54388             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
54389             // declaration container are the same).
54390             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
54391                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
54392                     isInTypeQuery(node) || node.parent.kind === 263 /* ExportSpecifier */) ||
54393                 node.parent.kind === 218 /* NonNullExpression */ ||
54394                 declaration.kind === 242 /* VariableDeclaration */ && declaration.exclamationToken ||
54395                 declaration.flags & 8388608 /* Ambient */;
54396             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
54397                 type === autoType || type === autoArrayType ? undefinedType :
54398                     getOptionalType(type);
54399             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
54400             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
54401             // from declaration to use, and when the variable's declared type doesn't include undefined but the
54402             // control flow based type does include undefined.
54403             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
54404                 if (flowType === autoType || flowType === autoArrayType) {
54405                     if (noImplicitAny) {
54406                         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));
54407                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
54408                     }
54409                     return convertAutoToAny(flowType);
54410                 }
54411             }
54412             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
54413                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
54414                 // Return the declared type to reduce follow-on errors
54415                 return type;
54416             }
54417             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
54418         }
54419         function isInsideFunction(node, threshold) {
54420             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
54421         }
54422         function getPartOfForStatementContainingNode(node, container) {
54423             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
54424         }
54425         function checkNestedBlockScopedBinding(node, symbol) {
54426             if (languageVersion >= 2 /* ES2015 */ ||
54427                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
54428                 ts.isSourceFile(symbol.valueDeclaration) ||
54429                 symbol.valueDeclaration.parent.kind === 280 /* CatchClause */) {
54430                 return;
54431             }
54432             // 1. walk from the use site up to the declaration and check
54433             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
54434             // 2. walk from the declaration up to the boundary of lexical environment and check
54435             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
54436             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
54437             var usedInFunction = isInsideFunction(node.parent, container);
54438             var current = container;
54439             var containedInIterationStatement = false;
54440             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
54441                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
54442                     containedInIterationStatement = true;
54443                     break;
54444                 }
54445                 current = current.parent;
54446             }
54447             if (containedInIterationStatement) {
54448                 if (usedInFunction) {
54449                     // mark iteration statement as containing block-scoped binding captured in some function
54450                     var capturesBlockScopeBindingInLoopBody = true;
54451                     if (ts.isForStatement(container)) {
54452                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54453                         if (varDeclList && varDeclList.parent === container) {
54454                             var part = getPartOfForStatementContainingNode(node.parent, container);
54455                             if (part) {
54456                                 var links = getNodeLinks(part);
54457                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
54458                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
54459                                 ts.pushIfUnique(capturedBindings, symbol);
54460                                 if (part === container.initializer) {
54461                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
54462                                 }
54463                             }
54464                         }
54465                     }
54466                     if (capturesBlockScopeBindingInLoopBody) {
54467                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
54468                     }
54469                 }
54470                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
54471                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
54472                 if (ts.isForStatement(container)) {
54473                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 243 /* VariableDeclarationList */);
54474                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
54475                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
54476                     }
54477                 }
54478                 // set 'declared inside loop' bit on the block-scoped binding
54479                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
54480             }
54481             if (usedInFunction) {
54482                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
54483             }
54484         }
54485         function isBindingCapturedByNode(node, decl) {
54486             var links = getNodeLinks(node);
54487             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
54488         }
54489         function isAssignedInBodyOfForStatement(node, container) {
54490             // skip parenthesized nodes
54491             var current = node;
54492             while (current.parent.kind === 200 /* ParenthesizedExpression */) {
54493                 current = current.parent;
54494             }
54495             // check if node is used as LHS in some assignment expression
54496             var isAssigned = false;
54497             if (ts.isAssignmentTarget(current)) {
54498                 isAssigned = true;
54499             }
54500             else if ((current.parent.kind === 207 /* PrefixUnaryExpression */ || current.parent.kind === 208 /* PostfixUnaryExpression */)) {
54501                 var expr = current.parent;
54502                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
54503             }
54504             if (!isAssigned) {
54505                 return false;
54506             }
54507             // at this point we know that node is the target of assignment
54508             // now check that modification happens inside the statement part of the ForStatement
54509             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
54510         }
54511         function captureLexicalThis(node, container) {
54512             getNodeLinks(node).flags |= 2 /* LexicalThis */;
54513             if (container.kind === 159 /* PropertyDeclaration */ || container.kind === 162 /* Constructor */) {
54514                 var classNode = container.parent;
54515                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
54516             }
54517             else {
54518                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
54519             }
54520         }
54521         function findFirstSuperCall(n) {
54522             if (ts.isSuperCall(n)) {
54523                 return n;
54524             }
54525             else if (ts.isFunctionLike(n)) {
54526                 return undefined;
54527             }
54528             return ts.forEachChild(n, findFirstSuperCall);
54529         }
54530         /**
54531          * Return a cached result if super-statement is already found.
54532          * Otherwise, find a super statement in a given constructor function and cache the result in the node-links of the constructor
54533          *
54534          * @param constructor constructor-function to look for super statement
54535          */
54536         function getSuperCallInConstructor(constructor) {
54537             var links = getNodeLinks(constructor);
54538             // Only trying to find super-call if we haven't yet tried to find one.  Once we try, we will record the result
54539             if (links.hasSuperCall === undefined) {
54540                 links.superCall = findFirstSuperCall(constructor.body);
54541                 links.hasSuperCall = links.superCall ? true : false;
54542             }
54543             return links.superCall;
54544         }
54545         /**
54546          * Check if the given class-declaration extends null then return true.
54547          * Otherwise, return false
54548          * @param classDecl a class declaration to check if it extends null
54549          */
54550         function classDeclarationExtendsNull(classDecl) {
54551             var classSymbol = getSymbolOfNode(classDecl);
54552             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
54553             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
54554             return baseConstructorType === nullWideningType;
54555         }
54556         function checkThisBeforeSuper(node, container, diagnosticMessage) {
54557             var containingClassDecl = container.parent;
54558             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
54559             // If a containing class does not have extends clause or the class extends null
54560             // skip checking whether super statement is called before "this" accessing.
54561             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
54562                 var superCall = getSuperCallInConstructor(container);
54563                 // We should give an error in the following cases:
54564                 //      - No super-call
54565                 //      - "this" is accessing before super-call.
54566                 //          i.e super(this)
54567                 //              this.x; super();
54568                 // We want to make sure that super-call is done before accessing "this" so that
54569                 // "this" is not accessed as a parameter of the super-call.
54570                 if (!superCall || superCall.end > node.pos) {
54571                     // In ES6, super inside constructor of class-declaration has to precede "this" accessing
54572                     error(node, diagnosticMessage);
54573                 }
54574             }
54575         }
54576         function checkThisExpression(node) {
54577             // Stop at the first arrow function so that we can
54578             // tell whether 'this' needs to be captured.
54579             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
54580             var capturedByArrowFunction = false;
54581             if (container.kind === 162 /* Constructor */) {
54582                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
54583             }
54584             // Now skip arrow functions to get the "real" owner of 'this'.
54585             if (container.kind === 202 /* ArrowFunction */) {
54586                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
54587                 capturedByArrowFunction = true;
54588             }
54589             switch (container.kind) {
54590                 case 249 /* ModuleDeclaration */:
54591                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
54592                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54593                     break;
54594                 case 248 /* EnumDeclaration */:
54595                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
54596                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54597                     break;
54598                 case 162 /* Constructor */:
54599                     if (isInConstructorArgumentInitializer(node, container)) {
54600                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
54601                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54602                     }
54603                     break;
54604                 case 159 /* PropertyDeclaration */:
54605                 case 158 /* PropertySignature */:
54606                     if (ts.hasModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
54607                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
54608                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
54609                     }
54610                     break;
54611                 case 154 /* ComputedPropertyName */:
54612                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
54613                     break;
54614             }
54615             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
54616             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
54617                 captureLexicalThis(node, container);
54618             }
54619             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
54620             if (noImplicitThis) {
54621                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
54622                 if (type === globalThisType_1 && capturedByArrowFunction) {
54623                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
54624                 }
54625                 else if (!type) {
54626                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
54627                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
54628                     if (!ts.isSourceFile(container)) {
54629                         var outsideThis = tryGetThisTypeAt(container);
54630                         if (outsideThis && outsideThis !== globalThisType_1) {
54631                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
54632                         }
54633                     }
54634                 }
54635             }
54636             return type || anyType;
54637         }
54638         function tryGetThisTypeAt(node, includeGlobalThis, container) {
54639             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
54640             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
54641             var isInJS = ts.isInJSFile(node);
54642             if (ts.isFunctionLike(container) &&
54643                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
54644                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
54645                 // If this is a function in a JS file, it might be a class method.
54646                 var className = getClassNameFromPrototypeMethod(container);
54647                 if (isInJS && className) {
54648                     var classSymbol = checkExpression(className).symbol;
54649                     if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
54650                         var classType = getDeclaredTypeOfSymbol(classSymbol).thisType;
54651                         if (classType) {
54652                             return getFlowTypeOfReference(node, classType);
54653                         }
54654                     }
54655                 }
54656                 // Check if it's a constructor definition, can be either a variable decl or function decl
54657                 // i.e.
54658                 //   * /** @constructor */ function [name]() { ... }
54659                 //   * /** @constructor */ var x = function() { ... }
54660                 else if (isInJS &&
54661                     (container.kind === 201 /* FunctionExpression */ || container.kind === 244 /* FunctionDeclaration */) &&
54662                     ts.getJSDocClassTag(container)) {
54663                     var classType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
54664                     return getFlowTypeOfReference(node, classType);
54665                 }
54666                 var thisType = getThisTypeOfDeclaration(container) || getContextualThisParameterType(container);
54667                 if (thisType) {
54668                     return getFlowTypeOfReference(node, thisType);
54669                 }
54670             }
54671             if (ts.isClassLike(container.parent)) {
54672                 var symbol = getSymbolOfNode(container.parent);
54673                 var type = ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54674                 return getFlowTypeOfReference(node, type);
54675             }
54676             if (isInJS) {
54677                 var type = getTypeForThisExpressionFromJSDoc(container);
54678                 if (type && type !== errorType) {
54679                     return getFlowTypeOfReference(node, type);
54680                 }
54681             }
54682             if (ts.isSourceFile(container)) {
54683                 // look up in the source file's locals or exports
54684                 if (container.commonJsModuleIndicator) {
54685                     var fileSymbol = getSymbolOfNode(container);
54686                     return fileSymbol && getTypeOfSymbol(fileSymbol);
54687                 }
54688                 else if (includeGlobalThis) {
54689                     return getTypeOfSymbol(globalThisSymbol);
54690                 }
54691             }
54692         }
54693         function getExplicitThisType(node) {
54694             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
54695             if (ts.isFunctionLike(container)) {
54696                 var signature = getSignatureFromDeclaration(container);
54697                 if (signature.thisParameter) {
54698                     return getExplicitTypeOfSymbol(signature.thisParameter);
54699                 }
54700             }
54701             if (ts.isClassLike(container.parent)) {
54702                 var symbol = getSymbolOfNode(container.parent);
54703                 return ts.hasModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
54704             }
54705         }
54706         function getClassNameFromPrototypeMethod(container) {
54707             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
54708             if (container.kind === 201 /* FunctionExpression */ &&
54709                 ts.isBinaryExpression(container.parent) &&
54710                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
54711                 // Get the 'x' of 'x.prototype.y = container'
54712                 return container.parent // x.prototype.y = container
54713                     .left // x.prototype.y
54714                     .expression // x.prototype
54715                     .expression; // x
54716             }
54717             // x.prototype = { method() { } }
54718             else if (container.kind === 161 /* MethodDeclaration */ &&
54719                 container.parent.kind === 193 /* ObjectLiteralExpression */ &&
54720                 ts.isBinaryExpression(container.parent.parent) &&
54721                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
54722                 return container.parent.parent.left.expression;
54723             }
54724             // x.prototype = { method: function() { } }
54725             else if (container.kind === 201 /* FunctionExpression */ &&
54726                 container.parent.kind === 281 /* PropertyAssignment */ &&
54727                 container.parent.parent.kind === 193 /* ObjectLiteralExpression */ &&
54728                 ts.isBinaryExpression(container.parent.parent.parent) &&
54729                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
54730                 return container.parent.parent.parent.left.expression;
54731             }
54732             // Object.defineProperty(x, "method", { value: function() { } });
54733             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
54734             // Object.defineProperty(x, "method", { get: () => function() { }) });
54735             else if (container.kind === 201 /* FunctionExpression */ &&
54736                 ts.isPropertyAssignment(container.parent) &&
54737                 ts.isIdentifier(container.parent.name) &&
54738                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
54739                 ts.isObjectLiteralExpression(container.parent.parent) &&
54740                 ts.isCallExpression(container.parent.parent.parent) &&
54741                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
54742                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54743                 return container.parent.parent.parent.arguments[0].expression;
54744             }
54745             // Object.defineProperty(x, "method", { value() { } });
54746             // Object.defineProperty(x, "method", { set(x: () => void) {} });
54747             // Object.defineProperty(x, "method", { get() { return () => {} } });
54748             else if (ts.isMethodDeclaration(container) &&
54749                 ts.isIdentifier(container.name) &&
54750                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
54751                 ts.isObjectLiteralExpression(container.parent) &&
54752                 ts.isCallExpression(container.parent.parent) &&
54753                 container.parent.parent.arguments[2] === container.parent &&
54754                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
54755                 return container.parent.parent.arguments[0].expression;
54756             }
54757         }
54758         function getTypeForThisExpressionFromJSDoc(node) {
54759             var jsdocType = ts.getJSDocType(node);
54760             if (jsdocType && jsdocType.kind === 300 /* JSDocFunctionType */) {
54761                 var jsDocFunctionType = jsdocType;
54762                 if (jsDocFunctionType.parameters.length > 0 &&
54763                     jsDocFunctionType.parameters[0].name &&
54764                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
54765                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
54766                 }
54767             }
54768             var thisTag = ts.getJSDocThisTag(node);
54769             if (thisTag && thisTag.typeExpression) {
54770                 return getTypeFromTypeNode(thisTag.typeExpression);
54771             }
54772         }
54773         function isInConstructorArgumentInitializer(node, constructorDecl) {
54774             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 156 /* Parameter */ && n.parent === constructorDecl; });
54775         }
54776         function checkSuperExpression(node) {
54777             var isCallExpression = node.parent.kind === 196 /* CallExpression */ && node.parent.expression === node;
54778             var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
54779             var needToCaptureLexicalThis = false;
54780             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
54781             if (!isCallExpression) {
54782                 while (container && container.kind === 202 /* ArrowFunction */) {
54783                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
54784                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
54785                 }
54786             }
54787             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
54788             var nodeCheckFlag = 0;
54789             if (!canUseSuperExpression) {
54790                 // issue more specific error if super is used in computed property name
54791                 // class A { foo() { return "1" }}
54792                 // class B {
54793                 //     [super.foo()]() {}
54794                 // }
54795                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 154 /* ComputedPropertyName */; });
54796                 if (current && current.kind === 154 /* ComputedPropertyName */) {
54797                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
54798                 }
54799                 else if (isCallExpression) {
54800                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
54801                 }
54802                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */)) {
54803                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
54804                 }
54805                 else {
54806                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
54807                 }
54808                 return errorType;
54809             }
54810             if (!isCallExpression && container.kind === 162 /* Constructor */) {
54811                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
54812             }
54813             if (ts.hasModifier(container, 32 /* Static */) || isCallExpression) {
54814                 nodeCheckFlag = 512 /* SuperStatic */;
54815             }
54816             else {
54817                 nodeCheckFlag = 256 /* SuperInstance */;
54818             }
54819             getNodeLinks(node).flags |= nodeCheckFlag;
54820             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
54821             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
54822             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
54823             // uses an arrow function, which is permitted to reference `super`.
54824             //
54825             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
54826             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
54827             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
54828             //
54829             // The simplest case is reading a value, in which case we will emit something like the following:
54830             //
54831             //  // ts
54832             //  ...
54833             //  async asyncMethod() {
54834             //    let x = await super.asyncMethod();
54835             //    return x;
54836             //  }
54837             //  ...
54838             //
54839             //  // js
54840             //  ...
54841             //  asyncMethod() {
54842             //      const _super = Object.create(null, {
54843             //        asyncMethod: { get: () => super.asyncMethod },
54844             //      });
54845             //      return __awaiter(this, arguments, Promise, function *() {
54846             //          let x = yield _super.asyncMethod.call(this);
54847             //          return x;
54848             //      });
54849             //  }
54850             //  ...
54851             //
54852             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
54853             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
54854             //
54855             //  // ts
54856             //  ...
54857             //  async asyncMethod(ar: Promise<any[]>) {
54858             //      [super.a, super.b] = await ar;
54859             //  }
54860             //  ...
54861             //
54862             //  // js
54863             //  ...
54864             //  asyncMethod(ar) {
54865             //      const _super = Object.create(null, {
54866             //        a: { get: () => super.a, set: (v) => super.a = v },
54867             //        b: { get: () => super.b, set: (v) => super.b = v }
54868             //      };
54869             //      return __awaiter(this, arguments, Promise, function *() {
54870             //          [_super.a, _super.b] = yield ar;
54871             //      });
54872             //  }
54873             //  ...
54874             //
54875             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
54876             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
54877             //
54878             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
54879             if (container.kind === 161 /* MethodDeclaration */ && ts.hasModifier(container, 256 /* Async */)) {
54880                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
54881                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
54882                 }
54883                 else {
54884                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
54885                 }
54886             }
54887             if (needToCaptureLexicalThis) {
54888                 // call expressions are allowed only in constructors so they should always capture correct 'this'
54889                 // super property access expressions can also appear in arrow functions -
54890                 // in this case they should also use correct lexical this
54891                 captureLexicalThis(node.parent, container);
54892             }
54893             if (container.parent.kind === 193 /* ObjectLiteralExpression */) {
54894                 if (languageVersion < 2 /* ES2015 */) {
54895                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
54896                     return errorType;
54897                 }
54898                 else {
54899                     // for object literal assume that type of 'super' is 'any'
54900                     return anyType;
54901                 }
54902             }
54903             // at this point the only legal case for parent is ClassLikeDeclaration
54904             var classLikeDeclaration = container.parent;
54905             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
54906                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
54907                 return errorType;
54908             }
54909             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
54910             var baseClassType = classType && getBaseTypes(classType)[0];
54911             if (!baseClassType) {
54912                 return errorType;
54913             }
54914             if (container.kind === 162 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
54915                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
54916                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
54917                 return errorType;
54918             }
54919             return nodeCheckFlag === 512 /* SuperStatic */
54920                 ? getBaseConstructorTypeOfClass(classType)
54921                 : getTypeWithThisArgument(baseClassType, classType.thisType);
54922             function isLegalUsageOfSuperExpression(container) {
54923                 if (!container) {
54924                     return false;
54925                 }
54926                 if (isCallExpression) {
54927                     // TS 1.0 SPEC (April 2014): 4.8.1
54928                     // Super calls are only permitted in constructors of derived classes
54929                     return container.kind === 162 /* Constructor */;
54930                 }
54931                 else {
54932                     // TS 1.0 SPEC (April 2014)
54933                     // 'super' property access is allowed
54934                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
54935                     // - In a static member function or static member accessor
54936                     // topmost container must be something that is directly nested in the class declaration\object literal expression
54937                     if (ts.isClassLike(container.parent) || container.parent.kind === 193 /* ObjectLiteralExpression */) {
54938                         if (ts.hasModifier(container, 32 /* Static */)) {
54939                             return container.kind === 161 /* MethodDeclaration */ ||
54940                                 container.kind === 160 /* MethodSignature */ ||
54941                                 container.kind === 163 /* GetAccessor */ ||
54942                                 container.kind === 164 /* SetAccessor */;
54943                         }
54944                         else {
54945                             return container.kind === 161 /* MethodDeclaration */ ||
54946                                 container.kind === 160 /* MethodSignature */ ||
54947                                 container.kind === 163 /* GetAccessor */ ||
54948                                 container.kind === 164 /* SetAccessor */ ||
54949                                 container.kind === 159 /* PropertyDeclaration */ ||
54950                                 container.kind === 158 /* PropertySignature */ ||
54951                                 container.kind === 162 /* Constructor */;
54952                         }
54953                     }
54954                 }
54955                 return false;
54956             }
54957         }
54958         function getContainingObjectLiteral(func) {
54959             return (func.kind === 161 /* MethodDeclaration */ ||
54960                 func.kind === 163 /* GetAccessor */ ||
54961                 func.kind === 164 /* SetAccessor */) && func.parent.kind === 193 /* ObjectLiteralExpression */ ? func.parent :
54962                 func.kind === 201 /* FunctionExpression */ && func.parent.kind === 281 /* PropertyAssignment */ ? func.parent.parent :
54963                     undefined;
54964         }
54965         function getThisTypeArgument(type) {
54966             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
54967         }
54968         function getThisTypeFromContextualType(type) {
54969             return mapType(type, function (t) {
54970                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
54971             });
54972         }
54973         function getContextualThisParameterType(func) {
54974             if (func.kind === 202 /* ArrowFunction */) {
54975                 return undefined;
54976             }
54977             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
54978                 var contextualSignature = getContextualSignature(func);
54979                 if (contextualSignature) {
54980                     var thisParameter = contextualSignature.thisParameter;
54981                     if (thisParameter) {
54982                         return getTypeOfSymbol(thisParameter);
54983                     }
54984                 }
54985             }
54986             var inJs = ts.isInJSFile(func);
54987             if (noImplicitThis || inJs) {
54988                 var containingLiteral = getContainingObjectLiteral(func);
54989                 if (containingLiteral) {
54990                     // We have an object literal method. Check if the containing object literal has a contextual type
54991                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
54992                     // any directly enclosing object literals.
54993                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
54994                     var literal = containingLiteral;
54995                     var type = contextualType;
54996                     while (type) {
54997                         var thisType = getThisTypeFromContextualType(type);
54998                         if (thisType) {
54999                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
55000                         }
55001                         if (literal.parent.kind !== 281 /* PropertyAssignment */) {
55002                             break;
55003                         }
55004                         literal = literal.parent.parent;
55005                         type = getApparentTypeOfContextualType(literal);
55006                     }
55007                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
55008                     // for 'this' is the non-null form of the contextual type for the containing object literal or
55009                     // the type of the object literal itself.
55010                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
55011                 }
55012                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
55013                 // contextual type for 'this' is 'obj'.
55014                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
55015                 if (parent.kind === 209 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
55016                     var target = parent.left;
55017                     if (ts.isAccessExpression(target)) {
55018                         var expression = target.expression;
55019                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
55020                         if (inJs && ts.isIdentifier(expression)) {
55021                             var sourceFile = ts.getSourceFileOfNode(parent);
55022                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
55023                                 return undefined;
55024                             }
55025                         }
55026                         return getWidenedType(checkExpressionCached(expression));
55027                     }
55028                 }
55029             }
55030             return undefined;
55031         }
55032         // Return contextual type of parameter or undefined if no contextual type is available
55033         function getContextuallyTypedParameterType(parameter) {
55034             var func = parameter.parent;
55035             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
55036                 return undefined;
55037             }
55038             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
55039             if (iife && iife.arguments) {
55040                 var args = getEffectiveCallArguments(iife);
55041                 var indexOfParameter = func.parameters.indexOf(parameter);
55042                 if (parameter.dotDotDotToken) {
55043                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined);
55044                 }
55045                 var links = getNodeLinks(iife);
55046                 var cached = links.resolvedSignature;
55047                 links.resolvedSignature = anySignature;
55048                 var type = indexOfParameter < args.length ?
55049                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
55050                     parameter.initializer ? undefined : undefinedWideningType;
55051                 links.resolvedSignature = cached;
55052                 return type;
55053             }
55054             var contextualSignature = getContextualSignature(func);
55055             if (contextualSignature) {
55056                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
55057                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
55058                     getRestTypeAtPosition(contextualSignature, index) :
55059                     tryGetTypeAtPosition(contextualSignature, index);
55060             }
55061         }
55062         function getContextualTypeForVariableLikeDeclaration(declaration) {
55063             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
55064             if (typeNode) {
55065                 return getTypeFromTypeNode(typeNode);
55066             }
55067             switch (declaration.kind) {
55068                 case 156 /* Parameter */:
55069                     return getContextuallyTypedParameterType(declaration);
55070                 case 191 /* BindingElement */:
55071                     return getContextualTypeForBindingElement(declaration);
55072                 // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent
55073             }
55074         }
55075         function getContextualTypeForBindingElement(declaration) {
55076             var parent = declaration.parent.parent;
55077             var name = declaration.propertyName || declaration.name;
55078             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
55079                 parent.kind !== 191 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
55080             if (parentType && !ts.isBindingPattern(name) && !ts.isComputedNonLiteralName(name)) {
55081                 var nameType = getLiteralTypeFromPropertyName(name);
55082                 if (isTypeUsableAsPropertyName(nameType)) {
55083                     var text = getPropertyNameFromType(nameType);
55084                     return getTypeOfPropertyOfType(parentType, text);
55085                 }
55086             }
55087         }
55088         // In a variable, parameter or property declaration with a type annotation,
55089         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
55090         // Otherwise, in a parameter declaration of a contextually typed function expression,
55091         //   the contextual type of an initializer expression is the contextual type of the parameter.
55092         // Otherwise, in a variable or parameter declaration with a binding pattern name,
55093         //   the contextual type of an initializer expression is the type implied by the binding pattern.
55094         // Otherwise, in a binding pattern inside a variable or parameter declaration,
55095         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
55096         function getContextualTypeForInitializerExpression(node) {
55097             var declaration = node.parent;
55098             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
55099                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
55100                 if (result) {
55101                     return result;
55102                 }
55103                 if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
55104                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
55105                 }
55106             }
55107             return undefined;
55108         }
55109         function getContextualTypeForReturnExpression(node) {
55110             var func = ts.getContainingFunction(node);
55111             if (func) {
55112                 var functionFlags = ts.getFunctionFlags(func);
55113                 if (functionFlags & 1 /* Generator */) { // AsyncGenerator function or Generator function
55114                     return undefined;
55115                 }
55116                 var contextualReturnType = getContextualReturnType(func);
55117                 if (contextualReturnType) {
55118                     if (functionFlags & 2 /* Async */) { // Async function
55119                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeOfPromise);
55120                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55121                     }
55122                     return contextualReturnType; // Regular function
55123                 }
55124             }
55125             return undefined;
55126         }
55127         function getContextualTypeForAwaitOperand(node) {
55128             var contextualType = getContextualType(node);
55129             if (contextualType) {
55130                 var contextualAwaitedType = getAwaitedType(contextualType);
55131                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
55132             }
55133             return undefined;
55134         }
55135         function getContextualTypeForYieldOperand(node) {
55136             var func = ts.getContainingFunction(node);
55137             if (func) {
55138                 var functionFlags = ts.getFunctionFlags(func);
55139                 var contextualReturnType = getContextualReturnType(func);
55140                 if (contextualReturnType) {
55141                     return node.asteriskToken
55142                         ? contextualReturnType
55143                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
55144                 }
55145             }
55146             return undefined;
55147         }
55148         function isInParameterInitializerBeforeContainingFunction(node) {
55149             var inBindingInitializer = false;
55150             while (node.parent && !ts.isFunctionLike(node.parent)) {
55151                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
55152                     return true;
55153                 }
55154                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
55155                     inBindingInitializer = true;
55156                 }
55157                 node = node.parent;
55158             }
55159             return false;
55160         }
55161         function getContextualIterationType(kind, functionDecl) {
55162             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
55163             var contextualReturnType = getContextualReturnType(functionDecl);
55164             if (contextualReturnType) {
55165                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
55166                     || undefined;
55167             }
55168             return undefined;
55169         }
55170         function getContextualReturnType(functionDecl) {
55171             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
55172             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
55173             var returnType = getReturnTypeFromAnnotation(functionDecl);
55174             if (returnType) {
55175                 return returnType;
55176             }
55177             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
55178             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
55179             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
55180             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
55181                 return getReturnTypeOfSignature(signature);
55182             }
55183             return undefined;
55184         }
55185         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
55186         function getContextualTypeForArgument(callTarget, arg) {
55187             var args = getEffectiveCallArguments(callTarget);
55188             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
55189             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
55190         }
55191         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
55192             // If we're already in the process of resolving the given signature, don't resolve again as
55193             // that could cause infinite recursion. Instead, return anySignature.
55194             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
55195             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
55196                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
55197             }
55198             return getTypeAtPosition(signature, argIndex);
55199         }
55200         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
55201             if (template.parent.kind === 198 /* TaggedTemplateExpression */) {
55202                 return getContextualTypeForArgument(template.parent, substitutionExpression);
55203             }
55204             return undefined;
55205         }
55206         function getContextualTypeForBinaryOperand(node, contextFlags) {
55207             var binaryExpression = node.parent;
55208             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
55209             switch (operatorToken.kind) {
55210                 case 62 /* EqualsToken */:
55211                     if (node !== right) {
55212                         return undefined;
55213                     }
55214                     var contextSensitive = getIsContextSensitiveAssignmentOrContextType(binaryExpression);
55215                     if (!contextSensitive) {
55216                         return undefined;
55217                     }
55218                     return contextSensitive === true ? getTypeOfExpression(left) : contextSensitive;
55219                 case 56 /* BarBarToken */:
55220                 case 60 /* QuestionQuestionToken */:
55221                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
55222                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
55223                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
55224                     // by the type of the left operand, except for the special case of Javascript declarations of the form
55225                     // `namespace.prop = namespace.prop || {}`.
55226                     var type = getContextualType(binaryExpression, contextFlags);
55227                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
55228                         getTypeOfExpression(left) : type;
55229                 case 55 /* AmpersandAmpersandToken */:
55230                 case 27 /* CommaToken */:
55231                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
55232                 default:
55233                     return undefined;
55234             }
55235         }
55236         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
55237         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
55238         function getIsContextSensitiveAssignmentOrContextType(binaryExpression) {
55239             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
55240             switch (kind) {
55241                 case 0 /* None */:
55242                     return true;
55243                 case 5 /* Property */:
55244                 case 1 /* ExportsProperty */:
55245                 case 6 /* Prototype */:
55246                 case 3 /* PrototypeProperty */:
55247                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
55248                     // See `bindStaticPropertyAssignment` in `binder.ts`.
55249                     if (!binaryExpression.left.symbol) {
55250                         return true;
55251                     }
55252                     else {
55253                         var decl = binaryExpression.left.symbol.valueDeclaration;
55254                         if (!decl) {
55255                             return false;
55256                         }
55257                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
55258                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
55259                         if (overallAnnotation) {
55260                             return getTypeFromTypeNode(overallAnnotation);
55261                         }
55262                         else if (ts.isIdentifier(lhs.expression)) {
55263                             var id = lhs.expression;
55264                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
55265                             if (parentSymbol) {
55266                                 var annotated = ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
55267                                 if (annotated) {
55268                                     var nameStr_1 = ts.getElementOrPropertyAccessName(lhs);
55269                                     if (nameStr_1 !== undefined) {
55270                                         var type = getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr_1);
55271                                         return type || false;
55272                                     }
55273                                 }
55274                                 return false;
55275                             }
55276                         }
55277                         return !ts.isInJSFile(decl);
55278                     }
55279                 case 2 /* ModuleExports */:
55280                 case 4 /* ThisProperty */:
55281                     if (!binaryExpression.symbol)
55282                         return true;
55283                     if (binaryExpression.symbol.valueDeclaration) {
55284                         var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
55285                         if (annotated) {
55286                             var type = getTypeFromTypeNode(annotated);
55287                             if (type) {
55288                                 return type;
55289                             }
55290                         }
55291                     }
55292                     if (kind === 2 /* ModuleExports */)
55293                         return false;
55294                     var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
55295                     if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
55296                         return false;
55297                     }
55298                     var thisType = checkThisExpression(thisAccess.expression);
55299                     var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
55300                     return nameStr !== undefined && thisType && getTypeOfPropertyOfContextualType(thisType, nameStr) || false;
55301                 case 7 /* ObjectDefinePropertyValue */:
55302                 case 8 /* ObjectDefinePropertyExports */:
55303                 case 9 /* ObjectDefinePrototypeProperty */:
55304                     return ts.Debug.fail("Does not apply");
55305                 default:
55306                     return ts.Debug.assertNever(kind);
55307             }
55308         }
55309         function isCircularMappedProperty(symbol) {
55310             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
55311         }
55312         function getTypeOfPropertyOfContextualType(type, name) {
55313             return mapType(type, function (t) {
55314                 if (isGenericMappedType(t)) {
55315                     var constraint = getConstraintTypeFromMappedType(t);
55316                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
55317                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
55318                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
55319                         return substituteIndexedMappedType(t, propertyNameType);
55320                     }
55321                 }
55322                 else if (t.flags & 3670016 /* StructuredType */) {
55323                     var prop = getPropertyOfType(t, name);
55324                     if (prop) {
55325                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
55326                     }
55327                     if (isTupleType(t)) {
55328                         var restType = getRestTypeOfTupleType(t);
55329                         if (restType && isNumericLiteralName(name) && +name >= 0) {
55330                             return restType;
55331                         }
55332                     }
55333                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
55334                         getIndexTypeOfContextualType(t, 0 /* String */);
55335                 }
55336                 return undefined;
55337             }, /*noReductions*/ true);
55338         }
55339         function getIndexTypeOfContextualType(type, kind) {
55340             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
55341         }
55342         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
55343         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
55344         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
55345         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
55346             ts.Debug.assert(ts.isObjectLiteralMethod(node));
55347             if (node.flags & 16777216 /* InWithStatement */) {
55348                 // We cannot answer semantic questions within a with block, do not proceed any further
55349                 return undefined;
55350             }
55351             return getContextualTypeForObjectLiteralElement(node, contextFlags);
55352         }
55353         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
55354             var objectLiteral = element.parent;
55355             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
55356             if (type) {
55357                 if (!hasNonBindableDynamicName(element)) {
55358                     // For a (non-symbol) computed property, there is no reason to look up the name
55359                     // in the type. It will just be "__computed", which does not appear in any
55360                     // SymbolTable.
55361                     var symbolName_3 = getSymbolOfNode(element).escapedName;
55362                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
55363                     if (propertyType) {
55364                         return propertyType;
55365                     }
55366                 }
55367                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
55368                     getIndexTypeOfContextualType(type, 0 /* String */);
55369             }
55370             return undefined;
55371         }
55372         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
55373         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
55374         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
55375         // type of T.
55376         function getContextualTypeForElementExpression(arrayContextualType, index) {
55377             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
55378                 || getIteratedTypeOrElementType(1 /* Element */, arrayContextualType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false));
55379         }
55380         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
55381         function getContextualTypeForConditionalOperand(node, contextFlags) {
55382             var conditional = node.parent;
55383             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
55384         }
55385         function getContextualTypeForChildJsxExpression(node, child) {
55386             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
55387             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
55388             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
55389             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
55390                 return undefined;
55391             }
55392             var realChildren = getSemanticJsxChildren(node.children);
55393             var childIndex = realChildren.indexOf(child);
55394             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
55395             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
55396                 if (isArrayLikeType(t)) {
55397                     return getIndexedAccessType(t, getLiteralType(childIndex));
55398                 }
55399                 else {
55400                     return t;
55401                 }
55402             }, /*noReductions*/ true));
55403         }
55404         function getContextualTypeForJsxExpression(node) {
55405             var exprParent = node.parent;
55406             return ts.isJsxAttributeLike(exprParent)
55407                 ? getContextualType(node)
55408                 : ts.isJsxElement(exprParent)
55409                     ? getContextualTypeForChildJsxExpression(exprParent, node)
55410                     : undefined;
55411         }
55412         function getContextualTypeForJsxAttribute(attribute) {
55413             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
55414             // which is a type of the parameter of the signature we are trying out.
55415             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
55416             if (ts.isJsxAttribute(attribute)) {
55417                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
55418                 if (!attributesType || isTypeAny(attributesType)) {
55419                     return undefined;
55420                 }
55421                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
55422             }
55423             else {
55424                 return getContextualType(attribute.parent);
55425             }
55426         }
55427         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
55428         // expressions we check to those that don't depend on their contextual type in order not to cause
55429         // recursive (and possibly infinite) invocations of getContextualType.
55430         function isPossiblyDiscriminantValue(node) {
55431             switch (node.kind) {
55432                 case 10 /* StringLiteral */:
55433                 case 8 /* NumericLiteral */:
55434                 case 9 /* BigIntLiteral */:
55435                 case 14 /* NoSubstitutionTemplateLiteral */:
55436                 case 106 /* TrueKeyword */:
55437                 case 91 /* FalseKeyword */:
55438                 case 100 /* NullKeyword */:
55439                 case 75 /* Identifier */:
55440                 case 146 /* UndefinedKeyword */:
55441                     return true;
55442                 case 194 /* PropertyAccessExpression */:
55443                 case 200 /* ParenthesizedExpression */:
55444                     return isPossiblyDiscriminantValue(node.expression);
55445                 case 276 /* JsxExpression */:
55446                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
55447             }
55448             return false;
55449         }
55450         function discriminateContextualTypeByObjectMembers(node, contextualType) {
55451             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 281 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
55452         }
55453         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
55454             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 273 /* 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);
55455         }
55456         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
55457         // be "pushed" onto a node using the contextualType property.
55458         function getApparentTypeOfContextualType(node, contextFlags) {
55459             var contextualType = ts.isObjectLiteralMethod(node) ?
55460                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
55461                 getContextualType(node, contextFlags);
55462             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
55463             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
55464                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
55465                 if (apparentType.flags & 1048576 /* Union */) {
55466                     if (ts.isObjectLiteralExpression(node)) {
55467                         return discriminateContextualTypeByObjectMembers(node, apparentType);
55468                     }
55469                     else if (ts.isJsxAttributes(node)) {
55470                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
55471                     }
55472                 }
55473                 return apparentType;
55474             }
55475         }
55476         // If the given contextual type contains instantiable types and if a mapper representing
55477         // return type inferences is available, instantiate those types using that mapper.
55478         function instantiateContextualType(contextualType, node, contextFlags) {
55479             if (contextualType && maybeTypeOfKind(contextualType, 63176704 /* Instantiable */)) {
55480                 var inferenceContext = getInferenceContext(node);
55481                 // If no inferences have been made, nothing is gained from instantiating as type parameters
55482                 // would just be replaced with their defaults similar to the apparent type.
55483                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
55484                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
55485                     // types as well as arguments to the left in a function call.
55486                     if (contextFlags && contextFlags & 1 /* Signature */) {
55487                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
55488                     }
55489                     // For other purposes (e.g. determining whether to produce literal types) we only
55490                     // incorporate inferences made from the return type in a function call.
55491                     if (inferenceContext.returnMapper) {
55492                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
55493                     }
55494                 }
55495             }
55496             return contextualType;
55497         }
55498         // This function is similar to instantiateType, except that (a) it only instantiates types that
55499         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
55500         // no reductions on instantiated union types.
55501         function instantiateInstantiableTypes(type, mapper) {
55502             if (type.flags & 63176704 /* Instantiable */) {
55503                 return instantiateType(type, mapper);
55504             }
55505             if (type.flags & 1048576 /* Union */) {
55506                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
55507             }
55508             if (type.flags & 2097152 /* Intersection */) {
55509                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
55510             }
55511             return type;
55512         }
55513         /**
55514          * Whoa! Do you really want to use this function?
55515          *
55516          * Unless you're trying to get the *non-apparent* type for a
55517          * value-literal type or you're authoring relevant portions of this algorithm,
55518          * you probably meant to use 'getApparentTypeOfContextualType'.
55519          * Otherwise this may not be very useful.
55520          *
55521          * In cases where you *are* working on this function, you should understand
55522          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
55523          *
55524          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
55525          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
55526          *
55527          * @param node the expression whose contextual type will be returned.
55528          * @returns the contextual type of an expression.
55529          */
55530         function getContextualType(node, contextFlags) {
55531             if (node.flags & 16777216 /* InWithStatement */) {
55532                 // We cannot answer semantic questions within a with block, do not proceed any further
55533                 return undefined;
55534             }
55535             if (node.contextualType) {
55536                 return node.contextualType;
55537             }
55538             var parent = node.parent;
55539             switch (parent.kind) {
55540                 case 242 /* VariableDeclaration */:
55541                 case 156 /* Parameter */:
55542                 case 159 /* PropertyDeclaration */:
55543                 case 158 /* PropertySignature */:
55544                 case 191 /* BindingElement */:
55545                     return getContextualTypeForInitializerExpression(node);
55546                 case 202 /* ArrowFunction */:
55547                 case 235 /* ReturnStatement */:
55548                     return getContextualTypeForReturnExpression(node);
55549                 case 212 /* YieldExpression */:
55550                     return getContextualTypeForYieldOperand(parent);
55551                 case 206 /* AwaitExpression */:
55552                     return getContextualTypeForAwaitOperand(parent);
55553                 case 196 /* CallExpression */:
55554                     if (parent.expression.kind === 96 /* ImportKeyword */) {
55555                         return stringType;
55556                     }
55557                 /* falls through */
55558                 case 197 /* NewExpression */:
55559                     return getContextualTypeForArgument(parent, node);
55560                 case 199 /* TypeAssertionExpression */:
55561                 case 217 /* AsExpression */:
55562                     return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type);
55563                 case 209 /* BinaryExpression */:
55564                     return getContextualTypeForBinaryOperand(node, contextFlags);
55565                 case 281 /* PropertyAssignment */:
55566                 case 282 /* ShorthandPropertyAssignment */:
55567                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
55568                 case 283 /* SpreadAssignment */:
55569                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
55570                 case 192 /* ArrayLiteralExpression */: {
55571                     var arrayLiteral = parent;
55572                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
55573                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
55574                 }
55575                 case 210 /* ConditionalExpression */:
55576                     return getContextualTypeForConditionalOperand(node, contextFlags);
55577                 case 221 /* TemplateSpan */:
55578                     ts.Debug.assert(parent.parent.kind === 211 /* TemplateExpression */);
55579                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
55580                 case 200 /* ParenthesizedExpression */: {
55581                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
55582                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
55583                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
55584                 }
55585                 case 276 /* JsxExpression */:
55586                     return getContextualTypeForJsxExpression(parent);
55587                 case 273 /* JsxAttribute */:
55588                 case 275 /* JsxSpreadAttribute */:
55589                     return getContextualTypeForJsxAttribute(parent);
55590                 case 268 /* JsxOpeningElement */:
55591                 case 267 /* JsxSelfClosingElement */:
55592                     return getContextualJsxElementAttributesType(parent, contextFlags);
55593             }
55594             return undefined;
55595         }
55596         function getInferenceContext(node) {
55597             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
55598             return ancestor && ancestor.inferenceContext;
55599         }
55600         function getContextualJsxElementAttributesType(node, contextFlags) {
55601             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
55602                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
55603                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
55604                 // (as below) instead!
55605                 return node.parent.contextualType;
55606             }
55607             return getContextualTypeForArgumentAtIndex(node, 0);
55608         }
55609         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
55610             return getJsxReferenceKind(node) !== 0 /* Component */
55611                 ? getJsxPropsTypeFromCallSignature(signature, node)
55612                 : getJsxPropsTypeFromClassType(signature, node);
55613         }
55614         function getJsxPropsTypeFromCallSignature(sig, context) {
55615             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
55616             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
55617             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55618             if (intrinsicAttribs !== errorType) {
55619                 propsType = intersectTypes(intrinsicAttribs, propsType);
55620             }
55621             return propsType;
55622         }
55623         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
55624             if (sig.unionSignatures) {
55625                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
55626                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
55627                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
55628                 // 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.
55629                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
55630                 var results = [];
55631                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
55632                     var signature = _a[_i];
55633                     var instance = getReturnTypeOfSignature(signature);
55634                     if (isTypeAny(instance)) {
55635                         return instance;
55636                     }
55637                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
55638                     if (!propType) {
55639                         return;
55640                     }
55641                     results.push(propType);
55642                 }
55643                 return getIntersectionType(results);
55644             }
55645             var instanceType = getReturnTypeOfSignature(sig);
55646             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
55647         }
55648         function getStaticTypeOfReferencedJsxConstructor(context) {
55649             if (isJsxIntrinsicIdentifier(context.tagName)) {
55650                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
55651                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55652                 return getOrCreateTypeFromSignature(fakeSignature);
55653             }
55654             var tagType = checkExpressionCached(context.tagName);
55655             if (tagType.flags & 128 /* StringLiteral */) {
55656                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
55657                 if (!result) {
55658                     return errorType;
55659                 }
55660                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
55661                 return getOrCreateTypeFromSignature(fakeSignature);
55662             }
55663             return tagType;
55664         }
55665         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
55666             var managedSym = getJsxLibraryManagedAttributes(ns);
55667             if (managedSym) {
55668                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
55669                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
55670                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
55671                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
55672                     return createTypeReference(declaredManagedType, args);
55673                 }
55674                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
55675                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
55676                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
55677                 }
55678             }
55679             return attributesType;
55680         }
55681         function getJsxPropsTypeFromClassType(sig, context) {
55682             var ns = getJsxNamespaceAt(context);
55683             var forcedLookupLocation = getJsxElementPropertiesName(ns);
55684             var attributesType = forcedLookupLocation === undefined
55685                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
55686                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
55687                 : forcedLookupLocation === ""
55688                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
55689                     ? getReturnTypeOfSignature(sig)
55690                     // Otherwise get the type of the property on the signature return type
55691                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
55692             if (!attributesType) {
55693                 // There is no property named 'props' on this instance type
55694                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
55695                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
55696                 }
55697                 return unknownType;
55698             }
55699             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
55700             if (isTypeAny(attributesType)) {
55701                 // Props is of type 'any' or unknown
55702                 return attributesType;
55703             }
55704             else {
55705                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
55706                 var apparentAttributesType = attributesType;
55707                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
55708                 if (intrinsicClassAttribs !== errorType) {
55709                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
55710                     var hostClassType = getReturnTypeOfSignature(sig);
55711                     apparentAttributesType = intersectTypes(typeParams
55712                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
55713                         : intrinsicClassAttribs, apparentAttributesType);
55714                 }
55715                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
55716                 if (intrinsicAttribs !== errorType) {
55717                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
55718                 }
55719                 return apparentAttributesType;
55720             }
55721         }
55722         // If the given type is an object or union type with a single signature, and if that signature has at
55723         // least as many parameters as the given function, return the signature. Otherwise return undefined.
55724         function getContextualCallSignature(type, node) {
55725             var signatures = getSignaturesOfType(type, 0 /* Call */);
55726             if (signatures.length === 1) {
55727                 var signature = signatures[0];
55728                 if (!isAritySmaller(signature, node)) {
55729                     return signature;
55730                 }
55731             }
55732         }
55733         /** If the contextual signature has fewer parameters than the function expression, do not use it */
55734         function isAritySmaller(signature, target) {
55735             var targetParameterCount = 0;
55736             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
55737                 var param = target.parameters[targetParameterCount];
55738                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
55739                     break;
55740                 }
55741             }
55742             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
55743                 targetParameterCount--;
55744             }
55745             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
55746         }
55747         function isFunctionExpressionOrArrowFunction(node) {
55748             return node.kind === 201 /* FunctionExpression */ || node.kind === 202 /* ArrowFunction */;
55749         }
55750         function getContextualSignatureForFunctionLikeDeclaration(node) {
55751             // Only function expressions, arrow functions, and object literal methods are contextually typed.
55752             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
55753                 ? getContextualSignature(node)
55754                 : undefined;
55755         }
55756         // Return the contextual signature for a given expression node. A contextual type provides a
55757         // contextual signature if it has a single call signature and if that call signature is non-generic.
55758         // If the contextual type is a union type, get the signature from each type possible and if they are
55759         // all identical ignoring their return type, the result is same signature but with return type as
55760         // union type of return types from these signatures
55761         function getContextualSignature(node) {
55762             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
55763             var typeTagSignature = getSignatureOfTypeTag(node);
55764             if (typeTagSignature) {
55765                 return typeTagSignature;
55766             }
55767             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
55768             if (!type) {
55769                 return undefined;
55770             }
55771             if (!(type.flags & 1048576 /* Union */)) {
55772                 return getContextualCallSignature(type, node);
55773             }
55774             var signatureList;
55775             var types = type.types;
55776             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
55777                 var current = types_17[_i];
55778                 var signature = getContextualCallSignature(current, node);
55779                 if (signature) {
55780                     if (!signatureList) {
55781                         // This signature will contribute to contextual union signature
55782                         signatureList = [signature];
55783                     }
55784                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
55785                         // Signatures aren't identical, do not use
55786                         return undefined;
55787                     }
55788                     else {
55789                         // Use this signature for contextual union signature
55790                         signatureList.push(signature);
55791                     }
55792                 }
55793             }
55794             // Result is union of signatures collected (return type is union of return types of this signature set)
55795             if (signatureList) {
55796                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
55797             }
55798         }
55799         function checkSpreadExpression(node, checkMode) {
55800             if (languageVersion < 2 /* ES2015 */) {
55801                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
55802             }
55803             var arrayOrIterableType = checkExpression(node.expression, checkMode);
55804             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
55805         }
55806         function hasDefaultValue(node) {
55807             return (node.kind === 191 /* BindingElement */ && !!node.initializer) ||
55808                 (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
55809         }
55810         function checkArrayLiteral(node, checkMode, forceTuple) {
55811             var elements = node.elements;
55812             var elementCount = elements.length;
55813             var elementTypes = [];
55814             var hasEndingSpreadElement = false;
55815             var hasNonEndingSpreadElement = false;
55816             var contextualType = getApparentTypeOfContextualType(node);
55817             var inDestructuringPattern = ts.isAssignmentTarget(node);
55818             var inConstContext = isConstContext(node);
55819             for (var i = 0; i < elementCount; i++) {
55820                 var e = elements[i];
55821                 var spread = e.kind === 213 /* SpreadElement */ && e.expression;
55822                 var spreadType = spread && checkExpression(spread, checkMode, forceTuple);
55823                 if (spreadType && isTupleType(spreadType)) {
55824                     elementTypes.push.apply(elementTypes, getTypeArguments(spreadType));
55825                     if (spreadType.target.hasRestElement) {
55826                         if (i === elementCount - 1)
55827                             hasEndingSpreadElement = true;
55828                         else
55829                             hasNonEndingSpreadElement = true;
55830                     }
55831                 }
55832                 else {
55833                     if (inDestructuringPattern && spreadType) {
55834                         // Given the following situation:
55835                         //    var c: {};
55836                         //    [...c] = ["", 0];
55837                         //
55838                         // c is represented in the tree as a spread element in an array literal.
55839                         // But c really functions as a rest element, and its purpose is to provide
55840                         // a contextual type for the right hand side of the assignment. Therefore,
55841                         // instead of calling checkExpression on "...c", which will give an error
55842                         // if c is not iterable/array-like, we need to act as if we are trying to
55843                         // get the contextual element type from it. So we do something similar to
55844                         // getContextualTypeForElementExpression, which will crucially not error
55845                         // if there is no index type / iterated type.
55846                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
55847                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false);
55848                         if (restElementType) {
55849                             elementTypes.push(restElementType);
55850                         }
55851                     }
55852                     else {
55853                         var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
55854                         var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
55855                         elementTypes.push(type);
55856                     }
55857                     if (spread) { // tuples are done above, so these are only arrays
55858                         if (i === elementCount - 1)
55859                             hasEndingSpreadElement = true;
55860                         else
55861                             hasNonEndingSpreadElement = true;
55862                     }
55863                 }
55864             }
55865             if (!hasNonEndingSpreadElement) {
55866                 var minLength = elementTypes.length - (hasEndingSpreadElement ? 1 : 0);
55867                 // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
55868                 // that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
55869                 var tupleResult = void 0;
55870                 if (inDestructuringPattern && minLength > 0) {
55871                     var type = cloneTypeReference(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55872                     type.pattern = node;
55873                     return type;
55874                 }
55875                 else if (tupleResult = getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasEndingSpreadElement, elementTypes.length, inConstContext)) {
55876                     return createArrayLiteralType(tupleResult);
55877                 }
55878                 else if (forceTuple) {
55879                     return createArrayLiteralType(createTupleType(elementTypes, minLength, hasEndingSpreadElement));
55880                 }
55881             }
55882             return createArrayLiteralType(createArrayType(elementTypes.length ?
55883                 getUnionType(elementTypes, 2 /* Subtype */) :
55884                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
55885         }
55886         function createArrayLiteralType(type) {
55887             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
55888                 return type;
55889             }
55890             var literalType = type.literalType;
55891             if (!literalType) {
55892                 literalType = type.literalType = cloneTypeReference(type);
55893                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
55894             }
55895             return literalType;
55896         }
55897         function getArrayLiteralTupleTypeIfApplicable(elementTypes, contextualType, hasRestElement, elementCount, readonly) {
55898             if (elementCount === void 0) { elementCount = elementTypes.length; }
55899             if (readonly === void 0) { readonly = false; }
55900             // Infer a tuple type when the contextual type is or contains a tuple-like type
55901             if (readonly || (contextualType && forEachType(contextualType, isTupleLikeType))) {
55902                 return createTupleType(elementTypes, elementCount - (hasRestElement ? 1 : 0), hasRestElement, readonly);
55903             }
55904         }
55905         function isNumericName(name) {
55906             switch (name.kind) {
55907                 case 154 /* ComputedPropertyName */:
55908                     return isNumericComputedName(name);
55909                 case 75 /* Identifier */:
55910                     return isNumericLiteralName(name.escapedText);
55911                 case 8 /* NumericLiteral */:
55912                 case 10 /* StringLiteral */:
55913                     return isNumericLiteralName(name.text);
55914                 default:
55915                     return false;
55916             }
55917         }
55918         function isNumericComputedName(name) {
55919             // It seems odd to consider an expression of type Any to result in a numeric name,
55920             // but this behavior is consistent with checkIndexedAccess
55921             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
55922         }
55923         function isInfinityOrNaNString(name) {
55924             return name === "Infinity" || name === "-Infinity" || name === "NaN";
55925         }
55926         function isNumericLiteralName(name) {
55927             // The intent of numeric names is that
55928             //     - they are names with text in a numeric form, and that
55929             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
55930             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
55931             //
55932             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
55933             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
55934             //
55935             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
55936             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
55937             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
55938             // because their 'ToString' representation is not equal to their original text.
55939             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
55940             //
55941             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
55942             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
55943             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
55944             //
55945             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
55946             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
55947             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
55948             return (+name).toString() === name;
55949         }
55950         function checkComputedPropertyName(node) {
55951             var links = getNodeLinks(node.expression);
55952             if (!links.resolvedType) {
55953                 links.resolvedType = checkExpression(node.expression);
55954                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
55955                 // type, and any union of these types (like string | number).
55956                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
55957                     !isTypeAssignableToKind(links.resolvedType, 132 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
55958                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
55959                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
55960                 }
55961                 else {
55962                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
55963                 }
55964             }
55965             return links.resolvedType;
55966         }
55967         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
55968             var propTypes = [];
55969             for (var i = 0; i < properties.length; i++) {
55970                 if (kind === 0 /* String */ || isNumericName(node.properties[i + offset].name)) {
55971                     propTypes.push(getTypeOfSymbol(properties[i]));
55972                 }
55973             }
55974             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
55975             return createIndexInfo(unionType, isConstContext(node));
55976         }
55977         function getImmediateAliasedSymbol(symbol) {
55978             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
55979             var links = getSymbolLinks(symbol);
55980             if (!links.immediateTarget) {
55981                 var node = getDeclarationOfAliasSymbol(symbol);
55982                 if (!node)
55983                     return ts.Debug.fail();
55984                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
55985             }
55986             return links.immediateTarget;
55987         }
55988         function checkObjectLiteral(node, checkMode) {
55989             var inDestructuringPattern = ts.isAssignmentTarget(node);
55990             // Grammar checking
55991             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
55992             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
55993             var propertiesTable = ts.createSymbolTable();
55994             var propertiesArray = [];
55995             var spread = emptyObjectType;
55996             var contextualType = getApparentTypeOfContextualType(node);
55997             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
55998                 (contextualType.pattern.kind === 189 /* ObjectBindingPattern */ || contextualType.pattern.kind === 193 /* ObjectLiteralExpression */);
55999             var inConstContext = isConstContext(node);
56000             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
56001             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
56002             var enumTag = ts.getJSDocEnumTag(node);
56003             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
56004             var objectFlags = freshObjectLiteralFlag;
56005             var patternWithComputedProperties = false;
56006             var hasComputedStringProperty = false;
56007             var hasComputedNumberProperty = false;
56008             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
56009             // As otherwise they may not be checked until exports for the type at this position are retrieved,
56010             // which may never occur.
56011             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
56012                 var elem = _a[_i];
56013                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
56014                     checkComputedPropertyName(elem.name);
56015                 }
56016             }
56017             var offset = 0;
56018             for (var i = 0; i < node.properties.length; i++) {
56019                 var memberDecl = node.properties[i];
56020                 var member = getSymbolOfNode(memberDecl);
56021                 var computedNameType = memberDecl.name && memberDecl.name.kind === 154 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
56022                     checkComputedPropertyName(memberDecl.name) : undefined;
56023                 if (memberDecl.kind === 281 /* PropertyAssignment */ ||
56024                     memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ||
56025                     ts.isObjectLiteralMethod(memberDecl)) {
56026                     var type = memberDecl.kind === 281 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
56027                         memberDecl.kind === 282 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(memberDecl.name, checkMode) :
56028                             checkObjectLiteralMethod(memberDecl, checkMode);
56029                     if (isInJavascript) {
56030                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
56031                         if (jsDocType) {
56032                             checkTypeAssignableTo(type, jsDocType, memberDecl);
56033                             type = jsDocType;
56034                         }
56035                         else if (enumTag && enumTag.typeExpression) {
56036                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
56037                         }
56038                     }
56039                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
56040                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
56041                     var prop = nameType ?
56042                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
56043                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
56044                     if (nameType) {
56045                         prop.nameType = nameType;
56046                     }
56047                     if (inDestructuringPattern) {
56048                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
56049                         // for the property, make the property optional.
56050                         var isOptional = (memberDecl.kind === 281 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
56051                             (memberDecl.kind === 282 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
56052                         if (isOptional) {
56053                             prop.flags |= 16777216 /* Optional */;
56054                         }
56055                     }
56056                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
56057                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
56058                         // binding pattern specifies a default value for the property, make the property optional.
56059                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
56060                         if (impliedProp) {
56061                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
56062                         }
56063                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
56064                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
56065                         }
56066                     }
56067                     prop.declarations = member.declarations;
56068                     prop.parent = member.parent;
56069                     if (member.valueDeclaration) {
56070                         prop.valueDeclaration = member.valueDeclaration;
56071                     }
56072                     prop.type = type;
56073                     prop.target = member;
56074                     member = prop;
56075                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
56076                 }
56077                 else if (memberDecl.kind === 283 /* SpreadAssignment */) {
56078                     if (languageVersion < 2 /* ES2015 */) {
56079                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
56080                     }
56081                     if (propertiesArray.length > 0) {
56082                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56083                         propertiesArray = [];
56084                         propertiesTable = ts.createSymbolTable();
56085                         hasComputedStringProperty = false;
56086                         hasComputedNumberProperty = false;
56087                     }
56088                     var type = getReducedType(checkExpression(memberDecl.expression));
56089                     if (!isValidSpreadType(type)) {
56090                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
56091                         return errorType;
56092                     }
56093                     if (allPropertiesTable) {
56094                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
56095                     }
56096                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
56097                     offset = i + 1;
56098                     continue;
56099                 }
56100                 else {
56101                     // TypeScript 1.0 spec (April 2014)
56102                     // A get accessor declaration is processed in the same manner as
56103                     // an ordinary function declaration(section 6.1) with no parameters.
56104                     // A set accessor declaration is processed in the same manner
56105                     // as an ordinary function declaration with a single parameter and a Void return type.
56106                     ts.Debug.assert(memberDecl.kind === 163 /* GetAccessor */ || memberDecl.kind === 164 /* SetAccessor */);
56107                     checkNodeDeferred(memberDecl);
56108                 }
56109                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
56110                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
56111                         if (isTypeAssignableTo(computedNameType, numberType)) {
56112                             hasComputedNumberProperty = true;
56113                         }
56114                         else {
56115                             hasComputedStringProperty = true;
56116                         }
56117                         if (inDestructuringPattern) {
56118                             patternWithComputedProperties = true;
56119                         }
56120                     }
56121                 }
56122                 else {
56123                     propertiesTable.set(member.escapedName, member);
56124                 }
56125                 propertiesArray.push(member);
56126             }
56127             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
56128             // type with those properties for which the binding pattern specifies a default value.
56129             // If the object literal is spread into another object literal, skip this step and let the top-level object
56130             // literal handle it instead.
56131             if (contextualTypeHasPattern && node.parent.kind !== 283 /* SpreadAssignment */) {
56132                 for (var _b = 0, _c = getPropertiesOfType(contextualType); _b < _c.length; _b++) {
56133                     var prop = _c[_b];
56134                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
56135                         if (!(prop.flags & 16777216 /* Optional */)) {
56136                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
56137                         }
56138                         propertiesTable.set(prop.escapedName, prop);
56139                         propertiesArray.push(prop);
56140                     }
56141                 }
56142             }
56143             if (spread !== emptyObjectType) {
56144                 if (propertiesArray.length > 0) {
56145                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
56146                     propertiesArray = [];
56147                     propertiesTable = ts.createSymbolTable();
56148                     hasComputedStringProperty = false;
56149                     hasComputedNumberProperty = false;
56150                 }
56151                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
56152                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
56153             }
56154             return createObjectLiteralType();
56155             function createObjectLiteralType() {
56156                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
56157                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
56158                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
56159                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56160                 if (isJSObjectLiteral) {
56161                     result.objectFlags |= 16384 /* JSLiteral */;
56162                 }
56163                 if (patternWithComputedProperties) {
56164                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
56165                 }
56166                 if (inDestructuringPattern) {
56167                     result.pattern = node;
56168                 }
56169                 return result;
56170             }
56171         }
56172         function isValidSpreadType(type) {
56173             if (type.flags & 63176704 /* Instantiable */) {
56174                 var constraint = getBaseConstraintOfType(type);
56175                 if (constraint !== undefined) {
56176                     return isValidSpreadType(constraint);
56177                 }
56178             }
56179             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
56180                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
56181                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
56182         }
56183         function checkJsxSelfClosingElementDeferred(node) {
56184             checkJsxOpeningLikeElementOrOpeningFragment(node);
56185             resolveUntypedCall(node); // ensure type arguments and parameters are typechecked, even if there is an arity error
56186         }
56187         function checkJsxSelfClosingElement(node, _checkMode) {
56188             checkNodeDeferred(node);
56189             return getJsxElementTypeAt(node) || anyType;
56190         }
56191         function checkJsxElementDeferred(node) {
56192             // Check attributes
56193             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
56194             // Perform resolution on the closing tag so that rename/go to definition/etc work
56195             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
56196                 getIntrinsicTagSymbol(node.closingElement);
56197             }
56198             else {
56199                 checkExpression(node.closingElement.tagName);
56200             }
56201             checkJsxChildren(node);
56202         }
56203         function checkJsxElement(node, _checkMode) {
56204             checkNodeDeferred(node);
56205             return getJsxElementTypeAt(node) || anyType;
56206         }
56207         function checkJsxFragment(node) {
56208             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
56209             if (compilerOptions.jsx === 2 /* React */ && (compilerOptions.jsxFactory || ts.getSourceFileOfNode(node).pragmas.has("jsx"))) {
56210                 error(node, compilerOptions.jsxFactory
56211                     ? ts.Diagnostics.JSX_fragment_is_not_supported_when_using_jsxFactory
56212                     : ts.Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma);
56213             }
56214             checkJsxChildren(node);
56215             return getJsxElementTypeAt(node) || anyType;
56216         }
56217         /**
56218          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
56219          */
56220         function isUnhyphenatedJsxName(name) {
56221             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
56222             return !ts.stringContains(name, "-");
56223         }
56224         /**
56225          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
56226          */
56227         function isJsxIntrinsicIdentifier(tagName) {
56228             return tagName.kind === 75 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
56229         }
56230         function checkJsxAttribute(node, checkMode) {
56231             return node.initializer
56232                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
56233                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
56234         }
56235         /**
56236          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
56237          *
56238          * @param openingLikeElement a JSX opening-like element
56239          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
56240          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
56241          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
56242          * which also calls getSpreadType.
56243          */
56244         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
56245             var attributes = openingLikeElement.attributes;
56246             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
56247             var attributesTable = ts.createSymbolTable();
56248             var spread = emptyJsxObjectType;
56249             var hasSpreadAnyType = false;
56250             var typeToIntersect;
56251             var explicitlySpecifyChildrenAttribute = false;
56252             var objectFlags = 4096 /* JsxAttributes */;
56253             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
56254             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
56255                 var attributeDecl = _a[_i];
56256                 var member = attributeDecl.symbol;
56257                 if (ts.isJsxAttribute(attributeDecl)) {
56258                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
56259                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
56260                     var attributeSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */ | member.flags, member.escapedName);
56261                     attributeSymbol.declarations = member.declarations;
56262                     attributeSymbol.parent = member.parent;
56263                     if (member.valueDeclaration) {
56264                         attributeSymbol.valueDeclaration = member.valueDeclaration;
56265                     }
56266                     attributeSymbol.type = exprType;
56267                     attributeSymbol.target = member;
56268                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56269                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
56270                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
56271                         explicitlySpecifyChildrenAttribute = true;
56272                     }
56273                 }
56274                 else {
56275                     ts.Debug.assert(attributeDecl.kind === 275 /* JsxSpreadAttribute */);
56276                     if (attributesTable.size > 0) {
56277                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56278                         attributesTable = ts.createSymbolTable();
56279                     }
56280                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
56281                     if (isTypeAny(exprType)) {
56282                         hasSpreadAnyType = true;
56283                     }
56284                     if (isValidSpreadType(exprType)) {
56285                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
56286                         if (allAttributesTable) {
56287                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
56288                         }
56289                     }
56290                     else {
56291                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
56292                     }
56293                 }
56294             }
56295             if (!hasSpreadAnyType) {
56296                 if (attributesTable.size > 0) {
56297                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
56298                 }
56299             }
56300             // Handle children attribute
56301             var parent = openingLikeElement.parent.kind === 266 /* JsxElement */ ? openingLikeElement.parent : undefined;
56302             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
56303             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
56304                 var childrenTypes = checkJsxChildren(parent, checkMode);
56305                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
56306                     // Error if there is a attribute named "children" explicitly specified and children element.
56307                     // This is because children element will overwrite the value from attributes.
56308                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
56309                     if (explicitlySpecifyChildrenAttribute) {
56310                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
56311                     }
56312                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
56313                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
56314                     // 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
56315                     var childrenPropSymbol = createSymbol(4 /* Property */ | 33554432 /* Transient */, jsxChildrenPropertyName);
56316                     childrenPropSymbol.type = childrenTypes.length === 1 ?
56317                         childrenTypes[0] :
56318                         (getArrayLiteralTupleTypeIfApplicable(childrenTypes, childrenContextualType, /*hasRestElement*/ false) || createArrayType(getUnionType(childrenTypes)));
56319                     // Fake up a property declaration for the children
56320                     childrenPropSymbol.valueDeclaration = ts.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined);
56321                     childrenPropSymbol.valueDeclaration.parent = attributes;
56322                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
56323                     var childPropMap = ts.createSymbolTable();
56324                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
56325                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
56326                 }
56327             }
56328             if (hasSpreadAnyType) {
56329                 return anyType;
56330             }
56331             if (typeToIntersect && spread !== emptyJsxObjectType) {
56332                 return getIntersectionType([typeToIntersect, spread]);
56333             }
56334             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
56335             /**
56336              * Create anonymous type from given attributes symbol table.
56337              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
56338              * @param attributesTable a symbol table of attributes property
56339              */
56340             function createJsxAttributesType() {
56341                 objectFlags |= freshObjectLiteralFlag;
56342                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
56343                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56344                 return result;
56345             }
56346         }
56347         function checkJsxChildren(node, checkMode) {
56348             var childrenTypes = [];
56349             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
56350                 var child = _a[_i];
56351                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
56352                 // because then type of children property will have constituent of string type.
56353                 if (child.kind === 11 /* JsxText */) {
56354                     if (!child.containsOnlyTriviaWhiteSpaces) {
56355                         childrenTypes.push(stringType);
56356                     }
56357                 }
56358                 else {
56359                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
56360                 }
56361             }
56362             return childrenTypes;
56363         }
56364         function checkSpreadPropOverrides(type, props, spread) {
56365             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56366                 var right = _a[_i];
56367                 var left = props.get(right.escapedName);
56368                 var rightType = getTypeOfSymbol(right);
56369                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
56370                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
56371                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
56372                 }
56373             }
56374         }
56375         /**
56376          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
56377          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
56378          * @param node a JSXAttributes to be resolved of its type
56379          */
56380         function checkJsxAttributes(node, checkMode) {
56381             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
56382         }
56383         function getJsxType(name, location) {
56384             var namespace = getJsxNamespaceAt(location);
56385             var exports = namespace && getExportsOfSymbol(namespace);
56386             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
56387             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
56388         }
56389         /**
56390          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
56391          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
56392          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
56393          * May also return unknownSymbol if both of these lookups fail.
56394          */
56395         function getIntrinsicTagSymbol(node) {
56396             var links = getNodeLinks(node);
56397             if (!links.resolvedSymbol) {
56398                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
56399                 if (intrinsicElementsType !== errorType) {
56400                     // Property case
56401                     if (!ts.isIdentifier(node.tagName))
56402                         return ts.Debug.fail();
56403                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
56404                     if (intrinsicProp) {
56405                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
56406                         return links.resolvedSymbol = intrinsicProp;
56407                     }
56408                     // Intrinsic string indexer case
56409                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56410                     if (indexSignatureType) {
56411                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
56412                         return links.resolvedSymbol = intrinsicElementsType.symbol;
56413                     }
56414                     // Wasn't found
56415                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
56416                     return links.resolvedSymbol = unknownSymbol;
56417                 }
56418                 else {
56419                     if (noImplicitAny) {
56420                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
56421                     }
56422                     return links.resolvedSymbol = unknownSymbol;
56423                 }
56424             }
56425             return links.resolvedSymbol;
56426         }
56427         function getJsxNamespaceAt(location) {
56428             var links = location && getNodeLinks(location);
56429             if (links && links.jsxNamespace) {
56430                 return links.jsxNamespace;
56431             }
56432             if (!links || links.jsxNamespace !== false) {
56433                 var namespaceName = getJsxNamespace(location);
56434                 var resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
56435                 if (resolvedNamespace) {
56436                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
56437                     if (candidate) {
56438                         if (links) {
56439                             links.jsxNamespace = candidate;
56440                         }
56441                         return candidate;
56442                     }
56443                     if (links) {
56444                         links.jsxNamespace = false;
56445                     }
56446                 }
56447             }
56448             // JSX global fallback
56449             return getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined); // TODO: GH#18217
56450         }
56451         /**
56452          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
56453          * Get a single property from that container if existed. Report an error if there are more than one property.
56454          *
56455          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
56456          *          if other string is given or the container doesn't exist, return undefined.
56457          */
56458         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
56459             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
56460             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
56461             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
56462             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
56463             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
56464             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
56465             if (propertiesOfJsxElementAttribPropInterface) {
56466                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
56467                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
56468                     return "";
56469                 }
56470                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
56471                 // property of the class instance type
56472                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
56473                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
56474                 }
56475                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
56476                     // More than one property on ElementAttributesProperty is an error
56477                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
56478                 }
56479             }
56480             return undefined;
56481         }
56482         function getJsxLibraryManagedAttributes(jsxNamespace) {
56483             // JSX.LibraryManagedAttributes [symbol]
56484             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
56485         }
56486         /// e.g. "props" for React.d.ts,
56487         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
56488         ///     non-intrinsic elements' attributes type is 'any'),
56489         /// or '' if it has 0 properties (which means every
56490         ///     non-intrinsic elements' attributes type is the element instance type)
56491         function getJsxElementPropertiesName(jsxNamespace) {
56492             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
56493         }
56494         function getJsxElementChildrenPropertyName(jsxNamespace) {
56495             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
56496         }
56497         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
56498             if (elementType.flags & 4 /* String */) {
56499                 return [anySignature];
56500             }
56501             else if (elementType.flags & 128 /* StringLiteral */) {
56502                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
56503                 if (!intrinsicType) {
56504                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
56505                     return ts.emptyArray;
56506                 }
56507                 else {
56508                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
56509                     return [fakeSignature];
56510                 }
56511             }
56512             var apparentElemType = getApparentType(elementType);
56513             // Resolve the signatures, preferring constructor
56514             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
56515             if (signatures.length === 0) {
56516                 // No construct signatures, try call signatures
56517                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
56518             }
56519             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
56520                 // If each member has some combination of new/call signatures; make a union signature list for those
56521                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
56522             }
56523             return signatures;
56524         }
56525         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
56526             // 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
56527             // For example:
56528             //      var CustomTag: "h1" = "h1";
56529             //      <CustomTag> Hello World </CustomTag>
56530             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
56531             if (intrinsicElementsType !== errorType) {
56532                 var stringLiteralTypeName = type.value;
56533                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
56534                 if (intrinsicProp) {
56535                     return getTypeOfSymbol(intrinsicProp);
56536                 }
56537                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
56538                 if (indexSignatureType) {
56539                     return indexSignatureType;
56540                 }
56541                 return undefined;
56542             }
56543             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
56544             return anyType;
56545         }
56546         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
56547             if (refKind === 1 /* Function */) {
56548                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56549                 if (sfcReturnConstraint) {
56550                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56551                 }
56552             }
56553             else if (refKind === 0 /* Component */) {
56554                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56555                 if (classConstraint) {
56556                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
56557                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56558                 }
56559             }
56560             else { // Mixed
56561                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
56562                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
56563                 if (!sfcReturnConstraint || !classConstraint) {
56564                     return;
56565                 }
56566                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
56567                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
56568             }
56569             function generateInitialErrorChain() {
56570                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
56571                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
56572             }
56573         }
56574         /**
56575          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
56576          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
56577          * @param node an intrinsic JSX opening-like element
56578          */
56579         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
56580             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
56581             var links = getNodeLinks(node);
56582             if (!links.resolvedJsxElementAttributesType) {
56583                 var symbol = getIntrinsicTagSymbol(node);
56584                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
56585                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
56586                 }
56587                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
56588                     return links.resolvedJsxElementAttributesType =
56589                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
56590                 }
56591                 else {
56592                     return links.resolvedJsxElementAttributesType = errorType;
56593                 }
56594             }
56595             return links.resolvedJsxElementAttributesType;
56596         }
56597         function getJsxElementClassTypeAt(location) {
56598             var type = getJsxType(JsxNames.ElementClass, location);
56599             if (type === errorType)
56600                 return undefined;
56601             return type;
56602         }
56603         function getJsxElementTypeAt(location) {
56604             return getJsxType(JsxNames.Element, location);
56605         }
56606         function getJsxStatelessElementTypeAt(location) {
56607             var jsxElementType = getJsxElementTypeAt(location);
56608             if (jsxElementType) {
56609                 return getUnionType([jsxElementType, nullType]);
56610             }
56611         }
56612         /**
56613          * Returns all the properties of the Jsx.IntrinsicElements interface
56614          */
56615         function getJsxIntrinsicTagNamesAt(location) {
56616             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
56617             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
56618         }
56619         function checkJsxPreconditions(errorNode) {
56620             // Preconditions for using JSX
56621             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
56622                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
56623             }
56624             if (getJsxElementTypeAt(errorNode) === undefined) {
56625                 if (noImplicitAny) {
56626                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
56627                 }
56628             }
56629         }
56630         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
56631             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
56632             if (isNodeOpeningLikeElement) {
56633                 checkGrammarJsxElement(node);
56634             }
56635             checkJsxPreconditions(node);
56636             // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
56637             // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
56638             var reactRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
56639             var reactNamespace = getJsxNamespace(node);
56640             var reactLocation = isNodeOpeningLikeElement ? node.tagName : node;
56641             var reactSym = resolveName(reactLocation, reactNamespace, 111551 /* Value */, reactRefErr, reactNamespace, /*isUse*/ true);
56642             if (reactSym) {
56643                 // Mark local symbol as referenced here because it might not have been marked
56644                 // if jsx emit was not react as there wont be error being emitted
56645                 reactSym.isReferenced = 67108863 /* All */;
56646                 // If react symbol is alias, mark it as refereced
56647                 if (reactSym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(reactSym)) {
56648                     markAliasSymbolAsReferenced(reactSym);
56649                 }
56650             }
56651             if (isNodeOpeningLikeElement) {
56652                 var jsxOpeningLikeNode = node;
56653                 var sig = getResolvedSignature(jsxOpeningLikeNode);
56654                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
56655             }
56656         }
56657         /**
56658          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
56659          * is considered known if
56660          * 1. the object type is empty and the check is for assignability, or
56661          * 2. if the object type has index signatures, or
56662          * 3. if the property is actually declared in the object type
56663          *    (this means that 'toString', for example, is not usually a known property).
56664          * 4. In a union or intersection type,
56665          *    a property is considered known if it is known in any constituent type.
56666          * @param targetType a type to search a given name in
56667          * @param name a property name to search
56668          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
56669          */
56670         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
56671             if (targetType.flags & 524288 /* Object */) {
56672                 var resolved = resolveStructuredTypeMembers(targetType);
56673                 if (resolved.stringIndexInfo ||
56674                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
56675                     getPropertyOfObjectType(targetType, name) ||
56676                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
56677                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
56678                     return true;
56679                 }
56680             }
56681             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
56682                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
56683                     var t = _a[_i];
56684                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
56685                         return true;
56686                     }
56687                 }
56688             }
56689             return false;
56690         }
56691         function isExcessPropertyCheckTarget(type) {
56692             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
56693                 type.flags & 67108864 /* NonPrimitive */ ||
56694                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
56695                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
56696         }
56697         function checkJsxExpression(node, checkMode) {
56698             checkGrammarJsxExpression(node);
56699             if (node.expression) {
56700                 var type = checkExpression(node.expression, checkMode);
56701                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
56702                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
56703                 }
56704                 return type;
56705             }
56706             else {
56707                 return errorType;
56708             }
56709         }
56710         function getDeclarationNodeFlagsFromSymbol(s) {
56711             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
56712         }
56713         /**
56714          * Return whether this symbol is a member of a prototype somewhere
56715          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
56716          */
56717         function isPrototypeProperty(symbol) {
56718             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
56719                 return true;
56720             }
56721             if (ts.isInJSFile(symbol.valueDeclaration)) {
56722                 var parent = symbol.valueDeclaration.parent;
56723                 return parent && ts.isBinaryExpression(parent) &&
56724                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
56725             }
56726         }
56727         /**
56728          * Check whether the requested property access is valid.
56729          * Returns true if node is a valid property access, and false otherwise.
56730          * @param node The node to be checked.
56731          * @param isSuper True if the access is from `super.`.
56732          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
56733          * @param prop The symbol for the property being accessed.
56734          */
56735         function checkPropertyAccessibility(node, isSuper, type, prop) {
56736             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
56737             var errorNode = node.kind === 153 /* QualifiedName */ ? node.right : node.kind === 188 /* ImportType */ ? node : node.name;
56738             if (isSuper) {
56739                 // TS 1.0 spec (April 2014): 4.8.2
56740                 // - In a constructor, instance member function, instance member accessor, or
56741                 //   instance member variable initializer where this references a derived class instance,
56742                 //   a super property access is permitted and must specify a public instance member function of the base class.
56743                 // - In a static member function or static member accessor
56744                 //   where this references the constructor function object of a derived class,
56745                 //   a super property access is permitted and must specify a public static member function of the base class.
56746                 if (languageVersion < 2 /* ES2015 */) {
56747                     if (symbolHasNonMethodDeclaration(prop)) {
56748                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
56749                         return false;
56750                     }
56751                 }
56752                 if (flags & 128 /* Abstract */) {
56753                     // A method cannot be accessed in a super property access if the method is abstract.
56754                     // This error could mask a private property access error. But, a member
56755                     // cannot simultaneously be private and abstract, so this will trigger an
56756                     // additional error elsewhere.
56757                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56758                     return false;
56759                 }
56760             }
56761             // Referencing abstract properties within their own constructors is not allowed
56762             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
56763                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56764                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
56765                     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
56766                     return false;
56767                 }
56768             }
56769             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
56770                 if (!ts.getContainingClass(node)) {
56771                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56772                     return false;
56773                 }
56774                 return true;
56775             }
56776             // Public properties are otherwise accessible.
56777             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
56778                 return true;
56779             }
56780             // Property is known to be private or protected at this point
56781             // Private property is accessible if the property is within the declaring class
56782             if (flags & 8 /* Private */) {
56783                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
56784                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
56785                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
56786                     return false;
56787                 }
56788                 return true;
56789             }
56790             // Property is known to be protected at this point
56791             // All protected properties of a supertype are accessible in a super access
56792             if (isSuper) {
56793                 return true;
56794             }
56795             // Find the first enclosing class that has the declaring classes of the protected constituents
56796             // of the property as base classes
56797             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
56798                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
56799                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
56800             });
56801             // A protected property is accessible if the property is within the declaring class or classes derived from it
56802             if (!enclosingClass) {
56803                 // allow PropertyAccessibility if context is in function with this parameter
56804                 // static member access is disallow
56805                 var thisParameter = void 0;
56806                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
56807                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
56808                     return false;
56809                 }
56810                 var thisType = getTypeFromTypeNode(thisParameter.type);
56811                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
56812             }
56813             // No further restrictions for static properties
56814             if (flags & 32 /* Static */) {
56815                 return true;
56816             }
56817             if (type.flags & 262144 /* TypeParameter */) {
56818                 // get the original type -- represented as the type constraint of the 'this' type
56819                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
56820             }
56821             if (!type || !hasBaseType(type, enclosingClass)) {
56822                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
56823                 return false;
56824             }
56825             return true;
56826         }
56827         function getThisParameterFromNodeContext(node) {
56828             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
56829             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
56830         }
56831         function symbolHasNonMethodDeclaration(symbol) {
56832             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
56833         }
56834         function checkNonNullExpression(node) {
56835             return checkNonNullType(checkExpression(node), node);
56836         }
56837         function isNullableType(type) {
56838             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
56839         }
56840         function getNonNullableTypeIfNeeded(type) {
56841             return isNullableType(type) ? getNonNullableType(type) : type;
56842         }
56843         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
56844             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56845                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
56846                 ts.Diagnostics.Object_is_possibly_undefined :
56847                 ts.Diagnostics.Object_is_possibly_null);
56848         }
56849         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
56850             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
56851                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
56852                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
56853                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
56854         }
56855         function checkNonNullTypeWithReporter(type, node, reportError) {
56856             if (strictNullChecks && type.flags & 2 /* Unknown */) {
56857                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
56858                 return errorType;
56859             }
56860             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
56861             if (kind) {
56862                 reportError(node, kind);
56863                 var t = getNonNullableType(type);
56864                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
56865             }
56866             return type;
56867         }
56868         function checkNonNullType(type, node) {
56869             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
56870         }
56871         function checkNonNullNonVoidType(type, node) {
56872             var nonNullType = checkNonNullType(type, node);
56873             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
56874                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
56875             }
56876             return nonNullType;
56877         }
56878         function checkPropertyAccessExpression(node) {
56879             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
56880                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
56881         }
56882         function checkPropertyAccessChain(node) {
56883             var leftType = checkExpression(node.expression);
56884             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
56885             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
56886         }
56887         function checkQualifiedName(node) {
56888             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
56889         }
56890         function isMethodAccessForCall(node) {
56891             while (node.parent.kind === 200 /* ParenthesizedExpression */) {
56892                 node = node.parent;
56893             }
56894             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
56895         }
56896         // Lookup the private identifier lexically.
56897         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
56898             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
56899                 var symbol = containingClass.symbol;
56900                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
56901                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
56902                 if (prop) {
56903                     return prop;
56904                 }
56905             }
56906         }
56907         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
56908             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
56909         }
56910         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
56911             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
56912             // Find a private identifier with the same description on the type.
56913             var propertyOnType;
56914             var properties = getPropertiesOfType(leftType);
56915             if (properties) {
56916                 ts.forEach(properties, function (symbol) {
56917                     var decl = symbol.valueDeclaration;
56918                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
56919                         propertyOnType = symbol;
56920                         return true;
56921                     }
56922                 });
56923             }
56924             var diagName = diagnosticName(right);
56925             if (propertyOnType) {
56926                 var typeValueDecl = propertyOnType.valueDeclaration;
56927                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
56928                 ts.Debug.assert(!!typeClass_1);
56929                 // We found a private identifier property with the same description.
56930                 // Either:
56931                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
56932                 // - It is an attempt to access the private identifier outside of the class.
56933                 if (lexicallyScopedIdentifier) {
56934                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
56935                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
56936                     ts.Debug.assert(!!lexicalClass);
56937                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
56938                         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));
56939                         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));
56940                         return true;
56941                     }
56942                 }
56943                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
56944                 return true;
56945             }
56946             return false;
56947         }
56948         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
56949             var parentSymbol = getNodeLinks(left).resolvedSymbol;
56950             var assignmentKind = ts.getAssignmentTargetKind(node);
56951             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
56952             if (ts.isPrivateIdentifier(right)) {
56953                 checkExternalEmitHelpers(node, 262144 /* ClassPrivateFieldGet */);
56954             }
56955             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
56956             var prop;
56957             if (ts.isPrivateIdentifier(right)) {
56958                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
56959                 if (isAnyLike) {
56960                     if (lexicallyScopedSymbol) {
56961                         return apparentType;
56962                     }
56963                     if (!ts.getContainingClass(right)) {
56964                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
56965                         return anyType;
56966                     }
56967                 }
56968                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
56969                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
56970                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
56971                     return errorType;
56972                 }
56973             }
56974             else {
56975                 if (isAnyLike) {
56976                     if (ts.isIdentifier(left) && parentSymbol) {
56977                         markAliasReferenced(parentSymbol, node);
56978                     }
56979                     return apparentType;
56980                 }
56981                 prop = getPropertyOfType(apparentType, right.escapedText);
56982             }
56983             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
56984                 markAliasReferenced(parentSymbol, node);
56985             }
56986             var propType;
56987             if (!prop) {
56988                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
56989                 if (!(indexInfo && indexInfo.type)) {
56990                     if (isJSLiteralType(leftType)) {
56991                         return anyType;
56992                     }
56993                     if (leftType.symbol === globalThisSymbol) {
56994                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
56995                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
56996                         }
56997                         else if (noImplicitAny) {
56998                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
56999                         }
57000                         return anyType;
57001                     }
57002                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
57003                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
57004                     }
57005                     return errorType;
57006                 }
57007                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
57008                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
57009                 }
57010                 propType = indexInfo.type;
57011             }
57012             else {
57013                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
57014                 markPropertyAsReferenced(prop, node, left.kind === 104 /* ThisKeyword */);
57015                 getNodeLinks(node).resolvedSymbol = prop;
57016                 checkPropertyAccessibility(node, left.kind === 102 /* SuperKeyword */, apparentType, prop);
57017                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
57018                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
57019                     return errorType;
57020                 }
57021                 propType = getConstraintForLocation(getTypeOfSymbol(prop), node);
57022             }
57023             return getFlowTypeOfAccessExpression(node, prop, propType, right);
57024         }
57025         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
57026             // Only compute control flow type if this is a property access expression that isn't an
57027             // assignment target, and the referenced property was declared as a variable, property,
57028             // accessor, or optional method.
57029             var assignmentKind = ts.getAssignmentTargetKind(node);
57030             if (!ts.isAccessExpression(node) ||
57031                 assignmentKind === 1 /* Definite */ ||
57032                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
57033                 return propType;
57034             }
57035             // If strict null checks and strict property initialization checks are enabled, if we have
57036             // a this.xxx property access, if the property is an instance property without an initializer,
57037             // and if we are in a constructor of the same class as the property declaration, assume that
57038             // the property is uninitialized at the top of the control flow.
57039             var assumeUninitialized = false;
57040             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 104 /* ThisKeyword */) {
57041                 var declaration = prop && prop.valueDeclaration;
57042                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
57043                     var flowContainer = getControlFlowContainer(node);
57044                     if (flowContainer.kind === 162 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
57045                         assumeUninitialized = true;
57046                     }
57047                 }
57048             }
57049             else if (strictNullChecks && prop && prop.valueDeclaration &&
57050                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
57051                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
57052                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
57053                 assumeUninitialized = true;
57054             }
57055             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
57056             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
57057                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
57058                 // Return the declared type to reduce follow-on errors
57059                 return propType;
57060             }
57061             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
57062         }
57063         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
57064             var valueDeclaration = prop.valueDeclaration;
57065             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
57066                 return;
57067             }
57068             var diagnosticMessage;
57069             var declarationName = ts.idText(right);
57070             if (isInPropertyInitializer(node)
57071                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
57072                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
57073                 && !isPropertyDeclaredInAncestorClass(prop)) {
57074                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
57075             }
57076             else if (valueDeclaration.kind === 245 /* ClassDeclaration */ &&
57077                 node.parent.kind !== 169 /* TypeReference */ &&
57078                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
57079                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
57080                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
57081             }
57082             if (diagnosticMessage) {
57083                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
57084             }
57085         }
57086         function isInPropertyInitializer(node) {
57087             return !!ts.findAncestor(node, function (node) {
57088                 switch (node.kind) {
57089                     case 159 /* PropertyDeclaration */:
57090                         return true;
57091                     case 281 /* PropertyAssignment */:
57092                     case 161 /* MethodDeclaration */:
57093                     case 163 /* GetAccessor */:
57094                     case 164 /* SetAccessor */:
57095                     case 283 /* SpreadAssignment */:
57096                     case 154 /* ComputedPropertyName */:
57097                     case 221 /* TemplateSpan */:
57098                     case 276 /* JsxExpression */:
57099                     case 273 /* JsxAttribute */:
57100                     case 274 /* JsxAttributes */:
57101                     case 275 /* JsxSpreadAttribute */:
57102                     case 268 /* JsxOpeningElement */:
57103                     case 216 /* ExpressionWithTypeArguments */:
57104                     case 279 /* HeritageClause */:
57105                         return false;
57106                     default:
57107                         return ts.isExpressionNode(node) ? false : "quit";
57108                 }
57109             });
57110         }
57111         /**
57112          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
57113          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
57114          */
57115         function isPropertyDeclaredInAncestorClass(prop) {
57116             if (!(prop.parent.flags & 32 /* Class */)) {
57117                 return false;
57118             }
57119             var classType = getTypeOfSymbol(prop.parent);
57120             while (true) {
57121                 classType = classType.symbol && getSuperClass(classType);
57122                 if (!classType) {
57123                     return false;
57124                 }
57125                 var superProperty = getPropertyOfType(classType, prop.escapedName);
57126                 if (superProperty && superProperty.valueDeclaration) {
57127                     return true;
57128                 }
57129             }
57130         }
57131         function getSuperClass(classType) {
57132             var x = getBaseTypes(classType);
57133             if (x.length === 0) {
57134                 return undefined;
57135             }
57136             return getIntersectionType(x);
57137         }
57138         function reportNonexistentProperty(propNode, containingType) {
57139             var errorInfo;
57140             var relatedInfo;
57141             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
57142                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
57143                     var subtype = _a[_i];
57144                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
57145                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
57146                         break;
57147                     }
57148                 }
57149             }
57150             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
57151                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57152             }
57153             else {
57154                 var promisedType = getPromisedTypeOfPromise(containingType);
57155                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
57156                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57157                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
57158                 }
57159                 else {
57160                     var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
57161                     if (suggestion !== undefined) {
57162                         var suggestedName = ts.symbolName(suggestion);
57163                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, ts.declarationNameToString(propNode), typeToString(containingType), suggestedName);
57164                         relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
57165                     }
57166                     else {
57167                         errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
57168                     }
57169                 }
57170             }
57171             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
57172             if (relatedInfo) {
57173                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
57174             }
57175             diagnostics.add(resultDiagnostic);
57176         }
57177         function typeHasStaticProperty(propName, containingType) {
57178             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
57179             return prop !== undefined && prop.valueDeclaration && ts.hasModifier(prop.valueDeclaration, 32 /* Static */);
57180         }
57181         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
57182             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
57183         }
57184         function getSuggestionForNonexistentProperty(name, containingType) {
57185             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
57186             return suggestion && ts.symbolName(suggestion);
57187         }
57188         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
57189             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
57190             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
57191                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
57192                 var symbol = getSymbol(symbols, name, meaning);
57193                 // 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
57194                 // So the table *contains* `x` but `x` isn't actually in scope.
57195                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
57196                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
57197             });
57198             return result;
57199         }
57200         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
57201             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
57202             return symbolResult && ts.symbolName(symbolResult);
57203         }
57204         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
57205             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
57206         }
57207         function getSuggestionForNonexistentExport(name, targetModule) {
57208             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
57209             return suggestion && ts.symbolName(suggestion);
57210         }
57211         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
57212             // check if object type has setter or getter
57213             function hasProp(name) {
57214                 var prop = getPropertyOfObjectType(objectType, name);
57215                 if (prop) {
57216                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
57217                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
57218                 }
57219                 return false;
57220             }
57221             ;
57222             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
57223             if (!hasProp(suggestedMethod)) {
57224                 return undefined;
57225             }
57226             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
57227             if (suggestion === undefined) {
57228                 suggestion = suggestedMethod;
57229             }
57230             else {
57231                 suggestion += "." + suggestedMethod;
57232             }
57233             return suggestion;
57234         }
57235         /**
57236          * 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.
57237          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
57238          *
57239          * If there is a candidate that's the same except for case, return that.
57240          * If there is a candidate that's within one edit of the name, return that.
57241          * Otherwise, return the candidate with the smallest Levenshtein distance,
57242          *    except for candidates:
57243          *      * With no name
57244          *      * Whose meaning doesn't match the `meaning` parameter.
57245          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
57246          *      * Whose levenshtein distance is more than 0.4 of the length of the name
57247          *        (0.4 allows 1 substitution/transposition for every 5 characters,
57248          *         and 1 insertion/deletion at 3 characters)
57249          */
57250         function getSpellingSuggestionForName(name, symbols, meaning) {
57251             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
57252             function getCandidateName(candidate) {
57253                 var candidateName = ts.symbolName(candidate);
57254                 if (ts.startsWith(candidateName, "\"")) {
57255                     return undefined;
57256                 }
57257                 if (candidate.flags & meaning) {
57258                     return candidateName;
57259                 }
57260                 if (candidate.flags & 2097152 /* Alias */) {
57261                     var alias = tryResolveAlias(candidate);
57262                     if (alias && alias.flags & meaning) {
57263                         return candidateName;
57264                     }
57265                 }
57266                 return undefined;
57267             }
57268         }
57269         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
57270             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
57271             if (!valueDeclaration) {
57272                 return;
57273             }
57274             var hasPrivateModifier = ts.hasModifier(valueDeclaration, 8 /* Private */);
57275             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
57276             if (!hasPrivateModifier && !hasPrivateIdentifier) {
57277                 return;
57278             }
57279             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
57280                 return;
57281             }
57282             if (isThisAccess) {
57283                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
57284                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
57285                 if (containingMethod && containingMethod.symbol === prop) {
57286                     return;
57287                 }
57288             }
57289             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
57290         }
57291         function isValidPropertyAccess(node, propertyName) {
57292             switch (node.kind) {
57293                 case 194 /* PropertyAccessExpression */:
57294                     return isValidPropertyAccessWithType(node, node.expression.kind === 102 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
57295                 case 153 /* QualifiedName */:
57296                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
57297                 case 188 /* ImportType */:
57298                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
57299             }
57300         }
57301         function isValidPropertyAccessForCompletions(node, type, property) {
57302             return isValidPropertyAccessWithType(node, node.kind === 194 /* PropertyAccessExpression */ && node.expression.kind === 102 /* SuperKeyword */, property.escapedName, type);
57303             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
57304         }
57305         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
57306             if (type === errorType || isTypeAny(type)) {
57307                 return true;
57308             }
57309             var prop = getPropertyOfType(type, propertyName);
57310             if (prop) {
57311                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
57312                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
57313                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
57314                 }
57315                 return checkPropertyAccessibility(node, isSuper, type, prop);
57316             }
57317             // In js files properties of unions are allowed in completion
57318             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
57319         }
57320         /**
57321          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
57322          */
57323         function getForInVariableSymbol(node) {
57324             var initializer = node.initializer;
57325             if (initializer.kind === 243 /* VariableDeclarationList */) {
57326                 var variable = initializer.declarations[0];
57327                 if (variable && !ts.isBindingPattern(variable.name)) {
57328                     return getSymbolOfNode(variable);
57329                 }
57330             }
57331             else if (initializer.kind === 75 /* Identifier */) {
57332                 return getResolvedSymbol(initializer);
57333             }
57334             return undefined;
57335         }
57336         /**
57337          * Return true if the given type is considered to have numeric property names.
57338          */
57339         function hasNumericPropertyNames(type) {
57340             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
57341         }
57342         /**
57343          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
57344          * that references a for-in variable for an object with numeric property names.
57345          */
57346         function isForInVariableForNumericPropertyNames(expr) {
57347             var e = ts.skipParentheses(expr);
57348             if (e.kind === 75 /* Identifier */) {
57349                 var symbol = getResolvedSymbol(e);
57350                 if (symbol.flags & 3 /* Variable */) {
57351                     var child = expr;
57352                     var node = expr.parent;
57353                     while (node) {
57354                         if (node.kind === 231 /* ForInStatement */ &&
57355                             child === node.statement &&
57356                             getForInVariableSymbol(node) === symbol &&
57357                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
57358                             return true;
57359                         }
57360                         child = node;
57361                         node = node.parent;
57362                     }
57363                 }
57364             }
57365             return false;
57366         }
57367         function checkIndexedAccess(node) {
57368             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
57369                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
57370         }
57371         function checkElementAccessChain(node) {
57372             var exprType = checkExpression(node.expression);
57373             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
57374             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
57375         }
57376         function checkElementAccessExpression(node, exprType) {
57377             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
57378             var indexExpression = node.argumentExpression;
57379             var indexType = checkExpression(indexExpression);
57380             if (objectType === errorType || objectType === silentNeverType) {
57381                 return objectType;
57382             }
57383             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
57384                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
57385                 return errorType;
57386             }
57387             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
57388             var accessFlags = ts.isAssignmentTarget(node) ?
57389                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
57390                 0 /* None */;
57391             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType;
57392             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
57393         }
57394         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
57395             if (expressionType === errorType) {
57396                 // There is already an error, so no need to report one.
57397                 return false;
57398             }
57399             if (!ts.isWellKnownSymbolSyntactically(expression)) {
57400                 return false;
57401             }
57402             // Make sure the property type is the primitive symbol type
57403             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
57404                 if (reportError) {
57405                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
57406                 }
57407                 return false;
57408             }
57409             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
57410             // global Symbol object
57411             var leftHandSide = expression.expression;
57412             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
57413             if (!leftHandSideSymbol) {
57414                 return false;
57415             }
57416             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
57417             if (!globalESSymbol) {
57418                 // Already errored when we tried to look up the symbol
57419                 return false;
57420             }
57421             if (leftHandSideSymbol !== globalESSymbol) {
57422                 if (reportError) {
57423                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
57424                 }
57425                 return false;
57426             }
57427             return true;
57428         }
57429         function callLikeExpressionMayHaveTypeArguments(node) {
57430             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
57431         }
57432         function resolveUntypedCall(node) {
57433             if (callLikeExpressionMayHaveTypeArguments(node)) {
57434                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
57435                 // This gets us diagnostics for the type arguments and marks them as referenced.
57436                 ts.forEach(node.typeArguments, checkSourceElement);
57437             }
57438             if (node.kind === 198 /* TaggedTemplateExpression */) {
57439                 checkExpression(node.template);
57440             }
57441             else if (ts.isJsxOpeningLikeElement(node)) {
57442                 checkExpression(node.attributes);
57443             }
57444             else if (node.kind !== 157 /* Decorator */) {
57445                 ts.forEach(node.arguments, function (argument) {
57446                     checkExpression(argument);
57447                 });
57448             }
57449             return anySignature;
57450         }
57451         function resolveErrorCall(node) {
57452             resolveUntypedCall(node);
57453             return unknownSignature;
57454         }
57455         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
57456         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
57457         // A nit here is that we reorder only signatures that belong to the same symbol,
57458         // so order how inherited signatures are processed is still preserved.
57459         // interface A { (x: string): void }
57460         // interface B extends A { (x: 'foo'): string }
57461         // const b: B;
57462         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
57463         function reorderCandidates(signatures, result, callChainFlags) {
57464             var lastParent;
57465             var lastSymbol;
57466             var cutoffIndex = 0;
57467             var index;
57468             var specializedIndex = -1;
57469             var spliceIndex;
57470             ts.Debug.assert(!result.length);
57471             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
57472                 var signature = signatures_7[_i];
57473                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
57474                 var parent = signature.declaration && signature.declaration.parent;
57475                 if (!lastSymbol || symbol === lastSymbol) {
57476                     if (lastParent && parent === lastParent) {
57477                         index = index + 1;
57478                     }
57479                     else {
57480                         lastParent = parent;
57481                         index = cutoffIndex;
57482                     }
57483                 }
57484                 else {
57485                     // current declaration belongs to a different symbol
57486                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
57487                     index = cutoffIndex = result.length;
57488                     lastParent = parent;
57489                 }
57490                 lastSymbol = symbol;
57491                 // specialized signatures always need to be placed before non-specialized signatures regardless
57492                 // of the cutoff position; see GH#1133
57493                 if (signatureHasLiteralTypes(signature)) {
57494                     specializedIndex++;
57495                     spliceIndex = specializedIndex;
57496                     // The cutoff index always needs to be greater than or equal to the specialized signature index
57497                     // in order to prevent non-specialized signatures from being added before a specialized
57498                     // signature.
57499                     cutoffIndex++;
57500                 }
57501                 else {
57502                     spliceIndex = index;
57503                 }
57504                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
57505             }
57506         }
57507         function isSpreadArgument(arg) {
57508             return !!arg && (arg.kind === 213 /* SpreadElement */ || arg.kind === 220 /* SyntheticExpression */ && arg.isSpread);
57509         }
57510         function getSpreadArgumentIndex(args) {
57511             return ts.findIndex(args, isSpreadArgument);
57512         }
57513         function acceptsVoid(t) {
57514             return !!(t.flags & 16384 /* Void */);
57515         }
57516         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
57517             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
57518             var argCount;
57519             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
57520             var effectiveParameterCount = getParameterCount(signature);
57521             var effectiveMinimumArguments = getMinArgumentCount(signature);
57522             if (node.kind === 198 /* TaggedTemplateExpression */) {
57523                 argCount = args.length;
57524                 if (node.template.kind === 211 /* TemplateExpression */) {
57525                     // If a tagged template expression lacks a tail literal, the call is incomplete.
57526                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
57527                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
57528                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
57529                 }
57530                 else {
57531                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
57532                     // then this might actually turn out to be a TemplateHead in the future;
57533                     // so we consider the call to be incomplete.
57534                     var templateLiteral = node.template;
57535                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
57536                     callIsIncomplete = !!templateLiteral.isUnterminated;
57537                 }
57538             }
57539             else if (node.kind === 157 /* Decorator */) {
57540                 argCount = getDecoratorArgumentCount(node, signature);
57541             }
57542             else if (ts.isJsxOpeningLikeElement(node)) {
57543                 callIsIncomplete = node.attributes.end === node.end;
57544                 if (callIsIncomplete) {
57545                     return true;
57546                 }
57547                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
57548                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
57549                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
57550             }
57551             else {
57552                 if (!node.arguments) {
57553                     // This only happens when we have something of the form: 'new C'
57554                     ts.Debug.assert(node.kind === 197 /* NewExpression */);
57555                     return getMinArgumentCount(signature) === 0;
57556                 }
57557                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
57558                 // If we are missing the close parenthesis, the call is incomplete.
57559                 callIsIncomplete = node.arguments.end === node.end;
57560                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
57561                 var spreadArgIndex = getSpreadArgumentIndex(args);
57562                 if (spreadArgIndex >= 0) {
57563                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
57564                 }
57565             }
57566             // Too many arguments implies incorrect arity.
57567             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
57568                 return false;
57569             }
57570             // If the call is incomplete, we should skip the lower bound check.
57571             // JSX signatures can have extra parameters provided by the library which we don't check
57572             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
57573                 return true;
57574             }
57575             for (var i = argCount; i < effectiveMinimumArguments; i++) {
57576                 var type = getTypeAtPosition(signature, i);
57577                 if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
57578                     return false;
57579                 }
57580             }
57581             return true;
57582         }
57583         function hasCorrectTypeArgumentArity(signature, typeArguments) {
57584             // If the user supplied type arguments, but the number of type arguments does not match
57585             // the declared number of type parameters, the call has an incorrect arity.
57586             var numTypeParameters = ts.length(signature.typeParameters);
57587             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
57588             return !ts.some(typeArguments) ||
57589                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
57590         }
57591         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
57592         function getSingleCallSignature(type) {
57593             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
57594         }
57595         function getSingleCallOrConstructSignature(type) {
57596             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
57597                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
57598         }
57599         function getSingleSignature(type, kind, allowMembers) {
57600             if (type.flags & 524288 /* Object */) {
57601                 var resolved = resolveStructuredTypeMembers(type);
57602                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
57603                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
57604                         return resolved.callSignatures[0];
57605                     }
57606                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
57607                         return resolved.constructSignatures[0];
57608                     }
57609                 }
57610             }
57611             return undefined;
57612         }
57613         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
57614         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
57615             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
57616             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
57617             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
57618             // for T but leave it possible to later infer '[any]' back to A.
57619             var restType = getEffectiveRestType(contextualSignature);
57620             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
57621             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
57622             applyToParameterTypes(sourceSignature, signature, function (source, target) {
57623                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
57624                 inferTypes(context.inferences, source, target);
57625             });
57626             if (!inferenceContext) {
57627                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
57628                     inferTypes(context.inferences, source, target, 32 /* ReturnType */);
57629                 });
57630             }
57631             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
57632         }
57633         function inferJsxTypeArguments(node, signature, checkMode, context) {
57634             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57635             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
57636             inferTypes(context.inferences, checkAttrType, paramType);
57637             return getInferredTypes(context);
57638         }
57639         function inferTypeArguments(node, signature, args, checkMode, context) {
57640             if (ts.isJsxOpeningLikeElement(node)) {
57641                 return inferJsxTypeArguments(node, signature, checkMode, context);
57642             }
57643             // If a contextual type is available, infer from that type to the return type of the call expression. For
57644             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
57645             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
57646             // return type of 'wrap'.
57647             if (node.kind !== 157 /* Decorator */) {
57648                 var contextualType = getContextualType(node);
57649                 if (contextualType) {
57650                     // We clone the inference context to avoid disturbing a resolution in progress for an
57651                     // outer call expression. Effectively we just want a snapshot of whatever has been
57652                     // inferred for any outer call expression so far.
57653                     var outerContext = getInferenceContext(node);
57654                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
57655                     var instantiatedType = instantiateType(contextualType, outerMapper);
57656                     // If the contextual type is a generic function type with a single call signature, we
57657                     // instantiate the type with its own type parameters and type arguments. This ensures that
57658                     // the type parameters are not erased to type any during type inference such that they can
57659                     // be inferred as actual types from the contextual type. For example:
57660                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
57661                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
57662                     // Above, the type of the 'value' parameter is inferred to be 'A'.
57663                     var contextualSignature = getSingleCallSignature(instantiatedType);
57664                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
57665                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
57666                         instantiatedType;
57667                     var inferenceTargetType = getReturnTypeOfSignature(signature);
57668                     // Inferences made from return types have lower priority than all other inferences.
57669                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 32 /* ReturnType */);
57670                     // Create a type mapper for instantiating generic contextual types using the inferences made
57671                     // from the return type. We need a separate inference pass here because (a) instantiation of
57672                     // the source type uses the outer context's return mapper (which excludes inferences made from
57673                     // outer arguments), and (b) we don't want any further inferences going into this context.
57674                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
57675                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
57676                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
57677                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
57678                 }
57679             }
57680             var thisType = getThisTypeOfSignature(signature);
57681             if (thisType) {
57682                 var thisArgumentNode = getThisArgumentOfCall(node);
57683                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
57684                 inferTypes(context.inferences, thisArgumentType, thisType);
57685             }
57686             var restType = getNonArrayRestType(signature);
57687             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57688             for (var i = 0; i < argCount; i++) {
57689                 var arg = args[i];
57690                 if (arg.kind !== 215 /* OmittedExpression */) {
57691                     var paramType = getTypeAtPosition(signature, i);
57692                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
57693                     inferTypes(context.inferences, argType, paramType);
57694                 }
57695             }
57696             if (restType) {
57697                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context);
57698                 inferTypes(context.inferences, spreadType, restType);
57699             }
57700             return getInferredTypes(context);
57701         }
57702         function getArrayifiedType(type) {
57703             return type.flags & 1048576 /* Union */ ? mapType(type, getArrayifiedType) :
57704                 type.flags & (1 /* Any */ | 63176704 /* Instantiable */) || isMutableArrayOrTuple(type) ? type :
57705                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.minLength, type.target.hasRestElement, /*readonly*/ false, type.target.associatedNames) :
57706                         createArrayType(getIndexedAccessType(type, numberType));
57707         }
57708         function getSpreadArgumentType(args, index, argCount, restType, context) {
57709             if (index >= argCount - 1) {
57710                 var arg = args[argCount - 1];
57711                 if (isSpreadArgument(arg)) {
57712                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
57713                     // and the argument are ...x forms.
57714                     return arg.kind === 220 /* SyntheticExpression */ ?
57715                         createArrayType(arg.type) :
57716                         getArrayifiedType(checkExpressionWithContextualType(arg.expression, restType, context, 0 /* Normal */));
57717                 }
57718             }
57719             var types = [];
57720             var spreadIndex = -1;
57721             for (var i = index; i < argCount; i++) {
57722                 var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
57723                 var argType = checkExpressionWithContextualType(args[i], contextualType, context, 0 /* Normal */);
57724                 if (spreadIndex < 0 && isSpreadArgument(args[i])) {
57725                     spreadIndex = i - index;
57726                 }
57727                 var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */);
57728                 types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
57729             }
57730             return spreadIndex < 0 ?
57731                 createTupleType(types) :
57732                 createTupleType(ts.append(types.slice(0, spreadIndex), getUnionType(types.slice(spreadIndex))), spreadIndex, /*hasRestElement*/ true);
57733         }
57734         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
57735             var isJavascript = ts.isInJSFile(signature.declaration);
57736             var typeParameters = signature.typeParameters;
57737             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
57738             var mapper;
57739             for (var i = 0; i < typeArgumentNodes.length; i++) {
57740                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
57741                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
57742                 if (constraint) {
57743                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
57744                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
57745                     if (!mapper) {
57746                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
57747                     }
57748                     var typeArgument = typeArgumentTypes[i];
57749                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
57750                         return undefined;
57751                     }
57752                 }
57753             }
57754             return typeArgumentTypes;
57755         }
57756         function getJsxReferenceKind(node) {
57757             if (isJsxIntrinsicIdentifier(node.tagName)) {
57758                 return 2 /* Mixed */;
57759             }
57760             var tagType = getApparentType(checkExpression(node.tagName));
57761             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
57762                 return 0 /* Component */;
57763             }
57764             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
57765                 return 1 /* Function */;
57766             }
57767             return 2 /* Mixed */;
57768         }
57769         /**
57770          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
57771          * @param node a JSX opening-like element we are trying to figure its call signature
57772          * @param signature a candidate signature we are trying whether it is a call signature
57773          * @param relation a relationship to check parameter and argument type
57774          */
57775         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
57776             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
57777             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
57778             // can be specified by users through attributes property.
57779             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
57780             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
57781             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
57782             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57783             function checkTagNameDoesNotExpectTooManyArguments() {
57784                 var _a;
57785                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
57786                 if (!tagType) {
57787                     return true;
57788                 }
57789                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
57790                 if (!ts.length(tagCallSignatures)) {
57791                     return true;
57792                 }
57793                 var factory = getJsxFactoryEntity(node);
57794                 if (!factory) {
57795                     return true;
57796                 }
57797                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
57798                 if (!factorySymbol) {
57799                     return true;
57800                 }
57801                 var factoryType = getTypeOfSymbol(factorySymbol);
57802                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
57803                 if (!ts.length(callSignatures)) {
57804                     return true;
57805                 }
57806                 var hasFirstParamSignatures = false;
57807                 var maxParamCount = 0;
57808                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
57809                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
57810                     var sig = callSignatures_1[_i];
57811                     var firstparam = getTypeAtPosition(sig, 0);
57812                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
57813                     if (!ts.length(signaturesOfParam))
57814                         continue;
57815                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
57816                         var paramSig = signaturesOfParam_1[_b];
57817                         hasFirstParamSignatures = true;
57818                         if (hasEffectiveRestParameter(paramSig)) {
57819                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
57820                         }
57821                         var paramCount = getParameterCount(paramSig);
57822                         if (paramCount > maxParamCount) {
57823                             maxParamCount = paramCount;
57824                         }
57825                     }
57826                 }
57827                 if (!hasFirstParamSignatures) {
57828                     // Not a single signature had a first parameter which expected a signature - for back compat, and
57829                     // to guard against generic factories which won't have signatures directly, do not error
57830                     return true;
57831                 }
57832                 var absoluteMinArgCount = Infinity;
57833                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
57834                     var tagSig = tagCallSignatures_1[_c];
57835                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
57836                     if (tagRequiredArgCount < absoluteMinArgCount) {
57837                         absoluteMinArgCount = tagRequiredArgCount;
57838                     }
57839                 }
57840                 if (absoluteMinArgCount <= maxParamCount) {
57841                     return true; // some signature accepts the number of arguments the function component provides
57842                 }
57843                 if (reportErrors) {
57844                     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);
57845                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
57846                     if (tagNameDeclaration) {
57847                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
57848                     }
57849                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
57850                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57851                     }
57852                     if (!errorOutputContainer.skipLogging) {
57853                         diagnostics.add(diag);
57854                     }
57855                 }
57856                 return false;
57857             }
57858         }
57859         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
57860             var errorOutputContainer = { errors: undefined, skipLogging: true };
57861             if (ts.isJsxOpeningLikeElement(node)) {
57862                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
57863                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
57864                     return errorOutputContainer.errors || ts.emptyArray;
57865                 }
57866                 return undefined;
57867             }
57868             var thisType = getThisTypeOfSignature(signature);
57869             if (thisType && thisType !== voidType && node.kind !== 197 /* NewExpression */) {
57870                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
57871                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
57872                 // If the expression is a new expression, then the check is skipped.
57873                 var thisArgumentNode = getThisArgumentOfCall(node);
57874                 var thisArgumentType = void 0;
57875                 if (thisArgumentNode) {
57876                     thisArgumentType = checkExpression(thisArgumentNode);
57877                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
57878                         thisArgumentType = getNonNullableType(thisArgumentType);
57879                     }
57880                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
57881                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
57882                     }
57883                 }
57884                 else {
57885                     thisArgumentType = voidType;
57886                 }
57887                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
57888                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
57889                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
57890                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
57891                     return errorOutputContainer.errors || ts.emptyArray;
57892                 }
57893             }
57894             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
57895             var restType = getNonArrayRestType(signature);
57896             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
57897             for (var i = 0; i < argCount; i++) {
57898                 var arg = args[i];
57899                 if (arg.kind !== 215 /* OmittedExpression */) {
57900                     var paramType = getTypeAtPosition(signature, i);
57901                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
57902                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
57903                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
57904                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
57905                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
57906                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
57907                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
57908                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
57909                         return errorOutputContainer.errors || ts.emptyArray;
57910                     }
57911                 }
57912             }
57913             if (restType) {
57914                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined);
57915                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
57916                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
57917                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
57918                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
57919                     return errorOutputContainer.errors || ts.emptyArray;
57920                 }
57921             }
57922             return undefined;
57923             function maybeAddMissingAwaitInfo(errorNode, source, target) {
57924                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
57925                     // Bail if target is Promise-like---something else is wrong
57926                     if (getAwaitedTypeOfPromise(target)) {
57927                         return;
57928                     }
57929                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
57930                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
57931                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
57932                     }
57933                 }
57934             }
57935         }
57936         /**
57937          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
57938          */
57939         function getThisArgumentOfCall(node) {
57940             if (node.kind === 196 /* CallExpression */) {
57941                 var callee = ts.skipOuterExpressions(node.expression);
57942                 if (ts.isAccessExpression(callee)) {
57943                     return callee.expression;
57944                 }
57945             }
57946         }
57947         function createSyntheticExpression(parent, type, isSpread) {
57948             var result = ts.createNode(220 /* SyntheticExpression */, parent.pos, parent.end);
57949             result.parent = parent;
57950             result.type = type;
57951             result.isSpread = isSpread || false;
57952             return result;
57953         }
57954         /**
57955          * Returns the effective arguments for an expression that works like a function invocation.
57956          */
57957         function getEffectiveCallArguments(node) {
57958             if (node.kind === 198 /* TaggedTemplateExpression */) {
57959                 var template = node.template;
57960                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
57961                 if (template.kind === 211 /* TemplateExpression */) {
57962                     ts.forEach(template.templateSpans, function (span) {
57963                         args_3.push(span.expression);
57964                     });
57965                 }
57966                 return args_3;
57967             }
57968             if (node.kind === 157 /* Decorator */) {
57969                 return getEffectiveDecoratorArguments(node);
57970             }
57971             if (ts.isJsxOpeningLikeElement(node)) {
57972                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
57973             }
57974             var args = node.arguments || ts.emptyArray;
57975             var length = args.length;
57976             if (length && isSpreadArgument(args[length - 1]) && getSpreadArgumentIndex(args) === length - 1) {
57977                 // We have a spread argument in the last position and no other spread arguments. If the type
57978                 // of the argument is a tuple type, spread the tuple elements into the argument list. We can
57979                 // call checkExpressionCached because spread expressions never have a contextual type.
57980                 var spreadArgument_1 = args[length - 1];
57981                 var type = flowLoopCount ? checkExpression(spreadArgument_1.expression) : checkExpressionCached(spreadArgument_1.expression);
57982                 if (isTupleType(type)) {
57983                     var typeArguments = getTypeArguments(type);
57984                     var restIndex_2 = type.target.hasRestElement ? typeArguments.length - 1 : -1;
57985                     var syntheticArgs = ts.map(typeArguments, function (t, i) { return createSyntheticExpression(spreadArgument_1, t, /*isSpread*/ i === restIndex_2); });
57986                     return ts.concatenate(args.slice(0, length - 1), syntheticArgs);
57987                 }
57988             }
57989             return args;
57990         }
57991         /**
57992          * Returns the synthetic argument list for a decorator invocation.
57993          */
57994         function getEffectiveDecoratorArguments(node) {
57995             var parent = node.parent;
57996             var expr = node.expression;
57997             switch (parent.kind) {
57998                 case 245 /* ClassDeclaration */:
57999                 case 214 /* ClassExpression */:
58000                     // For a class decorator, the `target` is the type of the class (e.g. the
58001                     // "static" or "constructor" side of the class).
58002                     return [
58003                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
58004                     ];
58005                 case 156 /* Parameter */:
58006                     // A parameter declaration decorator will have three arguments (see
58007                     // `ParameterDecorator` in core.d.ts).
58008                     var func = parent.parent;
58009                     return [
58010                         createSyntheticExpression(expr, parent.parent.kind === 162 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
58011                         createSyntheticExpression(expr, anyType),
58012                         createSyntheticExpression(expr, numberType)
58013                     ];
58014                 case 159 /* PropertyDeclaration */:
58015                 case 161 /* MethodDeclaration */:
58016                 case 163 /* GetAccessor */:
58017                 case 164 /* SetAccessor */:
58018                     // A method or accessor declaration decorator will have two or three arguments (see
58019                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
58020                     // for ES3, we will only pass two arguments.
58021                     var hasPropDesc = parent.kind !== 159 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
58022                     return [
58023                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
58024                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
58025                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
58026                     ];
58027             }
58028             return ts.Debug.fail();
58029         }
58030         /**
58031          * Returns the argument count for a decorator node that works like a function invocation.
58032          */
58033         function getDecoratorArgumentCount(node, signature) {
58034             switch (node.parent.kind) {
58035                 case 245 /* ClassDeclaration */:
58036                 case 214 /* ClassExpression */:
58037                     return 1;
58038                 case 159 /* PropertyDeclaration */:
58039                     return 2;
58040                 case 161 /* MethodDeclaration */:
58041                 case 163 /* GetAccessor */:
58042                 case 164 /* SetAccessor */:
58043                     // For ES3 or decorators with only two parameters we supply only two arguments
58044                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
58045                 case 156 /* Parameter */:
58046                     return 3;
58047                 default:
58048                     return ts.Debug.fail();
58049             }
58050         }
58051         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
58052             var start;
58053             var length;
58054             var sourceFile = ts.getSourceFileOfNode(node);
58055             if (ts.isPropertyAccessExpression(node.expression)) {
58056                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
58057                 start = nameSpan.start;
58058                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
58059             }
58060             else {
58061                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
58062                 start = expressionSpan.start;
58063                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
58064             }
58065             return { start: start, length: length, sourceFile: sourceFile };
58066         }
58067         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
58068             if (ts.isCallExpression(node)) {
58069                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
58070                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
58071             }
58072             else {
58073                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
58074             }
58075         }
58076         function getArgumentArityError(node, signatures, args) {
58077             var min = Number.POSITIVE_INFINITY;
58078             var max = Number.NEGATIVE_INFINITY;
58079             var belowArgCount = Number.NEGATIVE_INFINITY;
58080             var aboveArgCount = Number.POSITIVE_INFINITY;
58081             var argCount = args.length;
58082             var closestSignature;
58083             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
58084                 var sig = signatures_8[_i];
58085                 var minCount = getMinArgumentCount(sig);
58086                 var maxCount = getParameterCount(sig);
58087                 if (minCount < argCount && minCount > belowArgCount)
58088                     belowArgCount = minCount;
58089                 if (argCount < maxCount && maxCount < aboveArgCount)
58090                     aboveArgCount = maxCount;
58091                 if (minCount < min) {
58092                     min = minCount;
58093                     closestSignature = sig;
58094                 }
58095                 max = Math.max(max, maxCount);
58096             }
58097             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
58098             var paramRange = hasRestParameter ? min :
58099                 min < max ? min + "-" + max :
58100                     min;
58101             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
58102             if (argCount <= max && hasSpreadArgument) {
58103                 argCount--;
58104             }
58105             var spanArray;
58106             var related;
58107             var error = hasRestParameter || hasSpreadArgument ? hasRestParameter && hasSpreadArgument ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
58108                 hasRestParameter ? ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
58109                     ts.Diagnostics.Expected_0_arguments_but_got_1_or_more : ts.Diagnostics.Expected_0_arguments_but_got_1;
58110             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
58111                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
58112                 if (paramDecl) {
58113                     related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined);
58114                 }
58115             }
58116             if (min < argCount && argCount < max) {
58117                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
58118             }
58119             if (!hasSpreadArgument && argCount < min) {
58120                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
58121                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
58122             }
58123             if (hasRestParameter || hasSpreadArgument) {
58124                 spanArray = ts.createNodeArray(args);
58125                 if (hasSpreadArgument && argCount) {
58126                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
58127                     spanArray = ts.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
58128                 }
58129             }
58130             else {
58131                 spanArray = ts.createNodeArray(args.slice(max));
58132             }
58133             spanArray.pos = ts.first(spanArray).pos;
58134             spanArray.end = ts.last(spanArray).end;
58135             if (spanArray.end === spanArray.pos) {
58136                 spanArray.end++;
58137             }
58138             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
58139             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
58140         }
58141         function getTypeArgumentArityError(node, signatures, typeArguments) {
58142             var argCount = typeArguments.length;
58143             // No overloads exist
58144             if (signatures.length === 1) {
58145                 var sig = signatures[0];
58146                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
58147                 var max = ts.length(sig.typeParameters);
58148                 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);
58149             }
58150             // Overloads exist
58151             var belowArgCount = -Infinity;
58152             var aboveArgCount = Infinity;
58153             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
58154                 var sig = signatures_9[_i];
58155                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
58156                 var max = ts.length(sig.typeParameters);
58157                 if (min_2 > argCount) {
58158                     aboveArgCount = Math.min(aboveArgCount, min_2);
58159                 }
58160                 else if (max < argCount) {
58161                     belowArgCount = Math.max(belowArgCount, max);
58162                 }
58163             }
58164             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
58165                 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);
58166             }
58167             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
58168         }
58169         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
58170             var isTaggedTemplate = node.kind === 198 /* TaggedTemplateExpression */;
58171             var isDecorator = node.kind === 157 /* Decorator */;
58172             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
58173             var reportErrors = !candidatesOutArray;
58174             var typeArguments;
58175             if (!isDecorator) {
58176                 typeArguments = node.typeArguments;
58177                 // We already perform checking on the type arguments on the class declaration itself.
58178                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 102 /* SuperKeyword */) {
58179                     ts.forEach(typeArguments, checkSourceElement);
58180                 }
58181             }
58182             var candidates = candidatesOutArray || [];
58183             // reorderCandidates fills up the candidates array directly
58184             reorderCandidates(signatures, candidates, callChainFlags);
58185             if (!candidates.length) {
58186                 if (reportErrors) {
58187                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
58188                 }
58189                 return resolveErrorCall(node);
58190             }
58191             var args = getEffectiveCallArguments(node);
58192             // The excludeArgument array contains true for each context sensitive argument (an argument
58193             // is context sensitive it is susceptible to a one-time permanent contextual typing).
58194             //
58195             // The idea is that we will perform type argument inference & assignability checking once
58196             // without using the susceptible parameters that are functions, and once more for those
58197             // parameters, contextually typing each as we go along.
58198             //
58199             // For a tagged template, then the first argument be 'undefined' if necessary because it
58200             // represents a TemplateStringsArray.
58201             //
58202             // For a decorator, no arguments are susceptible to contextual typing due to the fact
58203             // decorators are applied to a declaration by the emitter, and not to an expression.
58204             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
58205             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
58206             // The following variables are captured and modified by calls to chooseOverload.
58207             // If overload resolution or type argument inference fails, we want to report the
58208             // best error possible. The best error is one which says that an argument was not
58209             // assignable to a parameter. This implies that everything else about the overload
58210             // was fine. So if there is any overload that is only incorrect because of an
58211             // argument, we will report an error on that one.
58212             //
58213             //     function foo(s: string): void;
58214             //     function foo(n: number): void; // Report argument error on this overload
58215             //     function foo(): void;
58216             //     foo(true);
58217             //
58218             // If none of the overloads even made it that far, there are two possibilities.
58219             // There was a problem with type arguments for some overload, in which case
58220             // report an error on that. Or none of the overloads even had correct arity,
58221             // in which case give an arity error.
58222             //
58223             //     function foo<T extends string>(x: T): void; // Report type argument error
58224             //     function foo(): void;
58225             //     foo<number>(0);
58226             //
58227             var candidatesForArgumentError;
58228             var candidateForArgumentArityError;
58229             var candidateForTypeArgumentError;
58230             var result;
58231             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
58232             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
58233             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 196 /* CallExpression */ && node.arguments.hasTrailingComma;
58234             // Section 4.12.1:
58235             // if the candidate list contains one or more signatures for which the type of each argument
58236             // expression is a subtype of each corresponding parameter type, the return type of the first
58237             // of those signatures becomes the return type of the function call.
58238             // Otherwise, the return type of the first signature in the candidate list becomes the return
58239             // type of the function call.
58240             //
58241             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
58242             // is just important for choosing the best signature. So in the case where there is only one
58243             // signature, the subtype pass is useless. So skipping it is an optimization.
58244             if (candidates.length > 1) {
58245                 result = chooseOverload(candidates, subtypeRelation, signatureHelpTrailingComma);
58246             }
58247             if (!result) {
58248                 result = chooseOverload(candidates, assignableRelation, signatureHelpTrailingComma);
58249             }
58250             if (result) {
58251                 return result;
58252             }
58253             // No signatures were applicable. Now report errors based on the last applicable signature with
58254             // no arguments excluded from assignability checks.
58255             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
58256             // skip the checkApplicableSignature check.
58257             if (reportErrors) {
58258                 if (candidatesForArgumentError) {
58259                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
58260                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
58261                         var chain_1;
58262                         if (candidatesForArgumentError.length > 3) {
58263                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
58264                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
58265                         }
58266                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
58267                         if (diags) {
58268                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
58269                                 var d = diags_1[_i];
58270                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
58271                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
58272                                 }
58273                                 diagnostics.add(d);
58274                             }
58275                         }
58276                         else {
58277                             ts.Debug.fail("No error for last overload signature");
58278                         }
58279                     }
58280                     else {
58281                         var allDiagnostics = [];
58282                         var max = 0;
58283                         var min_3 = Number.MAX_VALUE;
58284                         var minIndex = 0;
58285                         var i_1 = 0;
58286                         var _loop_17 = function (c) {
58287                             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)); };
58288                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
58289                             if (diags_2) {
58290                                 if (diags_2.length <= min_3) {
58291                                     min_3 = diags_2.length;
58292                                     minIndex = i_1;
58293                                 }
58294                                 max = Math.max(max, diags_2.length);
58295                                 allDiagnostics.push(diags_2);
58296                             }
58297                             else {
58298                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
58299                             }
58300                             i_1++;
58301                         };
58302                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
58303                             var c = candidatesForArgumentError_1[_a];
58304                             _loop_17(c);
58305                         }
58306                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
58307                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
58308                         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);
58309                         var related = ts.flatMap(diags_3, function (d) { return d.relatedInformation; });
58310                         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; })) {
58311                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
58312                             diagnostics.add({ file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related });
58313                         }
58314                         else {
58315                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, chain, related));
58316                         }
58317                     }
58318                 }
58319                 else if (candidateForArgumentArityError) {
58320                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
58321                 }
58322                 else if (candidateForTypeArgumentError) {
58323                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
58324                 }
58325                 else {
58326                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
58327                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
58328                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
58329                     }
58330                     else if (!isDecorator) {
58331                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
58332                     }
58333                     else if (fallbackError) {
58334                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
58335                     }
58336                 }
58337             }
58338             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
58339             function chooseOverload(candidates, relation, signatureHelpTrailingComma) {
58340                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
58341                 candidatesForArgumentError = undefined;
58342                 candidateForArgumentArityError = undefined;
58343                 candidateForTypeArgumentError = undefined;
58344                 if (isSingleNonGenericCandidate) {
58345                     var candidate = candidates[0];
58346                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58347                         return undefined;
58348                     }
58349                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58350                         candidatesForArgumentError = [candidate];
58351                         return undefined;
58352                     }
58353                     return candidate;
58354                 }
58355                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
58356                     var candidate = candidates[candidateIndex];
58357                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
58358                         continue;
58359                     }
58360                     var checkCandidate = void 0;
58361                     var inferenceContext = void 0;
58362                     if (candidate.typeParameters) {
58363                         var typeArgumentTypes = void 0;
58364                         if (ts.some(typeArguments)) {
58365                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
58366                             if (!typeArgumentTypes) {
58367                                 candidateForTypeArgumentError = candidate;
58368                                 continue;
58369                             }
58370                         }
58371                         else {
58372                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58373                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
58374                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
58375                         }
58376                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58377                         // If the original signature has a generic rest type, instantiation may produce a
58378                         // signature with different arity and we need to perform another arity check.
58379                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58380                             candidateForArgumentArityError = checkCandidate;
58381                             continue;
58382                         }
58383                     }
58384                     else {
58385                         checkCandidate = candidate;
58386                     }
58387                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58388                         // Give preference to error candidates that have no rest parameters (as they are more specific)
58389                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58390                         continue;
58391                     }
58392                     if (argCheckMode) {
58393                         // If one or more context sensitive arguments were excluded, we start including
58394                         // them now (and keeping do so for any subsequent candidates) and perform a second
58395                         // round of type inference and applicability checking for this particular candidate.
58396                         argCheckMode = 0 /* Normal */;
58397                         if (inferenceContext) {
58398                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
58399                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
58400                             // If the original signature has a generic rest type, instantiation may produce a
58401                             // signature with different arity and we need to perform another arity check.
58402                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
58403                                 candidateForArgumentArityError = checkCandidate;
58404                                 continue;
58405                             }
58406                         }
58407                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
58408                             // Give preference to error candidates that have no rest parameters (as they are more specific)
58409                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
58410                             continue;
58411                         }
58412                     }
58413                     candidates[candidateIndex] = checkCandidate;
58414                     return checkCandidate;
58415                 }
58416                 return undefined;
58417             }
58418         }
58419         // No signature was applicable. We have already reported the errors for the invalid signature.
58420         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
58421             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
58422             checkNodeDeferred(node);
58423             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
58424             // Don't do this if there is a `candidatesOutArray`,
58425             // because then we want the chosen best candidate to be one of the overloads, not a combination.
58426             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
58427                 ? pickLongestCandidateSignature(node, candidates, args)
58428                 : createUnionOfSignaturesForOverloadFailure(candidates);
58429         }
58430         function createUnionOfSignaturesForOverloadFailure(candidates) {
58431             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
58432             var thisParameter;
58433             if (thisParameters.length) {
58434                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
58435             }
58436             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
58437             var parameters = [];
58438             var _loop_18 = function (i) {
58439                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
58440                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
58441                     i < s.parameters.length ? s.parameters[i] : undefined; });
58442                 ts.Debug.assert(symbols.length !== 0);
58443                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
58444             };
58445             for (var i = 0; i < maxNonRestParam; i++) {
58446                 _loop_18(i);
58447             }
58448             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
58449             var flags = 0 /* None */;
58450             if (restParameterSymbols.length !== 0) {
58451                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
58452                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
58453                 flags |= 1 /* HasRestParameter */;
58454             }
58455             if (candidates.some(signatureHasLiteralTypes)) {
58456                 flags |= 2 /* HasLiteralTypes */;
58457             }
58458             return createSignature(candidates[0].declaration, 
58459             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
58460             thisParameter, parameters, 
58461             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
58462             /*typePredicate*/ undefined, minArgumentCount, flags);
58463         }
58464         function getNumNonRestParameters(signature) {
58465             var numParams = signature.parameters.length;
58466             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
58467         }
58468         function createCombinedSymbolFromTypes(sources, types) {
58469             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
58470         }
58471         function createCombinedSymbolForOverloadFailure(sources, type) {
58472             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
58473             return createSymbolWithType(ts.first(sources), type);
58474         }
58475         function pickLongestCandidateSignature(node, candidates, args) {
58476             // Pick the longest signature. This way we can get a contextual type for cases like:
58477             //     declare function f(a: { xa: number; xb: number; }, b: number);
58478             //     f({ |
58479             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
58480             //     declare function f<T>(k: keyof T);
58481             //     f<Foo>("
58482             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
58483             var candidate = candidates[bestIndex];
58484             var typeParameters = candidate.typeParameters;
58485             if (!typeParameters) {
58486                 return candidate;
58487             }
58488             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
58489             var instantiated = typeArgumentNodes
58490                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
58491                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
58492             candidates[bestIndex] = instantiated;
58493             return instantiated;
58494         }
58495         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
58496             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
58497             while (typeArguments.length > typeParameters.length) {
58498                 typeArguments.pop();
58499             }
58500             while (typeArguments.length < typeParameters.length) {
58501                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
58502             }
58503             return typeArguments;
58504         }
58505         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
58506             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
58507             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
58508             return createSignatureInstantiation(candidate, typeArgumentTypes);
58509         }
58510         function getLongestCandidateIndex(candidates, argsCount) {
58511             var maxParamsIndex = -1;
58512             var maxParams = -1;
58513             for (var i = 0; i < candidates.length; i++) {
58514                 var candidate = candidates[i];
58515                 var paramCount = getParameterCount(candidate);
58516                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
58517                     return i;
58518                 }
58519                 if (paramCount > maxParams) {
58520                     maxParams = paramCount;
58521                     maxParamsIndex = i;
58522                 }
58523             }
58524             return maxParamsIndex;
58525         }
58526         function resolveCallExpression(node, candidatesOutArray, checkMode) {
58527             if (node.expression.kind === 102 /* SuperKeyword */) {
58528                 var superType = checkSuperExpression(node.expression);
58529                 if (isTypeAny(superType)) {
58530                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
58531                         var arg = _a[_i];
58532                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
58533                     }
58534                     return anySignature;
58535                 }
58536                 if (superType !== errorType) {
58537                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
58538                     // with the type arguments specified in the extends clause.
58539                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
58540                     if (baseTypeNode) {
58541                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
58542                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
58543                     }
58544                 }
58545                 return resolveUntypedCall(node);
58546             }
58547             var callChainFlags;
58548             var funcType = checkExpression(node.expression);
58549             if (ts.isCallChain(node)) {
58550                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
58551                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
58552                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
58553                         4 /* IsInnerCallChain */;
58554                 funcType = nonOptionalType;
58555             }
58556             else {
58557                 callChainFlags = 0 /* None */;
58558             }
58559             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
58560             if (funcType === silentNeverType) {
58561                 return silentNeverSignature;
58562             }
58563             var apparentType = getApparentType(funcType);
58564             if (apparentType === errorType) {
58565                 // Another error has already been reported
58566                 return resolveErrorCall(node);
58567             }
58568             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58569             // but we are not including call signatures that may have been added to the Object or
58570             // Function interface, since they have none by default. This is a bit of a leap of faith
58571             // that the user will not add any.
58572             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58573             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58574             // TS 1.0 Spec: 4.12
58575             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
58576             // types are provided for the argument expressions, and the result is always of type Any.
58577             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58578                 // The unknownType indicates that an error already occurred (and was reported).  No
58579                 // need to report another error in this case.
58580                 if (funcType !== errorType && node.typeArguments) {
58581                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58582                 }
58583                 return resolveUntypedCall(node);
58584             }
58585             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
58586             // TypeScript employs overload resolution in typed function calls in order to support functions
58587             // with multiple call signatures.
58588             if (!callSignatures.length) {
58589                 if (numConstructSignatures) {
58590                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58591                 }
58592                 else {
58593                     var relatedInformation = void 0;
58594                     if (node.arguments.length === 1) {
58595                         var text = ts.getSourceFileOfNode(node).text;
58596                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
58597                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
58598                         }
58599                     }
58600                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
58601                 }
58602                 return resolveErrorCall(node);
58603             }
58604             // When a call to a generic function is an argument to an outer call to a generic function for which
58605             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
58606             // its contextual type to its return type, deferring the inner call processing allows the best possible
58607             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
58608             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
58609             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
58610             // If no type arguments are specified in the inner call and at least one call signature is generic and
58611             // returns a function type, we choose to defer processing. This narrowly permits function composition
58612             // operators to flow inferences through return types, but otherwise processes calls right away. We
58613             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
58614             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
58615             // from which we never make inferences).
58616             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
58617                 skippedGenericFunction(node, checkMode);
58618                 return resolvingSignature;
58619             }
58620             // If the function is explicitly marked with `@class`, then it must be constructed.
58621             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
58622                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
58623                 return resolveErrorCall(node);
58624             }
58625             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
58626         }
58627         function isGenericFunctionReturningFunction(signature) {
58628             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
58629         }
58630         /**
58631          * TS 1.0 spec: 4.12
58632          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
58633          * but is a subtype of the Function interface, the call is an untyped function call.
58634          */
58635         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
58636             // We exclude union types because we may have a union of function types that happen to have no common signatures.
58637             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
58638                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
58639         }
58640         function resolveNewExpression(node, candidatesOutArray, checkMode) {
58641             if (node.arguments && languageVersion < 1 /* ES5 */) {
58642                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
58643                 if (spreadIndex >= 0) {
58644                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
58645                 }
58646             }
58647             var expressionType = checkNonNullExpression(node.expression);
58648             if (expressionType === silentNeverType) {
58649                 return silentNeverSignature;
58650             }
58651             // If expressionType's apparent type(section 3.8.1) is an object type with one or
58652             // more construct signatures, the expression is processed in the same manner as a
58653             // function call, but using the construct signatures as the initial set of candidate
58654             // signatures for overload resolution. The result type of the function call becomes
58655             // the result type of the operation.
58656             expressionType = getApparentType(expressionType);
58657             if (expressionType === errorType) {
58658                 // Another error has already been reported
58659                 return resolveErrorCall(node);
58660             }
58661             // TS 1.0 spec: 4.11
58662             // If expressionType is of type Any, Args can be any argument
58663             // list and the result of the operation is of type Any.
58664             if (isTypeAny(expressionType)) {
58665                 if (node.typeArguments) {
58666                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
58667                 }
58668                 return resolveUntypedCall(node);
58669             }
58670             // Technically, this signatures list may be incomplete. We are taking the apparent type,
58671             // but we are not including construct signatures that may have been added to the Object or
58672             // Function interface, since they have none by default. This is a bit of a leap of faith
58673             // that the user will not add any.
58674             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
58675             if (constructSignatures.length) {
58676                 if (!isConstructorAccessible(node, constructSignatures[0])) {
58677                     return resolveErrorCall(node);
58678                 }
58679                 // If the expression is a class of abstract type, then it cannot be instantiated.
58680                 // Note, only class declarations can be declared abstract.
58681                 // In the case of a merged class-module or class-interface declaration,
58682                 // only the class declaration node will have the Abstract flag set.
58683                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
58684                 if (valueDecl && ts.hasModifier(valueDecl, 128 /* Abstract */)) {
58685                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
58686                     return resolveErrorCall(node);
58687                 }
58688                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
58689             }
58690             // If expressionType's apparent type is an object type with no construct signatures but
58691             // one or more call signatures, the expression is processed as a function call. A compile-time
58692             // error occurs if the result of the function call is not Void. The type of the result of the
58693             // operation is Any. It is an error to have a Void this type.
58694             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
58695             if (callSignatures.length) {
58696                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58697                 if (!noImplicitAny) {
58698                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
58699                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
58700                     }
58701                     if (getThisTypeOfSignature(signature) === voidType) {
58702                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
58703                     }
58704                 }
58705                 return signature;
58706             }
58707             invocationError(node.expression, expressionType, 1 /* Construct */);
58708             return resolveErrorCall(node);
58709         }
58710         function typeHasProtectedAccessibleBase(target, type) {
58711             var baseTypes = getBaseTypes(type);
58712             if (!ts.length(baseTypes)) {
58713                 return false;
58714             }
58715             var firstBase = baseTypes[0];
58716             if (firstBase.flags & 2097152 /* Intersection */) {
58717                 var types = firstBase.types;
58718                 var mixinFlags = findMixins(types);
58719                 var i = 0;
58720                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
58721                     var intersectionMember = _a[_i];
58722                     // We want to ignore mixin ctors
58723                     if (!mixinFlags[i]) {
58724                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
58725                             if (intersectionMember.symbol === target) {
58726                                 return true;
58727                             }
58728                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
58729                                 return true;
58730                             }
58731                         }
58732                     }
58733                     i++;
58734                 }
58735                 return false;
58736             }
58737             if (firstBase.symbol === target) {
58738                 return true;
58739             }
58740             return typeHasProtectedAccessibleBase(target, firstBase);
58741         }
58742         function isConstructorAccessible(node, signature) {
58743             if (!signature || !signature.declaration) {
58744                 return true;
58745             }
58746             var declaration = signature.declaration;
58747             var modifiers = ts.getSelectedModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
58748             // (1) Public constructors and (2) constructor functions are always accessible.
58749             if (!modifiers || declaration.kind !== 162 /* Constructor */) {
58750                 return true;
58751             }
58752             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
58753             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
58754             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
58755             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
58756                 var containingClass = ts.getContainingClass(node);
58757                 if (containingClass && modifiers & 16 /* Protected */) {
58758                     var containingType = getTypeOfNode(containingClass);
58759                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
58760                         return true;
58761                     }
58762                 }
58763                 if (modifiers & 8 /* Private */) {
58764                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58765                 }
58766                 if (modifiers & 16 /* Protected */) {
58767                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
58768                 }
58769                 return false;
58770             }
58771             return true;
58772         }
58773         function invocationErrorDetails(apparentType, kind) {
58774             var errorInfo;
58775             var isCall = kind === 0 /* Call */;
58776             var awaitedType = getAwaitedType(apparentType);
58777             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
58778             if (apparentType.flags & 1048576 /* Union */) {
58779                 var types = apparentType.types;
58780                 var hasSignatures = false;
58781                 for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
58782                     var constituent = types_18[_i];
58783                     var signatures = getSignaturesOfType(constituent, kind);
58784                     if (signatures.length !== 0) {
58785                         hasSignatures = true;
58786                         if (errorInfo) {
58787                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
58788                             break;
58789                         }
58790                     }
58791                     else {
58792                         // Error on the first non callable constituent only
58793                         if (!errorInfo) {
58794                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58795                                 ts.Diagnostics.Type_0_has_no_call_signatures :
58796                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
58797                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58798                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
58799                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
58800                         }
58801                         if (hasSignatures) {
58802                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
58803                             break;
58804                         }
58805                     }
58806                 }
58807                 if (!hasSignatures) {
58808                     errorInfo = ts.chainDiagnosticMessages(
58809                     /* detials */ undefined, isCall ?
58810                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
58811                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
58812                 }
58813                 if (!errorInfo) {
58814                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58815                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
58816                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
58817                 }
58818             }
58819             else {
58820                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
58821                     ts.Diagnostics.Type_0_has_no_call_signatures :
58822                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
58823             }
58824             return {
58825                 messageChain: ts.chainDiagnosticMessages(errorInfo, isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable),
58826                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
58827             };
58828         }
58829         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
58830             var _a = invocationErrorDetails(apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
58831             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
58832             if (relatedInfo) {
58833                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
58834             }
58835             if (ts.isCallExpression(errorTarget.parent)) {
58836                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
58837                 diagnostic.start = start;
58838                 diagnostic.length = length_7;
58839             }
58840             diagnostics.add(diagnostic);
58841             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
58842         }
58843         function invocationErrorRecovery(apparentType, kind, diagnostic) {
58844             if (!apparentType.symbol) {
58845                 return;
58846             }
58847             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
58848             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
58849             //  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
58850             if (importNode && !ts.isImportCall(importNode)) {
58851                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
58852                 if (!sigs || !sigs.length)
58853                     return;
58854                 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));
58855             }
58856         }
58857         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
58858             var tagType = checkExpression(node.tag);
58859             var apparentType = getApparentType(tagType);
58860             if (apparentType === errorType) {
58861                 // Another error has already been reported
58862                 return resolveErrorCall(node);
58863             }
58864             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58865             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58866             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
58867                 return resolveUntypedCall(node);
58868             }
58869             if (!callSignatures.length) {
58870                 invocationError(node.tag, apparentType, 0 /* Call */);
58871                 return resolveErrorCall(node);
58872             }
58873             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
58874         }
58875         /**
58876          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
58877          */
58878         function getDiagnosticHeadMessageForDecoratorResolution(node) {
58879             switch (node.parent.kind) {
58880                 case 245 /* ClassDeclaration */:
58881                 case 214 /* ClassExpression */:
58882                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
58883                 case 156 /* Parameter */:
58884                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
58885                 case 159 /* PropertyDeclaration */:
58886                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
58887                 case 161 /* MethodDeclaration */:
58888                 case 163 /* GetAccessor */:
58889                 case 164 /* SetAccessor */:
58890                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
58891                 default:
58892                     return ts.Debug.fail();
58893             }
58894         }
58895         /**
58896          * Resolves a decorator as if it were a call expression.
58897          */
58898         function resolveDecorator(node, candidatesOutArray, checkMode) {
58899             var funcType = checkExpression(node.expression);
58900             var apparentType = getApparentType(funcType);
58901             if (apparentType === errorType) {
58902                 return resolveErrorCall(node);
58903             }
58904             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
58905             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
58906             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
58907                 return resolveUntypedCall(node);
58908             }
58909             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
58910                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
58911                 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);
58912                 return resolveErrorCall(node);
58913             }
58914             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
58915             if (!callSignatures.length) {
58916                 var errorDetails = invocationErrorDetails(apparentType, 0 /* Call */);
58917                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
58918                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
58919                 if (errorDetails.relatedMessage) {
58920                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
58921                 }
58922                 diagnostics.add(diag);
58923                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
58924                 return resolveErrorCall(node);
58925             }
58926             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
58927         }
58928         function createSignatureForJSXIntrinsic(node, result) {
58929             var namespace = getJsxNamespaceAt(node);
58930             var exports = namespace && getExportsOfSymbol(namespace);
58931             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
58932             // file would probably be preferable.
58933             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
58934             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
58935             var declaration = ts.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.createKeywordTypeNode(125 /* AnyKeyword */));
58936             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
58937             parameterSymbol.type = result;
58938             return createSignature(declaration, 
58939             /*typeParameters*/ undefined, 
58940             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
58941             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
58942         }
58943         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
58944             if (isJsxIntrinsicIdentifier(node.tagName)) {
58945                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
58946                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
58947                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
58948                 return fakeSignature;
58949             }
58950             var exprTypes = checkExpression(node.tagName);
58951             var apparentType = getApparentType(exprTypes);
58952             if (apparentType === errorType) {
58953                 return resolveErrorCall(node);
58954             }
58955             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
58956             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
58957                 return resolveUntypedCall(node);
58958             }
58959             if (signatures.length === 0) {
58960                 // We found no signatures at all, which is an error
58961                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
58962                 return resolveErrorCall(node);
58963             }
58964             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
58965         }
58966         /**
58967          * Sometimes, we have a decorator that could accept zero arguments,
58968          * but is receiving too many arguments as part of the decorator invocation.
58969          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
58970          */
58971         function isPotentiallyUncalledDecorator(decorator, signatures) {
58972             return signatures.length && ts.every(signatures, function (signature) {
58973                 return signature.minArgumentCount === 0 &&
58974                     !signatureHasRestParameter(signature) &&
58975                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
58976             });
58977         }
58978         function resolveSignature(node, candidatesOutArray, checkMode) {
58979             switch (node.kind) {
58980                 case 196 /* CallExpression */:
58981                     return resolveCallExpression(node, candidatesOutArray, checkMode);
58982                 case 197 /* NewExpression */:
58983                     return resolveNewExpression(node, candidatesOutArray, checkMode);
58984                 case 198 /* TaggedTemplateExpression */:
58985                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
58986                 case 157 /* Decorator */:
58987                     return resolveDecorator(node, candidatesOutArray, checkMode);
58988                 case 268 /* JsxOpeningElement */:
58989                 case 267 /* JsxSelfClosingElement */:
58990                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
58991             }
58992             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
58993         }
58994         /**
58995          * Resolve a signature of a given call-like expression.
58996          * @param node a call-like expression to try resolve a signature for
58997          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
58998          *                           the function will fill it up with appropriate candidate signatures
58999          * @return a signature of the call-like expression or undefined if one can't be found
59000          */
59001         function getResolvedSignature(node, candidatesOutArray, checkMode) {
59002             var links = getNodeLinks(node);
59003             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
59004             // However, it is possible that either candidatesOutArray was not passed in the first time,
59005             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
59006             // to correctly fill the candidatesOutArray.
59007             var cached = links.resolvedSignature;
59008             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
59009                 return cached;
59010             }
59011             links.resolvedSignature = resolvingSignature;
59012             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
59013             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
59014             // resolution should be deferred.
59015             if (result !== resolvingSignature) {
59016                 // If signature resolution originated in control flow type analysis (for example to compute the
59017                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
59018                 // types from the control flow analysis.
59019                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
59020             }
59021             return result;
59022         }
59023         /**
59024          * Indicates whether a declaration can be treated as a constructor in a JavaScript
59025          * file.
59026          */
59027         function isJSConstructor(node) {
59028             if (!node || !ts.isInJSFile(node)) {
59029                 return false;
59030             }
59031             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
59032                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
59033                     undefined;
59034             if (func) {
59035                 // If the node has a @class tag, treat it like a constructor.
59036                 if (ts.getJSDocClassTag(node))
59037                     return true;
59038                 // If the symbol of the node has members, treat it like a constructor.
59039                 var symbol = getSymbolOfNode(func);
59040                 return !!symbol && ts.hasEntries(symbol.members);
59041             }
59042             return false;
59043         }
59044         function mergeJSSymbols(target, source) {
59045             if (source) {
59046                 var links = getSymbolLinks(source);
59047                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has("" + getSymbolId(target))) {
59048                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
59049                     inferred.exports = inferred.exports || ts.createSymbolTable();
59050                     inferred.members = inferred.members || ts.createSymbolTable();
59051                     inferred.flags |= source.flags & 32 /* Class */;
59052                     if (ts.hasEntries(source.exports)) {
59053                         mergeSymbolTable(inferred.exports, source.exports);
59054                     }
59055                     if (ts.hasEntries(source.members)) {
59056                         mergeSymbolTable(inferred.members, source.members);
59057                     }
59058                     (links.inferredClassSymbol || (links.inferredClassSymbol = ts.createMap())).set("" + getSymbolId(inferred), inferred);
59059                     return inferred;
59060                 }
59061                 return links.inferredClassSymbol.get("" + getSymbolId(target));
59062             }
59063         }
59064         function getAssignedClassSymbol(decl) {
59065             var assignmentSymbol = decl && decl.parent &&
59066                 (ts.isFunctionDeclaration(decl) && getSymbolOfNode(decl) ||
59067                     ts.isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) ||
59068                     ts.isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent));
59069             var prototype = assignmentSymbol && assignmentSymbol.exports && assignmentSymbol.exports.get("prototype");
59070             var init = prototype && prototype.valueDeclaration && getAssignedJSPrototype(prototype.valueDeclaration);
59071             return init ? getSymbolOfNode(init) : undefined;
59072         }
59073         function getAssignedJSPrototype(node) {
59074             if (!node.parent) {
59075                 return false;
59076             }
59077             var parent = node.parent;
59078             while (parent && parent.kind === 194 /* PropertyAccessExpression */) {
59079                 parent = parent.parent;
59080             }
59081             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
59082                 var right = ts.getInitializerOfBinaryExpression(parent);
59083                 return ts.isObjectLiteralExpression(right) && right;
59084             }
59085         }
59086         /**
59087          * Syntactically and semantically checks a call or new expression.
59088          * @param node The call/new expression to be checked.
59089          * @returns On success, the expression's signature's return type. On failure, anyType.
59090          */
59091         function checkCallExpression(node, checkMode) {
59092             if (!checkGrammarTypeArguments(node, node.typeArguments))
59093                 checkGrammarArguments(node.arguments);
59094             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
59095             if (signature === resolvingSignature) {
59096                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
59097                 // returns a function type. We defer checking and return nonInferrableType.
59098                 return nonInferrableType;
59099             }
59100             if (node.expression.kind === 102 /* SuperKeyword */) {
59101                 return voidType;
59102             }
59103             if (node.kind === 197 /* NewExpression */) {
59104                 var declaration = signature.declaration;
59105                 if (declaration &&
59106                     declaration.kind !== 162 /* Constructor */ &&
59107                     declaration.kind !== 166 /* ConstructSignature */ &&
59108                     declaration.kind !== 171 /* ConstructorType */ &&
59109                     !ts.isJSDocConstructSignature(declaration) &&
59110                     !isJSConstructor(declaration)) {
59111                     // When resolved signature is a call signature (and not a construct signature) the result type is any
59112                     if (noImplicitAny) {
59113                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
59114                     }
59115                     return anyType;
59116                 }
59117             }
59118             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
59119             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
59120                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
59121             }
59122             var returnType = getReturnTypeOfSignature(signature);
59123             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
59124             // as a fresh unique symbol literal type.
59125             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
59126                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
59127             }
59128             if (node.kind === 196 /* CallExpression */ && node.parent.kind === 226 /* ExpressionStatement */ &&
59129                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
59130                 if (!ts.isDottedName(node.expression)) {
59131                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
59132                 }
59133                 else if (!getEffectsSignature(node)) {
59134                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
59135                     getTypeOfDottedName(node.expression, diagnostic);
59136                 }
59137             }
59138             if (ts.isInJSFile(node)) {
59139                 var decl = ts.getDeclarationOfExpando(node);
59140                 if (decl) {
59141                     var jsSymbol = getSymbolOfNode(decl);
59142                     if (jsSymbol && ts.hasEntries(jsSymbol.exports)) {
59143                         var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
59144                         jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
59145                         return getIntersectionType([returnType, jsAssignmentType]);
59146                     }
59147                 }
59148             }
59149             return returnType;
59150         }
59151         function isSymbolOrSymbolForCall(node) {
59152             if (!ts.isCallExpression(node))
59153                 return false;
59154             var left = node.expression;
59155             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
59156                 left = left.expression;
59157             }
59158             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
59159                 return false;
59160             }
59161             // make sure `Symbol` is the global symbol
59162             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
59163             if (!globalESSymbol) {
59164                 return false;
59165             }
59166             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
59167         }
59168         function checkImportCallExpression(node) {
59169             // Check grammar of dynamic import
59170             if (!checkGrammarArguments(node.arguments))
59171                 checkGrammarImportCallExpression(node);
59172             if (node.arguments.length === 0) {
59173                 return createPromiseReturnType(node, anyType);
59174             }
59175             var specifier = node.arguments[0];
59176             var specifierType = checkExpressionCached(specifier);
59177             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
59178             for (var i = 1; i < node.arguments.length; ++i) {
59179                 checkExpressionCached(node.arguments[i]);
59180             }
59181             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
59182                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
59183             }
59184             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
59185             var moduleSymbol = resolveExternalModuleName(node, specifier);
59186             if (moduleSymbol) {
59187                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
59188                 if (esModuleSymbol) {
59189                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
59190                 }
59191             }
59192             return createPromiseReturnType(node, anyType);
59193         }
59194         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
59195             if (allowSyntheticDefaultImports && type && type !== errorType) {
59196                 var synthType = type;
59197                 if (!synthType.syntheticType) {
59198                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
59199                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
59200                     if (hasSyntheticDefault) {
59201                         var memberTable = ts.createSymbolTable();
59202                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
59203                         newSymbol.nameType = getLiteralType("default");
59204                         newSymbol.target = resolveSymbol(symbol);
59205                         memberTable.set("default" /* Default */, newSymbol);
59206                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
59207                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
59208                         anonymousSymbol.type = defaultContainingObject;
59209                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
59210                     }
59211                     else {
59212                         synthType.syntheticType = type;
59213                     }
59214                 }
59215                 return synthType.syntheticType;
59216             }
59217             return type;
59218         }
59219         function isCommonJsRequire(node) {
59220             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
59221                 return false;
59222             }
59223             // Make sure require is not a local function
59224             if (!ts.isIdentifier(node.expression))
59225                 return ts.Debug.fail();
59226             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
59227             if (resolvedRequire === requireSymbol) {
59228                 return true;
59229             }
59230             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
59231             if (resolvedRequire.flags & 2097152 /* Alias */) {
59232                 return false;
59233             }
59234             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
59235                 ? 244 /* FunctionDeclaration */
59236                 : resolvedRequire.flags & 3 /* Variable */
59237                     ? 242 /* VariableDeclaration */
59238                     : 0 /* Unknown */;
59239             if (targetDeclarationKind !== 0 /* Unknown */) {
59240                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
59241                 // function/variable declaration should be ambient
59242                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
59243             }
59244             return false;
59245         }
59246         function checkTaggedTemplateExpression(node) {
59247             if (!checkGrammarTaggedTemplateChain(node))
59248                 checkGrammarTypeArguments(node, node.typeArguments);
59249             if (languageVersion < 2 /* ES2015 */) {
59250                 checkExternalEmitHelpers(node, 131072 /* MakeTemplateObject */);
59251             }
59252             return getReturnTypeOfSignature(getResolvedSignature(node));
59253         }
59254         function checkAssertion(node) {
59255             return checkAssertionWorker(node, node.type, node.expression);
59256         }
59257         function isValidConstAssertionArgument(node) {
59258             switch (node.kind) {
59259                 case 10 /* StringLiteral */:
59260                 case 14 /* NoSubstitutionTemplateLiteral */:
59261                 case 8 /* NumericLiteral */:
59262                 case 9 /* BigIntLiteral */:
59263                 case 106 /* TrueKeyword */:
59264                 case 91 /* FalseKeyword */:
59265                 case 192 /* ArrayLiteralExpression */:
59266                 case 193 /* ObjectLiteralExpression */:
59267                     return true;
59268                 case 200 /* ParenthesizedExpression */:
59269                     return isValidConstAssertionArgument(node.expression);
59270                 case 207 /* PrefixUnaryExpression */:
59271                     var op = node.operator;
59272                     var arg = node.operand;
59273                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
59274                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
59275                 case 194 /* PropertyAccessExpression */:
59276                 case 195 /* ElementAccessExpression */:
59277                     var expr = node.expression;
59278                     if (ts.isIdentifier(expr)) {
59279                         var symbol = getSymbolAtLocation(expr);
59280                         if (symbol && symbol.flags & 2097152 /* Alias */) {
59281                             symbol = resolveAlias(symbol);
59282                         }
59283                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
59284                     }
59285             }
59286             return false;
59287         }
59288         function checkAssertionWorker(errNode, type, expression, checkMode) {
59289             var exprType = checkExpression(expression, checkMode);
59290             if (ts.isConstTypeReference(type)) {
59291                 if (!isValidConstAssertionArgument(expression)) {
59292                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
59293                 }
59294                 return getRegularTypeOfLiteralType(exprType);
59295             }
59296             checkSourceElement(type);
59297             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
59298             var targetType = getTypeFromTypeNode(type);
59299             if (produceDiagnostics && targetType !== errorType) {
59300                 var widenedType = getWidenedType(exprType);
59301                 if (!isTypeComparableTo(targetType, widenedType)) {
59302                     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);
59303                 }
59304             }
59305             return targetType;
59306         }
59307         function checkNonNullChain(node) {
59308             var leftType = checkExpression(node.expression);
59309             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
59310             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
59311         }
59312         function checkNonNullAssertion(node) {
59313             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
59314                 getNonNullableType(checkExpression(node.expression));
59315         }
59316         function checkMetaProperty(node) {
59317             checkGrammarMetaProperty(node);
59318             if (node.keywordToken === 99 /* NewKeyword */) {
59319                 return checkNewTargetMetaProperty(node);
59320             }
59321             if (node.keywordToken === 96 /* ImportKeyword */) {
59322                 return checkImportMetaProperty(node);
59323             }
59324             return ts.Debug.assertNever(node.keywordToken);
59325         }
59326         function checkNewTargetMetaProperty(node) {
59327             var container = ts.getNewTargetContainer(node);
59328             if (!container) {
59329                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
59330                 return errorType;
59331             }
59332             else if (container.kind === 162 /* Constructor */) {
59333                 var symbol = getSymbolOfNode(container.parent);
59334                 return getTypeOfSymbol(symbol);
59335             }
59336             else {
59337                 var symbol = getSymbolOfNode(container);
59338                 return getTypeOfSymbol(symbol);
59339             }
59340         }
59341         function checkImportMetaProperty(node) {
59342             if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
59343                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_esnext_or_system);
59344             }
59345             var file = ts.getSourceFileOfNode(node);
59346             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
59347             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
59348             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
59349         }
59350         function getTypeOfParameter(symbol) {
59351             var type = getTypeOfSymbol(symbol);
59352             if (strictNullChecks) {
59353                 var declaration = symbol.valueDeclaration;
59354                 if (declaration && ts.hasInitializer(declaration)) {
59355                     return getOptionalType(type);
59356                 }
59357             }
59358             return type;
59359         }
59360         function getParameterNameAtPosition(signature, pos) {
59361             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59362             if (pos < paramCount) {
59363                 return signature.parameters[pos].escapedName;
59364             }
59365             var restParameter = signature.parameters[paramCount] || unknownSymbol;
59366             var restType = getTypeOfSymbol(restParameter);
59367             if (isTupleType(restType)) {
59368                 var associatedNames = restType.target.associatedNames;
59369                 var index = pos - paramCount;
59370                 return associatedNames && associatedNames[index] || restParameter.escapedName + "_" + index;
59371             }
59372             return restParameter.escapedName;
59373         }
59374         function getTypeAtPosition(signature, pos) {
59375             return tryGetTypeAtPosition(signature, pos) || anyType;
59376         }
59377         function tryGetTypeAtPosition(signature, pos) {
59378             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59379             if (pos < paramCount) {
59380                 return getTypeOfParameter(signature.parameters[pos]);
59381             }
59382             if (signatureHasRestParameter(signature)) {
59383                 // We want to return the value undefined for an out of bounds parameter position,
59384                 // so we need to check bounds here before calling getIndexedAccessType (which
59385                 // otherwise would return the type 'undefined').
59386                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
59387                 var index = pos - paramCount;
59388                 if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) {
59389                     return getIndexedAccessType(restType, getLiteralType(index));
59390                 }
59391             }
59392             return undefined;
59393         }
59394         function getRestTypeAtPosition(source, pos) {
59395             var paramCount = getParameterCount(source);
59396             var restType = getEffectiveRestType(source);
59397             var nonRestCount = paramCount - (restType ? 1 : 0);
59398             if (restType && pos === nonRestCount) {
59399                 return restType;
59400             }
59401             var types = [];
59402             var names = [];
59403             for (var i = pos; i < nonRestCount; i++) {
59404                 types.push(getTypeAtPosition(source, i));
59405                 names.push(getParameterNameAtPosition(source, i));
59406             }
59407             if (restType) {
59408                 types.push(getIndexedAccessType(restType, numberType));
59409                 names.push(getParameterNameAtPosition(source, nonRestCount));
59410             }
59411             var minArgumentCount = getMinArgumentCount(source);
59412             var minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos;
59413             return createTupleType(types, minLength, !!restType, /*readonly*/ false, names);
59414         }
59415         function getParameterCount(signature) {
59416             var length = signature.parameters.length;
59417             if (signatureHasRestParameter(signature)) {
59418                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
59419                 if (isTupleType(restType)) {
59420                     return length + getTypeArguments(restType).length - 1;
59421                 }
59422             }
59423             return length;
59424         }
59425         function getMinArgumentCount(signature, strongArityForUntypedJS) {
59426             if (signatureHasRestParameter(signature)) {
59427                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59428                 if (isTupleType(restType)) {
59429                     var minLength = restType.target.minLength;
59430                     if (minLength > 0) {
59431                         return signature.parameters.length - 1 + minLength;
59432                     }
59433                 }
59434             }
59435             if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
59436                 return 0;
59437             }
59438             return signature.minArgumentCount;
59439         }
59440         function hasEffectiveRestParameter(signature) {
59441             if (signatureHasRestParameter(signature)) {
59442                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59443                 return !isTupleType(restType) || restType.target.hasRestElement;
59444             }
59445             return false;
59446         }
59447         function getEffectiveRestType(signature) {
59448             if (signatureHasRestParameter(signature)) {
59449                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
59450                 return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType;
59451             }
59452             return undefined;
59453         }
59454         function getNonArrayRestType(signature) {
59455             var restType = getEffectiveRestType(signature);
59456             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
59457         }
59458         function getTypeOfFirstParameterOfSignature(signature) {
59459             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
59460         }
59461         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
59462             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
59463         }
59464         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
59465             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59466             for (var i = 0; i < len; i++) {
59467                 var declaration = signature.parameters[i].valueDeclaration;
59468                 if (declaration.type) {
59469                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
59470                     if (typeNode) {
59471                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
59472                     }
59473                 }
59474             }
59475             var restType = getEffectiveRestType(context);
59476             if (restType && restType.flags & 262144 /* TypeParameter */) {
59477                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
59478                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
59479                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
59480                 assignContextualParameterTypes(signature, instantiatedContext);
59481                 // We then infer from a tuple type representing the parameters that correspond to the contextual
59482                 // rest parameter.
59483                 var restPos = getParameterCount(context) - 1;
59484                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
59485             }
59486         }
59487         function assignContextualParameterTypes(signature, context) {
59488             signature.typeParameters = context.typeParameters;
59489             if (context.thisParameter) {
59490                 var parameter = signature.thisParameter;
59491                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
59492                     if (!parameter) {
59493                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
59494                     }
59495                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
59496                 }
59497             }
59498             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
59499             for (var i = 0; i < len; i++) {
59500                 var parameter = signature.parameters[i];
59501                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59502                     var contextualParameterType = tryGetTypeAtPosition(context, i);
59503                     assignParameterType(parameter, contextualParameterType);
59504                 }
59505             }
59506             if (signatureHasRestParameter(signature)) {
59507                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
59508                 var parameter = ts.last(signature.parameters);
59509                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
59510                     var contextualParameterType = getRestTypeAtPosition(context, len);
59511                     assignParameterType(parameter, contextualParameterType);
59512                 }
59513             }
59514         }
59515         function assignNonContextualParameterTypes(signature) {
59516             if (signature.thisParameter) {
59517                 assignParameterType(signature.thisParameter);
59518             }
59519             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
59520                 var parameter = _a[_i];
59521                 assignParameterType(parameter);
59522             }
59523         }
59524         function assignParameterType(parameter, type) {
59525             var links = getSymbolLinks(parameter);
59526             if (!links.type) {
59527                 var declaration = parameter.valueDeclaration;
59528                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
59529                 if (declaration.name.kind !== 75 /* Identifier */) {
59530                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
59531                     if (links.type === unknownType) {
59532                         links.type = getTypeFromBindingPattern(declaration.name);
59533                     }
59534                     assignBindingElementTypes(declaration.name);
59535                 }
59536             }
59537         }
59538         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
59539         // the destructured type into the contained binding elements.
59540         function assignBindingElementTypes(pattern) {
59541             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
59542                 var element = _a[_i];
59543                 if (!ts.isOmittedExpression(element)) {
59544                     if (element.name.kind === 75 /* Identifier */) {
59545                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
59546                     }
59547                     else {
59548                         assignBindingElementTypes(element.name);
59549                     }
59550                 }
59551             }
59552         }
59553         function createPromiseType(promisedType) {
59554             // creates a `Promise<T>` type where `T` is the promisedType argument
59555             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
59556             if (globalPromiseType !== emptyGenericType) {
59557                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59558                 promisedType = getAwaitedType(promisedType) || unknownType;
59559                 return createTypeReference(globalPromiseType, [promisedType]);
59560             }
59561             return unknownType;
59562         }
59563         function createPromiseLikeType(promisedType) {
59564             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
59565             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
59566             if (globalPromiseLikeType !== emptyGenericType) {
59567                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
59568                 promisedType = getAwaitedType(promisedType) || unknownType;
59569                 return createTypeReference(globalPromiseLikeType, [promisedType]);
59570             }
59571             return unknownType;
59572         }
59573         function createPromiseReturnType(func, promisedType) {
59574             var promiseType = createPromiseType(promisedType);
59575             if (promiseType === unknownType) {
59576                 error(func, ts.isImportCall(func) ?
59577                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
59578                     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);
59579                 return errorType;
59580             }
59581             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
59582                 error(func, ts.isImportCall(func) ?
59583                     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 :
59584                     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);
59585             }
59586             return promiseType;
59587         }
59588         function getReturnTypeFromBody(func, checkMode) {
59589             if (!func.body) {
59590                 return errorType;
59591             }
59592             var functionFlags = ts.getFunctionFlags(func);
59593             var isAsync = (functionFlags & 2 /* Async */) !== 0;
59594             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
59595             var returnType;
59596             var yieldType;
59597             var nextType;
59598             var fallbackReturnType = voidType;
59599             if (func.body.kind !== 223 /* Block */) { // Async or normal arrow function
59600                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59601                 if (isAsync) {
59602                     // From within an async function you can return either a non-promise value or a promise. Any
59603                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59604                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
59605                     // the native Promise<T> type later in this function.
59606                     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);
59607                 }
59608             }
59609             else if (isGenerator) { // Generator or AsyncGenerator function
59610                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
59611                 if (!returnTypes) {
59612                     fallbackReturnType = neverType;
59613                 }
59614                 else if (returnTypes.length > 0) {
59615                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
59616                 }
59617                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
59618                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
59619                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
59620             }
59621             else { // Async or normal function
59622                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
59623                 if (!types) {
59624                     // For an async function, the return type will not be never, but rather a Promise for never.
59625                     return functionFlags & 2 /* Async */
59626                         ? createPromiseReturnType(func, neverType) // Async function
59627                         : neverType; // Normal function
59628                 }
59629                 if (types.length === 0) {
59630                     // For an async function, the return type will not be void, but rather a Promise for void.
59631                     return functionFlags & 2 /* Async */
59632                         ? createPromiseReturnType(func, voidType) // Async function
59633                         : voidType; // Normal function
59634                 }
59635                 // Return a union of the return expression types.
59636                 returnType = getUnionType(types, 2 /* Subtype */);
59637             }
59638             if (returnType || yieldType || nextType) {
59639                 if (yieldType)
59640                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
59641                 if (returnType)
59642                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
59643                 if (nextType)
59644                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
59645                 if (returnType && isUnitType(returnType) ||
59646                     yieldType && isUnitType(yieldType) ||
59647                     nextType && isUnitType(nextType)) {
59648                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
59649                     var contextualType = !contextualSignature ? undefined :
59650                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
59651                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
59652                     if (isGenerator) {
59653                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
59654                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
59655                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
59656                     }
59657                     else {
59658                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
59659                     }
59660                 }
59661                 if (yieldType)
59662                     yieldType = getWidenedType(yieldType);
59663                 if (returnType)
59664                     returnType = getWidenedType(returnType);
59665                 if (nextType)
59666                     nextType = getWidenedType(nextType);
59667             }
59668             if (isGenerator) {
59669                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
59670             }
59671             else {
59672                 // From within an async function you can return either a non-promise value or a promise. Any
59673                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59674                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
59675                 return isAsync
59676                     ? createPromiseType(returnType || fallbackReturnType)
59677                     : returnType || fallbackReturnType;
59678             }
59679         }
59680         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
59681             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
59682             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
59683             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
59684             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
59685             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
59686             if (globalGeneratorType === emptyGenericType) {
59687                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
59688                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
59689                 // nextType.
59690                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
59691                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
59692                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
59693                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
59694                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
59695                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
59696                     if (globalType !== emptyGenericType) {
59697                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
59698                     }
59699                     // The global IterableIterator type doesn't exist, so report an error
59700                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
59701                     return emptyObjectType;
59702                 }
59703                 // The global Generator type doesn't exist, so report an error
59704                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
59705                 return emptyObjectType;
59706             }
59707             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
59708         }
59709         function checkAndAggregateYieldOperandTypes(func, checkMode) {
59710             var yieldTypes = [];
59711             var nextTypes = [];
59712             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
59713             ts.forEachYieldExpression(func.body, function (yieldExpression) {
59714                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
59715                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
59716                 var nextType;
59717                 if (yieldExpression.asteriskToken) {
59718                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
59719                     nextType = iterationTypes && iterationTypes.nextType;
59720                 }
59721                 else {
59722                     nextType = getContextualType(yieldExpression);
59723                 }
59724                 if (nextType)
59725                     ts.pushIfUnique(nextTypes, nextType);
59726             });
59727             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
59728         }
59729         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
59730             var errorNode = node.expression || node;
59731             // A `yield*` expression effectively yields everything that its operand yields
59732             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
59733             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
59734                 ? 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
59735                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
59736         }
59737         /**
59738          * Collect the TypeFacts learned from a typeof switch with
59739          * total clauses `witnesses`, and the active clause ranging
59740          * from `start` to `end`. Parameter `hasDefault` denotes
59741          * whether the active clause contains a default clause.
59742          */
59743         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
59744             var facts = 0 /* None */;
59745             // When in the default we only collect inequality facts
59746             // because default is 'in theory' a set of infinite
59747             // equalities.
59748             if (hasDefault) {
59749                 // Value is not equal to any types after the active clause.
59750                 for (var i = end; i < witnesses.length; i++) {
59751                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59752                 }
59753                 // Remove inequalities for types that appear in the
59754                 // active clause because they appear before other
59755                 // types collected so far.
59756                 for (var i = start; i < end; i++) {
59757                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
59758                 }
59759                 // Add inequalities for types before the active clause unconditionally.
59760                 for (var i = 0; i < start; i++) {
59761                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
59762                 }
59763             }
59764             // When in an active clause without default the set of
59765             // equalities is finite.
59766             else {
59767                 // Add equalities for all types in the active clause.
59768                 for (var i = start; i < end; i++) {
59769                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
59770                 }
59771                 // Remove equalities for types that appear before the
59772                 // active clause.
59773                 for (var i = 0; i < start; i++) {
59774                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
59775                 }
59776             }
59777             return facts;
59778         }
59779         function isExhaustiveSwitchStatement(node) {
59780             var links = getNodeLinks(node);
59781             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
59782         }
59783         function computeExhaustiveSwitchStatement(node) {
59784             if (node.expression.kind === 204 /* TypeOfExpression */) {
59785                 var operandType = getTypeOfExpression(node.expression.expression);
59786                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
59787                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
59788                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
59789                 var type_3 = getBaseConstraintOfType(operandType) || operandType;
59790                 return !!(filterType(type_3, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
59791             }
59792             var type = getTypeOfExpression(node.expression);
59793             if (!isLiteralType(type)) {
59794                 return false;
59795             }
59796             var switchTypes = getSwitchClauseTypes(node);
59797             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
59798                 return false;
59799             }
59800             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
59801         }
59802         function functionHasImplicitReturn(func) {
59803             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
59804         }
59805         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
59806         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
59807             var functionFlags = ts.getFunctionFlags(func);
59808             var aggregatedTypes = [];
59809             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
59810             var hasReturnOfTypeNever = false;
59811             ts.forEachReturnStatement(func.body, function (returnStatement) {
59812                 var expr = returnStatement.expression;
59813                 if (expr) {
59814                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
59815                     if (functionFlags & 2 /* Async */) {
59816                         // From within an async function you can return either a non-promise value or a promise. Any
59817                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
59818                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
59819                         // the native Promise<T> type by the caller.
59820                         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);
59821                     }
59822                     if (type.flags & 131072 /* Never */) {
59823                         hasReturnOfTypeNever = true;
59824                     }
59825                     ts.pushIfUnique(aggregatedTypes, type);
59826                 }
59827                 else {
59828                     hasReturnWithNoExpression = true;
59829                 }
59830             });
59831             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
59832                 return undefined;
59833             }
59834             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
59835                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
59836                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
59837                 ts.pushIfUnique(aggregatedTypes, undefinedType);
59838             }
59839             return aggregatedTypes;
59840         }
59841         function mayReturnNever(func) {
59842             switch (func.kind) {
59843                 case 201 /* FunctionExpression */:
59844                 case 202 /* ArrowFunction */:
59845                     return true;
59846                 case 161 /* MethodDeclaration */:
59847                     return func.parent.kind === 193 /* ObjectLiteralExpression */;
59848                 default:
59849                     return false;
59850             }
59851         }
59852         /**
59853          * TypeScript Specification 1.0 (6.3) - July 2014
59854          *   An explicitly typed function whose return type isn't the Void type,
59855          *   the Any type, or a union type containing the Void or Any type as a constituent
59856          *   must have at least one return statement somewhere in its body.
59857          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
59858          *
59859          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
59860          */
59861         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
59862             if (!produceDiagnostics) {
59863                 return;
59864             }
59865             var functionFlags = ts.getFunctionFlags(func);
59866             var type = returnType && unwrapReturnType(returnType, functionFlags);
59867             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
59868             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
59869                 return;
59870             }
59871             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
59872             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
59873             if (func.kind === 160 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 223 /* Block */ || !functionHasImplicitReturn(func)) {
59874                 return;
59875             }
59876             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
59877             if (type && type.flags & 131072 /* Never */) {
59878                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
59879             }
59880             else if (type && !hasExplicitReturn) {
59881                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
59882                 // this function does not conform to the specification.
59883                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
59884                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
59885             }
59886             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
59887                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
59888             }
59889             else if (compilerOptions.noImplicitReturns) {
59890                 if (!type) {
59891                     // If return type annotation is omitted check if function has any explicit return statements.
59892                     // If it does not have any - its inferred return type is void - don't do any checks.
59893                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
59894                     if (!hasExplicitReturn) {
59895                         return;
59896                     }
59897                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
59898                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
59899                         return;
59900                     }
59901                 }
59902                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
59903             }
59904         }
59905         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59906             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59907             checkNodeDeferred(node);
59908             // The identityMapper object is used to indicate that function expressions are wildcards
59909             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
59910                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
59911                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
59912                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
59913                     var contextualSignature = getContextualSignature(node);
59914                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
59915                         var links = getNodeLinks(node);
59916                         if (links.contextFreeType) {
59917                             return links.contextFreeType;
59918                         }
59919                         var returnType = getReturnTypeFromBody(node, checkMode);
59920                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
59921                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
59922                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
59923                         return links.contextFreeType = returnOnlyType;
59924                     }
59925                 }
59926                 return anyFunctionType;
59927             }
59928             // Grammar checking
59929             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
59930             if (!hasGrammarError && node.kind === 201 /* FunctionExpression */) {
59931                 checkGrammarForGenerator(node);
59932             }
59933             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
59934             return getTypeOfSymbol(getSymbolOfNode(node));
59935         }
59936         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
59937             var links = getNodeLinks(node);
59938             // Check if function expression is contextually typed and assign parameter types if so.
59939             if (!(links.flags & 1024 /* ContextChecked */)) {
59940                 var contextualSignature = getContextualSignature(node);
59941                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
59942                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
59943                 // already assigned contextual types.
59944                 if (!(links.flags & 1024 /* ContextChecked */)) {
59945                     links.flags |= 1024 /* ContextChecked */;
59946                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
59947                     if (!signature) {
59948                         return;
59949                     }
59950                     if (isContextSensitive(node)) {
59951                         if (contextualSignature) {
59952                             var inferenceContext = getInferenceContext(node);
59953                             if (checkMode && checkMode & 2 /* Inferential */) {
59954                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
59955                             }
59956                             var instantiatedContextualSignature = inferenceContext ?
59957                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
59958                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
59959                         }
59960                         else {
59961                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
59962                             assignNonContextualParameterTypes(signature);
59963                         }
59964                     }
59965                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
59966                         var returnType = getReturnTypeFromBody(node, checkMode);
59967                         if (!signature.resolvedReturnType) {
59968                             signature.resolvedReturnType = returnType;
59969                         }
59970                     }
59971                     checkSignatureDeclaration(node);
59972                 }
59973             }
59974         }
59975         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
59976             ts.Debug.assert(node.kind !== 161 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
59977             var functionFlags = ts.getFunctionFlags(node);
59978             var returnType = getReturnTypeFromAnnotation(node);
59979             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
59980             if (node.body) {
59981                 if (!ts.getEffectiveReturnTypeNode(node)) {
59982                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
59983                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
59984                     // of a function. Because checking of function expression bodies is deferred, there was never an
59985                     // appropriate time to do this during the main walk of the file (see the comment at the top of
59986                     // checkFunctionExpressionBodies). So it must be done now.
59987                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
59988                 }
59989                 if (node.body.kind === 223 /* Block */) {
59990                     checkSourceElement(node.body);
59991                 }
59992                 else {
59993                     // From within an async function you can return either a non-promise value or a promise. Any
59994                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
59995                     // should not be checking assignability of a promise to the return type. Instead, we need to
59996                     // check assignability of the awaited type of the expression body against the promised type of
59997                     // its return type annotation.
59998                     var exprType = checkExpression(node.body);
59999                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
60000                     if (returnOrPromisedType) {
60001                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
60002                             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);
60003                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
60004                         }
60005                         else { // Normal function
60006                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
60007                         }
60008                     }
60009                 }
60010             }
60011         }
60012         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
60013             if (isAwaitValid === void 0) { isAwaitValid = false; }
60014             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
60015                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
60016                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
60017                 return false;
60018             }
60019             return true;
60020         }
60021         function isReadonlyAssignmentDeclaration(d) {
60022             if (!ts.isCallExpression(d)) {
60023                 return false;
60024             }
60025             if (!ts.isBindableObjectDefinePropertyCall(d)) {
60026                 return false;
60027             }
60028             var objectLitType = checkExpressionCached(d.arguments[2]);
60029             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
60030             if (valueType) {
60031                 var writableProp = getPropertyOfType(objectLitType, "writable");
60032                 var writableType = writableProp && getTypeOfSymbol(writableProp);
60033                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
60034                     return true;
60035                 }
60036                 // We include this definition whereupon we walk back and check the type at the declaration because
60037                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
60038                 // argument types, should the type be contextualized by the call itself.
60039                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
60040                     var initializer = writableProp.valueDeclaration.initializer;
60041                     var rawOriginalType = checkExpression(initializer);
60042                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
60043                         return true;
60044                     }
60045                 }
60046                 return false;
60047             }
60048             var setProp = getPropertyOfType(objectLitType, "set");
60049             return !setProp;
60050         }
60051         function isReadonlySymbol(symbol) {
60052             // The following symbols are considered read-only:
60053             // Properties with a 'readonly' modifier
60054             // Variables declared with 'const'
60055             // Get accessors without matching set accessors
60056             // Enum members
60057             // Object.defineProperty assignments with writable false or no setter
60058             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
60059             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
60060                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
60061                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
60062                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
60063                 symbol.flags & 8 /* EnumMember */ ||
60064                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
60065         }
60066         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
60067             var _a, _b;
60068             if (assignmentKind === 0 /* None */) {
60069                 // no assigment means it doesn't matter whether the entity is readonly
60070                 return false;
60071             }
60072             if (isReadonlySymbol(symbol)) {
60073                 // Allow assignments to readonly properties within constructors of the same class declaration.
60074                 if (symbol.flags & 4 /* Property */ &&
60075                     ts.isAccessExpression(expr) &&
60076                     expr.expression.kind === 104 /* ThisKeyword */) {
60077                     // Look for if this is the constructor for the class that `symbol` is a property of.
60078                     var ctor = ts.getContainingFunction(expr);
60079                     if (!(ctor && ctor.kind === 162 /* Constructor */)) {
60080                         return true;
60081                     }
60082                     if (symbol.valueDeclaration) {
60083                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
60084                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
60085                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
60086                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
60087                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
60088                         var isWriteableSymbol = isLocalPropertyDeclaration
60089                             || isLocalParameterProperty
60090                             || isLocalThisPropertyAssignment
60091                             || isLocalThisPropertyAssignmentConstructorFunction;
60092                         return !isWriteableSymbol;
60093                     }
60094                 }
60095                 return true;
60096             }
60097             if (ts.isAccessExpression(expr)) {
60098                 // references through namespace import should be readonly
60099                 var node = ts.skipParentheses(expr.expression);
60100                 if (node.kind === 75 /* Identifier */) {
60101                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
60102                     if (symbol_2.flags & 2097152 /* Alias */) {
60103                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
60104                         return !!declaration && declaration.kind === 256 /* NamespaceImport */;
60105                     }
60106                 }
60107             }
60108             return false;
60109         }
60110         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
60111             // References are combinations of identifiers, parentheses, and property accesses.
60112             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
60113             if (node.kind !== 75 /* Identifier */ && !ts.isAccessExpression(node)) {
60114                 error(expr, invalidReferenceMessage);
60115                 return false;
60116             }
60117             if (node.flags & 32 /* OptionalChain */) {
60118                 error(expr, invalidOptionalChainMessage);
60119                 return false;
60120             }
60121             return true;
60122         }
60123         function checkDeleteExpression(node) {
60124             checkExpression(node.expression);
60125             var expr = ts.skipParentheses(node.expression);
60126             if (!ts.isAccessExpression(expr)) {
60127                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
60128                 return booleanType;
60129             }
60130             // eslint-disable-next-line
60131             if (expr.kind === 194 /* PropertyAccessExpression */ && ts.isPrivateIdentifier(expr.name)) {
60132                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
60133             }
60134             var links = getNodeLinks(expr);
60135             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
60136             if (symbol && isReadonlySymbol(symbol)) {
60137                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
60138             }
60139             return booleanType;
60140         }
60141         function checkTypeOfExpression(node) {
60142             checkExpression(node.expression);
60143             return typeofType;
60144         }
60145         function checkVoidExpression(node) {
60146             checkExpression(node.expression);
60147             return undefinedWideningType;
60148         }
60149         function isTopLevelAwait(node) {
60150             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ true);
60151             return ts.isSourceFile(container);
60152         }
60153         function checkAwaitExpression(node) {
60154             // Grammar checking
60155             if (produceDiagnostics) {
60156                 if (!(node.flags & 32768 /* AwaitContext */)) {
60157                     if (isTopLevelAwait(node)) {
60158                         var sourceFile = ts.getSourceFileOfNode(node);
60159                         if (!hasParseDiagnostics(sourceFile)) {
60160                             var span = void 0;
60161                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
60162                                 if (!span)
60163                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60164                                 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);
60165                                 diagnostics.add(diagnostic);
60166                             }
60167                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
60168                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60169                                 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);
60170                                 diagnostics.add(diagnostic);
60171                             }
60172                         }
60173                     }
60174                     else {
60175                         // use of 'await' in non-async function
60176                         var sourceFile = ts.getSourceFileOfNode(node);
60177                         if (!hasParseDiagnostics(sourceFile)) {
60178                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
60179                             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);
60180                             var func = ts.getContainingFunction(node);
60181                             if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
60182                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
60183                                 ts.addRelatedInfo(diagnostic, relatedInfo);
60184                             }
60185                             diagnostics.add(diagnostic);
60186                         }
60187                     }
60188                 }
60189                 if (isInParameterInitializerBeforeContainingFunction(node)) {
60190                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
60191                 }
60192             }
60193             var operandType = checkExpression(node.expression);
60194             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);
60195             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
60196                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
60197             }
60198             return awaitedType;
60199         }
60200         function checkPrefixUnaryExpression(node) {
60201             var operandType = checkExpression(node.operand);
60202             if (operandType === silentNeverType) {
60203                 return silentNeverType;
60204             }
60205             switch (node.operand.kind) {
60206                 case 8 /* NumericLiteral */:
60207                     switch (node.operator) {
60208                         case 40 /* MinusToken */:
60209                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
60210                         case 39 /* PlusToken */:
60211                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
60212                     }
60213                     break;
60214                 case 9 /* BigIntLiteral */:
60215                     if (node.operator === 40 /* MinusToken */) {
60216                         return getFreshTypeOfLiteralType(getLiteralType({
60217                             negative: true,
60218                             base10Value: ts.parsePseudoBigInt(node.operand.text)
60219                         }));
60220                     }
60221             }
60222             switch (node.operator) {
60223                 case 39 /* PlusToken */:
60224                 case 40 /* MinusToken */:
60225                 case 54 /* TildeToken */:
60226                     checkNonNullType(operandType, node.operand);
60227                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
60228                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
60229                     }
60230                     if (node.operator === 39 /* PlusToken */) {
60231                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60232                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
60233                         }
60234                         return numberType;
60235                     }
60236                     return getUnaryResultType(operandType);
60237                 case 53 /* ExclamationToken */:
60238                     checkTruthinessExpression(node.operand);
60239                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
60240                     return facts === 4194304 /* Truthy */ ? falseType :
60241                         facts === 8388608 /* Falsy */ ? trueType :
60242                             booleanType;
60243                 case 45 /* PlusPlusToken */:
60244                 case 46 /* MinusMinusToken */:
60245                     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);
60246                     if (ok) {
60247                         // run check only if former checks succeeded to avoid reporting cascading errors
60248                         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);
60249                     }
60250                     return getUnaryResultType(operandType);
60251             }
60252             return errorType;
60253         }
60254         function checkPostfixUnaryExpression(node) {
60255             var operandType = checkExpression(node.operand);
60256             if (operandType === silentNeverType) {
60257                 return silentNeverType;
60258             }
60259             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);
60260             if (ok) {
60261                 // run check only if former checks succeeded to avoid reporting cascading errors
60262                 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);
60263             }
60264             return getUnaryResultType(operandType);
60265         }
60266         function getUnaryResultType(operandType) {
60267             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
60268                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
60269                     ? numberOrBigIntType
60270                     : bigintType;
60271             }
60272             // If it's not a bigint type, implicit coercion will result in a number
60273             return numberType;
60274         }
60275         // Return true if type might be of the given kind. A union or intersection type might be of a given
60276         // kind if at least one constituent type is of the given kind.
60277         function maybeTypeOfKind(type, kind) {
60278             if (type.flags & kind) {
60279                 return true;
60280             }
60281             if (type.flags & 3145728 /* UnionOrIntersection */) {
60282                 var types = type.types;
60283                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
60284                     var t = types_19[_i];
60285                     if (maybeTypeOfKind(t, kind)) {
60286                         return true;
60287                     }
60288                 }
60289             }
60290             return false;
60291         }
60292         function isTypeAssignableToKind(source, kind, strict) {
60293             if (source.flags & kind) {
60294                 return true;
60295             }
60296             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
60297                 return false;
60298             }
60299             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
60300                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
60301                 !!(kind & 132 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
60302                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
60303                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
60304                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
60305                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
60306                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
60307                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
60308                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
60309         }
60310         function allTypesAssignableToKind(source, kind, strict) {
60311             return source.flags & 1048576 /* Union */ ?
60312                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
60313                 isTypeAssignableToKind(source, kind, strict);
60314         }
60315         function isConstEnumObjectType(type) {
60316             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
60317         }
60318         function isConstEnumSymbol(symbol) {
60319             return (symbol.flags & 128 /* ConstEnum */) !== 0;
60320         }
60321         function checkInstanceOfExpression(left, right, leftType, rightType) {
60322             if (leftType === silentNeverType || rightType === silentNeverType) {
60323                 return silentNeverType;
60324             }
60325             // TypeScript 1.0 spec (April 2014): 4.15.4
60326             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
60327             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
60328             // The result is always of the Boolean primitive type.
60329             // NOTE: do not raise error if leftType is unknown as related error was already reported
60330             if (!isTypeAny(leftType) &&
60331                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
60332                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60333             }
60334             // NOTE: do not raise error if right is unknown as related error was already reported
60335             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
60336                 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);
60337             }
60338             return booleanType;
60339         }
60340         function checkInExpression(left, right, leftType, rightType) {
60341             if (leftType === silentNeverType || rightType === silentNeverType) {
60342                 return silentNeverType;
60343             }
60344             leftType = checkNonNullType(leftType, left);
60345             rightType = checkNonNullType(rightType, right);
60346             // TypeScript 1.0 spec (April 2014): 4.15.5
60347             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
60348             // and the right operand to be of type Any, an object type, or a type parameter type.
60349             // The result is always of the Boolean primitive type.
60350             if (!(isTypeComparableTo(leftType, stringType) || isTypeAssignableToKind(leftType, 296 /* NumberLike */ | 12288 /* ESSymbolLike */))) {
60351                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
60352             }
60353             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
60354                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
60355             }
60356             return booleanType;
60357         }
60358         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
60359             var properties = node.properties;
60360             if (strictNullChecks && properties.length === 0) {
60361                 return checkNonNullType(sourceType, node);
60362             }
60363             for (var i = 0; i < properties.length; i++) {
60364                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
60365             }
60366             return sourceType;
60367         }
60368         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
60369         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
60370             if (rightIsThis === void 0) { rightIsThis = false; }
60371             var properties = node.properties;
60372             var property = properties[propertyIndex];
60373             if (property.kind === 281 /* PropertyAssignment */ || property.kind === 282 /* ShorthandPropertyAssignment */) {
60374                 var name = property.name;
60375                 var exprType = getLiteralTypeFromPropertyName(name);
60376                 if (isTypeUsableAsPropertyName(exprType)) {
60377                     var text = getPropertyNameFromType(exprType);
60378                     var prop = getPropertyOfType(objectLiteralType, text);
60379                     if (prop) {
60380                         markPropertyAsReferenced(prop, property, rightIsThis);
60381                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
60382                     }
60383                 }
60384                 var elementType = getIndexedAccessType(objectLiteralType, exprType, name);
60385                 var type = getFlowTypeOfDestructuring(property, elementType);
60386                 return checkDestructuringAssignment(property.kind === 282 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
60387             }
60388             else if (property.kind === 283 /* SpreadAssignment */) {
60389                 if (propertyIndex < properties.length - 1) {
60390                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60391                 }
60392                 else {
60393                     if (languageVersion < 99 /* ESNext */) {
60394                         checkExternalEmitHelpers(property, 4 /* Rest */);
60395                     }
60396                     var nonRestNames = [];
60397                     if (allProperties) {
60398                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
60399                             var otherProperty = allProperties_1[_i];
60400                             if (!ts.isSpreadAssignment(otherProperty)) {
60401                                 nonRestNames.push(otherProperty.name);
60402                             }
60403                         }
60404                     }
60405                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
60406                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60407                     return checkDestructuringAssignment(property.expression, type);
60408                 }
60409             }
60410             else {
60411                 error(property, ts.Diagnostics.Property_assignment_expected);
60412             }
60413         }
60414         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
60415             var elements = node.elements;
60416             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
60417                 checkExternalEmitHelpers(node, 512 /* Read */);
60418             }
60419             // This elementType will be used if the specific property corresponding to this index is not
60420             // present (aka the tuple element property). This call also checks that the parentType is in
60421             // fact an iterable or array (depending on target language).
60422             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType;
60423             for (var i = 0; i < elements.length; i++) {
60424                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, elementType, checkMode);
60425             }
60426             return sourceType;
60427         }
60428         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
60429             var elements = node.elements;
60430             var element = elements[elementIndex];
60431             if (element.kind !== 215 /* OmittedExpression */) {
60432                 if (element.kind !== 213 /* SpreadElement */) {
60433                     var indexType = getLiteralType(elementIndex);
60434                     if (isArrayLikeType(sourceType)) {
60435                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
60436                         // when the element is a SyntaxKind.ElementAccessExpression.
60437                         var accessFlags = hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0;
60438                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, createSyntheticExpression(element, indexType), accessFlags) || errorType;
60439                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
60440                         var type = getFlowTypeOfDestructuring(element, assignedType);
60441                         return checkDestructuringAssignment(element, type, checkMode);
60442                     }
60443                     return checkDestructuringAssignment(element, elementType, checkMode);
60444                 }
60445                 if (elementIndex < elements.length - 1) {
60446                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
60447                 }
60448                 else {
60449                     var restExpression = element.expression;
60450                     if (restExpression.kind === 209 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
60451                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
60452                     }
60453                     else {
60454                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
60455                         var type = everyType(sourceType, isTupleType) ?
60456                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
60457                             createArrayType(elementType);
60458                         return checkDestructuringAssignment(restExpression, type, checkMode);
60459                     }
60460                 }
60461             }
60462             return undefined;
60463         }
60464         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
60465             var target;
60466             if (exprOrAssignment.kind === 282 /* ShorthandPropertyAssignment */) {
60467                 var prop = exprOrAssignment;
60468                 if (prop.objectAssignmentInitializer) {
60469                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
60470                     // undefined from the final type.
60471                     if (strictNullChecks &&
60472                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
60473                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
60474                     }
60475                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
60476                 }
60477                 target = exprOrAssignment.name;
60478             }
60479             else {
60480                 target = exprOrAssignment;
60481             }
60482             if (target.kind === 209 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
60483                 checkBinaryExpression(target, checkMode);
60484                 target = target.left;
60485             }
60486             if (target.kind === 193 /* ObjectLiteralExpression */) {
60487                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
60488             }
60489             if (target.kind === 192 /* ArrayLiteralExpression */) {
60490                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
60491             }
60492             return checkReferenceAssignment(target, sourceType, checkMode);
60493         }
60494         function checkReferenceAssignment(target, sourceType, checkMode) {
60495             var targetType = checkExpression(target, checkMode);
60496             var error = target.parent.kind === 283 /* SpreadAssignment */ ?
60497                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
60498                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
60499             var optionalError = target.parent.kind === 283 /* SpreadAssignment */ ?
60500                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
60501                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
60502             if (checkReferenceExpression(target, error, optionalError)) {
60503                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
60504             }
60505             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
60506                 checkExternalEmitHelpers(target.parent, 524288 /* ClassPrivateFieldSet */);
60507             }
60508             return sourceType;
60509         }
60510         /**
60511          * This is a *shallow* check: An expression is side-effect-free if the
60512          * evaluation of the expression *itself* cannot produce side effects.
60513          * For example, x++ / 3 is side-effect free because the / operator
60514          * does not have side effects.
60515          * The intent is to "smell test" an expression for correctness in positions where
60516          * its value is discarded (e.g. the left side of the comma operator).
60517          */
60518         function isSideEffectFree(node) {
60519             node = ts.skipParentheses(node);
60520             switch (node.kind) {
60521                 case 75 /* Identifier */:
60522                 case 10 /* StringLiteral */:
60523                 case 13 /* RegularExpressionLiteral */:
60524                 case 198 /* TaggedTemplateExpression */:
60525                 case 211 /* TemplateExpression */:
60526                 case 14 /* NoSubstitutionTemplateLiteral */:
60527                 case 8 /* NumericLiteral */:
60528                 case 9 /* BigIntLiteral */:
60529                 case 106 /* TrueKeyword */:
60530                 case 91 /* FalseKeyword */:
60531                 case 100 /* NullKeyword */:
60532                 case 146 /* UndefinedKeyword */:
60533                 case 201 /* FunctionExpression */:
60534                 case 214 /* ClassExpression */:
60535                 case 202 /* ArrowFunction */:
60536                 case 192 /* ArrayLiteralExpression */:
60537                 case 193 /* ObjectLiteralExpression */:
60538                 case 204 /* TypeOfExpression */:
60539                 case 218 /* NonNullExpression */:
60540                 case 267 /* JsxSelfClosingElement */:
60541                 case 266 /* JsxElement */:
60542                     return true;
60543                 case 210 /* ConditionalExpression */:
60544                     return isSideEffectFree(node.whenTrue) &&
60545                         isSideEffectFree(node.whenFalse);
60546                 case 209 /* BinaryExpression */:
60547                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
60548                         return false;
60549                     }
60550                     return isSideEffectFree(node.left) &&
60551                         isSideEffectFree(node.right);
60552                 case 207 /* PrefixUnaryExpression */:
60553                 case 208 /* PostfixUnaryExpression */:
60554                     // Unary operators ~, !, +, and - have no side effects.
60555                     // The rest do.
60556                     switch (node.operator) {
60557                         case 53 /* ExclamationToken */:
60558                         case 39 /* PlusToken */:
60559                         case 40 /* MinusToken */:
60560                         case 54 /* TildeToken */:
60561                             return true;
60562                     }
60563                     return false;
60564                 // Some forms listed here for clarity
60565                 case 205 /* VoidExpression */: // Explicit opt-out
60566                 case 199 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
60567                 case 217 /* AsExpression */: // Not SEF, but can produce useful type warnings
60568                 default:
60569                     return false;
60570             }
60571         }
60572         function isTypeEqualityComparableTo(source, target) {
60573             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
60574         }
60575         var CheckBinaryExpressionState;
60576         (function (CheckBinaryExpressionState) {
60577             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
60578             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
60579             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
60580         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
60581         function checkBinaryExpression(node, checkMode) {
60582             var workStacks = {
60583                 expr: [node],
60584                 state: [0 /* MaybeCheckLeft */],
60585                 leftType: [undefined]
60586             };
60587             var stackIndex = 0;
60588             var lastResult;
60589             while (stackIndex >= 0) {
60590                 node = workStacks.expr[stackIndex];
60591                 switch (workStacks.state[stackIndex]) {
60592                     case 0 /* MaybeCheckLeft */: {
60593                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
60594                             finishInvocation(checkExpression(node.right, checkMode));
60595                             break;
60596                         }
60597                         checkGrammarNullishCoalesceWithLogicalExpression(node);
60598                         var operator = node.operatorToken.kind;
60599                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 193 /* ObjectLiteralExpression */ || node.left.kind === 192 /* ArrayLiteralExpression */)) {
60600                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 104 /* ThisKeyword */));
60601                             break;
60602                         }
60603                         advanceState(1 /* CheckRight */);
60604                         maybeCheckExpression(node.left);
60605                         break;
60606                     }
60607                     case 1 /* CheckRight */: {
60608                         var leftType = lastResult;
60609                         workStacks.leftType[stackIndex] = leftType;
60610                         var operator = node.operatorToken.kind;
60611                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60612                             checkTruthinessOfType(leftType, node.left);
60613                         }
60614                         advanceState(2 /* FinishCheck */);
60615                         maybeCheckExpression(node.right);
60616                         break;
60617                     }
60618                     case 2 /* FinishCheck */: {
60619                         var leftType = workStacks.leftType[stackIndex];
60620                         var rightType = lastResult;
60621                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
60622                         break;
60623                     }
60624                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
60625                 }
60626             }
60627             return lastResult;
60628             function finishInvocation(result) {
60629                 lastResult = result;
60630                 stackIndex--;
60631             }
60632             /**
60633              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
60634              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
60635              */
60636             function advanceState(nextState) {
60637                 workStacks.state[stackIndex] = nextState;
60638             }
60639             function maybeCheckExpression(node) {
60640                 if (ts.isBinaryExpression(node)) {
60641                     stackIndex++;
60642                     workStacks.expr[stackIndex] = node;
60643                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
60644                     workStacks.leftType[stackIndex] = undefined;
60645                 }
60646                 else {
60647                     lastResult = checkExpression(node, checkMode);
60648                 }
60649             }
60650         }
60651         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
60652             var left = node.left, operatorToken = node.operatorToken, right = node.right;
60653             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
60654                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60655                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60656                 }
60657                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
60658                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
60659                 }
60660             }
60661         }
60662         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
60663         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
60664         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
60665             var operator = operatorToken.kind;
60666             if (operator === 62 /* EqualsToken */ && (left.kind === 193 /* ObjectLiteralExpression */ || left.kind === 192 /* ArrayLiteralExpression */)) {
60667                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 104 /* ThisKeyword */);
60668             }
60669             var leftType;
60670             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
60671                 leftType = checkTruthinessExpression(left, checkMode);
60672             }
60673             else {
60674                 leftType = checkExpression(left, checkMode);
60675             }
60676             var rightType = checkExpression(right, checkMode);
60677             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
60678         }
60679         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
60680             var operator = operatorToken.kind;
60681             switch (operator) {
60682                 case 41 /* AsteriskToken */:
60683                 case 42 /* AsteriskAsteriskToken */:
60684                 case 65 /* AsteriskEqualsToken */:
60685                 case 66 /* AsteriskAsteriskEqualsToken */:
60686                 case 43 /* SlashToken */:
60687                 case 67 /* SlashEqualsToken */:
60688                 case 44 /* PercentToken */:
60689                 case 68 /* PercentEqualsToken */:
60690                 case 40 /* MinusToken */:
60691                 case 64 /* MinusEqualsToken */:
60692                 case 47 /* LessThanLessThanToken */:
60693                 case 69 /* LessThanLessThanEqualsToken */:
60694                 case 48 /* GreaterThanGreaterThanToken */:
60695                 case 70 /* GreaterThanGreaterThanEqualsToken */:
60696                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60697                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60698                 case 51 /* BarToken */:
60699                 case 73 /* BarEqualsToken */:
60700                 case 52 /* CaretToken */:
60701                 case 74 /* CaretEqualsToken */:
60702                 case 50 /* AmpersandToken */:
60703                 case 72 /* AmpersandEqualsToken */:
60704                     if (leftType === silentNeverType || rightType === silentNeverType) {
60705                         return silentNeverType;
60706                     }
60707                     leftType = checkNonNullType(leftType, left);
60708                     rightType = checkNonNullType(rightType, right);
60709                     var suggestedOperator = void 0;
60710                     // if a user tries to apply a bitwise operator to 2 boolean operands
60711                     // try and return them a helpful suggestion
60712                     if ((leftType.flags & 528 /* BooleanLike */) &&
60713                         (rightType.flags & 528 /* BooleanLike */) &&
60714                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
60715                         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));
60716                         return numberType;
60717                     }
60718                     else {
60719                         // otherwise just check each operand separately and report errors as normal
60720                         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);
60721                         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);
60722                         var resultType_1;
60723                         // If both are any or unknown, allow operation; assume it will resolve to number
60724                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
60725                             // Or, if neither could be bigint, implicit coercion results in a number result
60726                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
60727                             resultType_1 = numberType;
60728                         }
60729                         // At least one is assignable to bigint, so check that both are
60730                         else if (bothAreBigIntLike(leftType, rightType)) {
60731                             switch (operator) {
60732                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
60733                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
60734                                     reportOperatorError();
60735                             }
60736                             resultType_1 = bigintType;
60737                         }
60738                         // Exactly one of leftType/rightType is assignable to bigint
60739                         else {
60740                             reportOperatorError(bothAreBigIntLike);
60741                             resultType_1 = errorType;
60742                         }
60743                         if (leftOk && rightOk) {
60744                             checkAssignmentOperator(resultType_1);
60745                         }
60746                         return resultType_1;
60747                     }
60748                 case 39 /* PlusToken */:
60749                 case 63 /* PlusEqualsToken */:
60750                     if (leftType === silentNeverType || rightType === silentNeverType) {
60751                         return silentNeverType;
60752                     }
60753                     if (!isTypeAssignableToKind(leftType, 132 /* StringLike */) && !isTypeAssignableToKind(rightType, 132 /* StringLike */)) {
60754                         leftType = checkNonNullType(leftType, left);
60755                         rightType = checkNonNullType(rightType, right);
60756                     }
60757                     var resultType = void 0;
60758                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
60759                         // Operands of an enum type are treated as having the primitive type Number.
60760                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
60761                         resultType = numberType;
60762                     }
60763                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
60764                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
60765                         resultType = bigintType;
60766                     }
60767                     else if (isTypeAssignableToKind(leftType, 132 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 132 /* StringLike */, /*strict*/ true)) {
60768                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
60769                         resultType = stringType;
60770                     }
60771                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
60772                         // Otherwise, the result is of type Any.
60773                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
60774                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
60775                     }
60776                     // Symbols are not allowed at all in arithmetic expressions
60777                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
60778                         return resultType;
60779                     }
60780                     if (!resultType) {
60781                         // Types that have a reasonably good chance of being a valid operand type.
60782                         // If both types have an awaited type of one of these, we'll assume the user
60783                         // might be missing an await without doing an exhaustive check that inserting
60784                         // await(s) will actually be a completely valid binary expression.
60785                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 132 /* StringLike */ | 3 /* AnyOrUnknown */;
60786                         reportOperatorError(function (left, right) {
60787                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
60788                                 isTypeAssignableToKind(right, closeEnoughKind_1);
60789                         });
60790                         return anyType;
60791                     }
60792                     if (operator === 63 /* PlusEqualsToken */) {
60793                         checkAssignmentOperator(resultType);
60794                     }
60795                     return resultType;
60796                 case 29 /* LessThanToken */:
60797                 case 31 /* GreaterThanToken */:
60798                 case 32 /* LessThanEqualsToken */:
60799                 case 33 /* GreaterThanEqualsToken */:
60800                     if (checkForDisallowedESSymbolOperand(operator)) {
60801                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
60802                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
60803                         reportOperatorErrorUnless(function (left, right) {
60804                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
60805                         });
60806                     }
60807                     return booleanType;
60808                 case 34 /* EqualsEqualsToken */:
60809                 case 35 /* ExclamationEqualsToken */:
60810                 case 36 /* EqualsEqualsEqualsToken */:
60811                 case 37 /* ExclamationEqualsEqualsToken */:
60812                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
60813                     return booleanType;
60814                 case 98 /* InstanceOfKeyword */:
60815                     return checkInstanceOfExpression(left, right, leftType, rightType);
60816                 case 97 /* InKeyword */:
60817                     return checkInExpression(left, right, leftType, rightType);
60818                 case 55 /* AmpersandAmpersandToken */:
60819                     return getTypeFacts(leftType) & 4194304 /* Truthy */ ?
60820                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
60821                         leftType;
60822                 case 56 /* BarBarToken */:
60823                     return getTypeFacts(leftType) & 8388608 /* Falsy */ ?
60824                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
60825                         leftType;
60826                 case 60 /* QuestionQuestionToken */:
60827                     return getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
60828                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
60829                         leftType;
60830                 case 62 /* EqualsToken */:
60831                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
60832                     checkAssignmentDeclaration(declKind, rightType);
60833                     if (isAssignmentDeclaration(declKind)) {
60834                         if (!(rightType.flags & 524288 /* Object */) ||
60835                             declKind !== 2 /* ModuleExports */ &&
60836                                 declKind !== 6 /* Prototype */ &&
60837                                 !isEmptyObjectType(rightType) &&
60838                                 !isFunctionObjectType(rightType) &&
60839                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
60840                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
60841                             checkAssignmentOperator(rightType);
60842                         }
60843                         return leftType;
60844                     }
60845                     else {
60846                         checkAssignmentOperator(rightType);
60847                         return getRegularTypeOfObjectLiteral(rightType);
60848                     }
60849                 case 27 /* CommaToken */:
60850                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
60851                         error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
60852                     }
60853                     return rightType;
60854                 default:
60855                     return ts.Debug.fail();
60856             }
60857             function bothAreBigIntLike(left, right) {
60858                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
60859             }
60860             function checkAssignmentDeclaration(kind, rightType) {
60861                 if (kind === 2 /* ModuleExports */) {
60862                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
60863                         var prop = _a[_i];
60864                         var propType = getTypeOfSymbol(prop);
60865                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
60866                             var name = prop.escapedName;
60867                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
60868                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
60869                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
60870                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
60871                             }
60872                         }
60873                     }
60874                 }
60875             }
60876             function isEvalNode(node) {
60877                 return node.kind === 75 /* Identifier */ && node.escapedText === "eval";
60878             }
60879             // Return true if there was no error, false if there was an error.
60880             function checkForDisallowedESSymbolOperand(operator) {
60881                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
60882                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
60883                         undefined;
60884                 if (offendingSymbolOperand) {
60885                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
60886                     return false;
60887                 }
60888                 return true;
60889             }
60890             function getSuggestedBooleanOperator(operator) {
60891                 switch (operator) {
60892                     case 51 /* BarToken */:
60893                     case 73 /* BarEqualsToken */:
60894                         return 56 /* BarBarToken */;
60895                     case 52 /* CaretToken */:
60896                     case 74 /* CaretEqualsToken */:
60897                         return 37 /* ExclamationEqualsEqualsToken */;
60898                     case 50 /* AmpersandToken */:
60899                     case 72 /* AmpersandEqualsToken */:
60900                         return 55 /* AmpersandAmpersandToken */;
60901                     default:
60902                         return undefined;
60903                 }
60904             }
60905             function checkAssignmentOperator(valueType) {
60906                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
60907                     // TypeScript 1.0 spec (April 2014): 4.17
60908                     // An assignment of the form
60909                     //    VarExpr = ValueExpr
60910                     // requires VarExpr to be classified as a reference
60911                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
60912                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
60913                     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)
60914                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
60915                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
60916                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
60917                     }
60918                 }
60919             }
60920             function isAssignmentDeclaration(kind) {
60921                 switch (kind) {
60922                     case 2 /* ModuleExports */:
60923                         return true;
60924                     case 1 /* ExportsProperty */:
60925                     case 5 /* Property */:
60926                     case 6 /* Prototype */:
60927                     case 3 /* PrototypeProperty */:
60928                     case 4 /* ThisProperty */:
60929                         var symbol = getSymbolOfNode(left);
60930                         var init = ts.getAssignedExpandoInitializer(right);
60931                         return init && ts.isObjectLiteralExpression(init) &&
60932                             symbol && ts.hasEntries(symbol.exports);
60933                     default:
60934                         return false;
60935                 }
60936             }
60937             /**
60938              * Returns true if an error is reported
60939              */
60940             function reportOperatorErrorUnless(typesAreCompatible) {
60941                 if (!typesAreCompatible(leftType, rightType)) {
60942                     reportOperatorError(typesAreCompatible);
60943                     return true;
60944                 }
60945                 return false;
60946             }
60947             function reportOperatorError(isRelated) {
60948                 var _a;
60949                 var wouldWorkWithAwait = false;
60950                 var errNode = errorNode || operatorToken;
60951                 if (isRelated) {
60952                     var awaitedLeftType = getAwaitedType(leftType);
60953                     var awaitedRightType = getAwaitedType(rightType);
60954                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
60955                         && !!(awaitedLeftType && awaitedRightType)
60956                         && isRelated(awaitedLeftType, awaitedRightType);
60957                 }
60958                 var effectiveLeft = leftType;
60959                 var effectiveRight = rightType;
60960                 if (!wouldWorkWithAwait && isRelated) {
60961                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
60962                 }
60963                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
60964                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
60965                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
60966                 }
60967             }
60968             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
60969                 var typeName;
60970                 switch (operatorToken.kind) {
60971                     case 36 /* EqualsEqualsEqualsToken */:
60972                     case 34 /* EqualsEqualsToken */:
60973                         typeName = "false";
60974                         break;
60975                     case 37 /* ExclamationEqualsEqualsToken */:
60976                     case 35 /* ExclamationEqualsToken */:
60977                         typeName = "true";
60978                 }
60979                 if (typeName) {
60980                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
60981                 }
60982                 return undefined;
60983             }
60984         }
60985         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
60986             var effectiveLeft = leftType;
60987             var effectiveRight = rightType;
60988             var leftBase = getBaseTypeOfLiteralType(leftType);
60989             var rightBase = getBaseTypeOfLiteralType(rightType);
60990             if (!isRelated(leftBase, rightBase)) {
60991                 effectiveLeft = leftBase;
60992                 effectiveRight = rightBase;
60993             }
60994             return [effectiveLeft, effectiveRight];
60995         }
60996         function checkYieldExpression(node) {
60997             // Grammar checking
60998             if (produceDiagnostics) {
60999                 if (!(node.flags & 8192 /* YieldContext */)) {
61000                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
61001                 }
61002                 if (isInParameterInitializerBeforeContainingFunction(node)) {
61003                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
61004                 }
61005             }
61006             var func = ts.getContainingFunction(node);
61007             if (!func)
61008                 return anyType;
61009             var functionFlags = ts.getFunctionFlags(func);
61010             if (!(functionFlags & 1 /* Generator */)) {
61011                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
61012                 return anyType;
61013             }
61014             var isAsync = (functionFlags & 2 /* Async */) !== 0;
61015             if (node.asteriskToken) {
61016                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
61017                 // and __asyncValues helpers
61018                 if (isAsync && languageVersion < 99 /* ESNext */) {
61019                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
61020                 }
61021                 // Generator functions prior to ES2015 require the __values helper
61022                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
61023                     checkExternalEmitHelpers(node, 256 /* Values */);
61024                 }
61025             }
61026             // There is no point in doing an assignability check if the function
61027             // has no explicit return type because the return type is directly computed
61028             // from the yield expressions.
61029             var returnType = getReturnTypeFromAnnotation(func);
61030             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
61031             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
61032             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
61033             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
61034             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
61035             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
61036             if (returnType && yieldedType) {
61037                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
61038             }
61039             if (node.asteriskToken) {
61040                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
61041                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
61042                     || anyType;
61043             }
61044             else if (returnType) {
61045                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
61046                     || anyType;
61047             }
61048             return getContextualIterationType(2 /* Next */, func) || anyType;
61049         }
61050         function checkConditionalExpression(node, checkMode) {
61051             var type = checkTruthinessExpression(node.condition);
61052             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
61053             var type1 = checkExpression(node.whenTrue, checkMode);
61054             var type2 = checkExpression(node.whenFalse, checkMode);
61055             return getUnionType([type1, type2], 2 /* Subtype */);
61056         }
61057         function checkTemplateExpression(node) {
61058             // We just want to check each expressions, but we are unconcerned with
61059             // the type of each expression, as any value may be coerced into a string.
61060             // It is worth asking whether this is what we really want though.
61061             // A place where we actually *are* concerned with the expressions' types are
61062             // in tagged templates.
61063             ts.forEach(node.templateSpans, function (templateSpan) {
61064                 if (maybeTypeOfKind(checkExpression(templateSpan.expression), 12288 /* ESSymbolLike */)) {
61065                     error(templateSpan.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
61066                 }
61067             });
61068             return stringType;
61069         }
61070         function getContextNode(node) {
61071             if (node.kind === 274 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
61072                 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)
61073             }
61074             return node;
61075         }
61076         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
61077             var context = getContextNode(node);
61078             var saveContextualType = context.contextualType;
61079             var saveInferenceContext = context.inferenceContext;
61080             try {
61081                 context.contextualType = contextualType;
61082                 context.inferenceContext = inferenceContext;
61083                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
61084                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
61085                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
61086                 // here would be to not mark contextually typed literals as fresh in the first place.
61087                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
61088                     getRegularTypeOfLiteralType(type) : type;
61089                 return result;
61090             }
61091             finally {
61092                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61093                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61094                 // may hold onto the checker that created it.
61095                 context.contextualType = saveContextualType;
61096                 context.inferenceContext = saveInferenceContext;
61097             }
61098         }
61099         function checkExpressionCached(node, checkMode) {
61100             var links = getNodeLinks(node);
61101             if (!links.resolvedType) {
61102                 if (checkMode && checkMode !== 0 /* Normal */) {
61103                     return checkExpression(node, checkMode);
61104                 }
61105                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
61106                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
61107                 // to the top of the stack ensures all transient types are computed from a known point.
61108                 var saveFlowLoopStart = flowLoopStart;
61109                 var saveFlowTypeCache = flowTypeCache;
61110                 flowLoopStart = flowLoopCount;
61111                 flowTypeCache = undefined;
61112                 links.resolvedType = checkExpression(node, checkMode);
61113                 flowTypeCache = saveFlowTypeCache;
61114                 flowLoopStart = saveFlowLoopStart;
61115             }
61116             return links.resolvedType;
61117         }
61118         function isTypeAssertion(node) {
61119             node = ts.skipParentheses(node);
61120             return node.kind === 199 /* TypeAssertionExpression */ || node.kind === 217 /* AsExpression */;
61121         }
61122         function checkDeclarationInitializer(declaration, contextualType) {
61123             var initializer = ts.getEffectiveInitializer(declaration);
61124             var type = getQuickTypeOfExpression(initializer) ||
61125                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
61126             return ts.isParameter(declaration) && declaration.name.kind === 190 /* ArrayBindingPattern */ &&
61127                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
61128                 padTupleType(type, declaration.name) : type;
61129         }
61130         function padTupleType(type, pattern) {
61131             var patternElements = pattern.elements;
61132             var arity = getTypeReferenceArity(type);
61133             var elementTypes = arity ? getTypeArguments(type).slice() : [];
61134             for (var i = arity; i < patternElements.length; i++) {
61135                 var e = patternElements[i];
61136                 if (i < patternElements.length - 1 || !(e.kind === 191 /* BindingElement */ && e.dotDotDotToken)) {
61137                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
61138                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
61139                         reportImplicitAny(e, anyType);
61140                     }
61141                 }
61142             }
61143             return createTupleType(elementTypes, type.target.minLength, /*hasRestElement*/ false, type.target.readonly);
61144         }
61145         function widenTypeInferredFromInitializer(declaration, type) {
61146             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
61147             if (ts.isInJSFile(declaration)) {
61148                 if (widened.flags & 98304 /* Nullable */) {
61149                     reportImplicitAny(declaration, anyType);
61150                     return anyType;
61151                 }
61152                 else if (isEmptyArrayLiteralType(widened)) {
61153                     reportImplicitAny(declaration, anyArrayType);
61154                     return anyArrayType;
61155                 }
61156             }
61157             return widened;
61158         }
61159         function isLiteralOfContextualType(candidateType, contextualType) {
61160             if (contextualType) {
61161                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
61162                     var types = contextualType.types;
61163                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
61164                 }
61165                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
61166                     // If the contextual type is a type variable constrained to a primitive type, consider
61167                     // this a literal context for literals of that primitive type. For example, given a
61168                     // type parameter 'T extends string', infer string literal types for T.
61169                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
61170                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61171                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61172                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61173                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
61174                         isLiteralOfContextualType(candidateType, constraint);
61175                 }
61176                 // If the contextual type is a literal of a particular primitive type, we consider this a
61177                 // literal context for all literals of that primitive type.
61178                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
61179                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
61180                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
61181                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
61182                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
61183             }
61184             return false;
61185         }
61186         function isConstContext(node) {
61187             var parent = node.parent;
61188             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
61189                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
61190                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) && isConstContext(parent.parent);
61191         }
61192         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
61193             var type = checkExpression(node, checkMode, forceTuple);
61194             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
61195                 isTypeAssertion(node) ? type :
61196                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
61197         }
61198         function checkPropertyAssignment(node, checkMode) {
61199             // Do not use hasDynamicName here, because that returns false for well known symbols.
61200             // We want to perform checkComputedPropertyName for all computed properties, including
61201             // well known symbols.
61202             if (node.name.kind === 154 /* ComputedPropertyName */) {
61203                 checkComputedPropertyName(node.name);
61204             }
61205             return checkExpressionForMutableLocation(node.initializer, checkMode);
61206         }
61207         function checkObjectLiteralMethod(node, checkMode) {
61208             // Grammar checking
61209             checkGrammarMethod(node);
61210             // Do not use hasDynamicName here, because that returns false for well known symbols.
61211             // We want to perform checkComputedPropertyName for all computed properties, including
61212             // well known symbols.
61213             if (node.name.kind === 154 /* ComputedPropertyName */) {
61214                 checkComputedPropertyName(node.name);
61215             }
61216             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61217             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61218         }
61219         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
61220             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
61221                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
61222                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
61223                 var signature = callSignature || constructSignature;
61224                 if (signature && signature.typeParameters) {
61225                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
61226                     if (contextualType) {
61227                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
61228                         if (contextualSignature && !contextualSignature.typeParameters) {
61229                             if (checkMode & 8 /* SkipGenericFunctions */) {
61230                                 skippedGenericFunction(node, checkMode);
61231                                 return anyFunctionType;
61232                             }
61233                             var context = getInferenceContext(node);
61234                             // We have an expression that is an argument of a generic function for which we are performing
61235                             // type argument inference. The expression is of a function type with a single generic call
61236                             // signature and a contextual function type with a single non-generic call signature. Now check
61237                             // if the outer function returns a function type with a single non-generic call signature and
61238                             // if some of the outer function type parameters have no inferences so far. If so, we can
61239                             // potentially add inferred type parameters to the outer function return type.
61240                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
61241                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
61242                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
61243                                 // Instantiate the signature with its own type parameters as type arguments, possibly
61244                                 // renaming the type parameters to ensure they have unique names.
61245                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
61246                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
61247                                 // Infer from the parameters of the instantiated signature to the parameters of the
61248                                 // contextual signature starting with an empty set of inference candidates.
61249                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
61250                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
61251                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
61252                                 });
61253                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
61254                                     // We have inference candidates, indicating that one or more type parameters are referenced
61255                                     // in the parameter types of the contextual signature. Now also infer from the return type.
61256                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
61257                                         inferTypes(inferences_3, source, target);
61258                                     });
61259                                     // If the type parameters for which we produced candidates do not have any inferences yet,
61260                                     // we adopt the new inference candidates and add the type parameters of the expression type
61261                                     // to the set of inferred type parameters for the outer function return type.
61262                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
61263                                         mergeInferences(context.inferences, inferences_3);
61264                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
61265                                         return getOrCreateTypeFromSignature(instantiatedSignature);
61266                                     }
61267                                 }
61268                             }
61269                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
61270                         }
61271                     }
61272                 }
61273             }
61274             return type;
61275         }
61276         function skippedGenericFunction(node, checkMode) {
61277             if (checkMode & 2 /* Inferential */) {
61278                 // We have skipped a generic function during inferential typing. Obtain the inference context and
61279                 // indicate this has occurred such that we know a second pass of inference is be needed.
61280                 var context = getInferenceContext(node);
61281                 context.flags |= 4 /* SkippedGenericFunction */;
61282             }
61283         }
61284         function hasInferenceCandidates(info) {
61285             return !!(info.candidates || info.contraCandidates);
61286         }
61287         function hasOverlappingInferences(a, b) {
61288             for (var i = 0; i < a.length; i++) {
61289                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
61290                     return true;
61291                 }
61292             }
61293             return false;
61294         }
61295         function mergeInferences(target, source) {
61296             for (var i = 0; i < target.length; i++) {
61297                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
61298                     target[i] = source[i];
61299                 }
61300             }
61301         }
61302         function getUniqueTypeParameters(context, typeParameters) {
61303             var result = [];
61304             var oldTypeParameters;
61305             var newTypeParameters;
61306             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
61307                 var tp = typeParameters_2[_i];
61308                 var name = tp.symbol.escapedName;
61309                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
61310                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
61311                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
61312                     var newTypeParameter = createTypeParameter(symbol);
61313                     newTypeParameter.target = tp;
61314                     oldTypeParameters = ts.append(oldTypeParameters, tp);
61315                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
61316                     result.push(newTypeParameter);
61317                 }
61318                 else {
61319                     result.push(tp);
61320                 }
61321             }
61322             if (newTypeParameters) {
61323                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
61324                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
61325                     var tp = newTypeParameters_1[_a];
61326                     tp.mapper = mapper;
61327                 }
61328             }
61329             return result;
61330         }
61331         function hasTypeParameterByName(typeParameters, name) {
61332             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
61333         }
61334         function getUniqueTypeParameterName(typeParameters, baseName) {
61335             var len = baseName.length;
61336             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
61337                 len--;
61338             var s = baseName.slice(0, len);
61339             for (var index = 1; true; index++) {
61340                 var augmentedName = (s + index);
61341                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
61342                     return augmentedName;
61343                 }
61344             }
61345         }
61346         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
61347             var signature = getSingleCallSignature(funcType);
61348             if (signature && !signature.typeParameters) {
61349                 return getReturnTypeOfSignature(signature);
61350             }
61351         }
61352         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
61353             var funcType = checkExpression(expr.expression);
61354             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
61355             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
61356             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
61357         }
61358         /**
61359          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61360          * with computing the type and may not fully check all contained sub-expressions for errors.
61361          */
61362         function getTypeOfExpression(node) {
61363             // Don't bother caching types that require no flow analysis and are quick to compute.
61364             var quickType = getQuickTypeOfExpression(node);
61365             if (quickType) {
61366                 return quickType;
61367             }
61368             // If a type has been cached for the node, return it.
61369             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
61370                 var cachedType = flowTypeCache[getNodeId(node)];
61371                 if (cachedType) {
61372                     return cachedType;
61373                 }
61374             }
61375             var startInvocationCount = flowInvocationCount;
61376             var type = checkExpression(node);
61377             // If control flow analysis was required to determine the type, it is worth caching.
61378             if (flowInvocationCount !== startInvocationCount) {
61379                 var cache = flowTypeCache || (flowTypeCache = []);
61380                 cache[getNodeId(node)] = type;
61381                 node.flags |= 67108864 /* TypeCached */;
61382             }
61383             return type;
61384         }
61385         function getQuickTypeOfExpression(node) {
61386             var expr = ts.skipParentheses(node);
61387             // Optimize for the common case of a call to a function with a single non-generic call
61388             // signature where we can just fetch the return type without checking the arguments.
61389             if (ts.isCallExpression(expr) && expr.expression.kind !== 102 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
61390                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
61391                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
61392                 if (type) {
61393                     return type;
61394                 }
61395             }
61396             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
61397                 return getTypeFromTypeNode(expr.type);
61398             }
61399             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
61400                 node.kind === 106 /* TrueKeyword */ || node.kind === 91 /* FalseKeyword */) {
61401                 return checkExpression(node);
61402             }
61403             return undefined;
61404         }
61405         /**
61406          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
61407          * with computing the type and may not fully check all contained sub-expressions for errors.
61408          * It is intended for uses where you know there is no contextual type,
61409          * and requesting the contextual type might cause a circularity or other bad behaviour.
61410          * It sets the contextual type of the node to any before calling getTypeOfExpression.
61411          */
61412         function getContextFreeTypeOfExpression(node) {
61413             var links = getNodeLinks(node);
61414             if (links.contextFreeType) {
61415                 return links.contextFreeType;
61416             }
61417             var saveContextualType = node.contextualType;
61418             node.contextualType = anyType;
61419             try {
61420                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
61421                 return type;
61422             }
61423             finally {
61424                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
61425                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
61426                 // may hold onto the checker that created it.
61427                 node.contextualType = saveContextualType;
61428             }
61429         }
61430         function checkExpression(node, checkMode, forceTuple) {
61431             var saveCurrentNode = currentNode;
61432             currentNode = node;
61433             instantiationCount = 0;
61434             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
61435             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
61436             if (isConstEnumObjectType(type)) {
61437                 checkConstEnumAccess(node, type);
61438             }
61439             currentNode = saveCurrentNode;
61440             return type;
61441         }
61442         function checkConstEnumAccess(node, type) {
61443             // enum object type for const enums are only permitted in:
61444             // - 'left' in property access
61445             // - 'object' in indexed access
61446             // - target in rhs of import statement
61447             var ok = (node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.expression === node) ||
61448                 (node.parent.kind === 195 /* ElementAccessExpression */ && node.parent.expression === node) ||
61449                 ((node.kind === 75 /* Identifier */ || node.kind === 153 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
61450                     (node.parent.kind === 172 /* TypeQuery */ && node.parent.exprName === node)) ||
61451                 (node.parent.kind === 263 /* ExportSpecifier */); // We allow reexporting const enums
61452             if (!ok) {
61453                 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);
61454             }
61455             if (compilerOptions.isolatedModules) {
61456                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
61457                 var constEnumDeclaration = type.symbol.valueDeclaration;
61458                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
61459                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
61460                 }
61461             }
61462         }
61463         function checkParenthesizedExpression(node, checkMode) {
61464             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
61465             if (tag) {
61466                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
61467             }
61468             return checkExpression(node.expression, checkMode);
61469         }
61470         function checkExpressionWorker(node, checkMode, forceTuple) {
61471             var kind = node.kind;
61472             if (cancellationToken) {
61473                 // Only bother checking on a few construct kinds.  We don't want to be excessively
61474                 // hitting the cancellation token on every node we check.
61475                 switch (kind) {
61476                     case 214 /* ClassExpression */:
61477                     case 201 /* FunctionExpression */:
61478                     case 202 /* ArrowFunction */:
61479                         cancellationToken.throwIfCancellationRequested();
61480                 }
61481             }
61482             switch (kind) {
61483                 case 75 /* Identifier */:
61484                     return checkIdentifier(node);
61485                 case 104 /* ThisKeyword */:
61486                     return checkThisExpression(node);
61487                 case 102 /* SuperKeyword */:
61488                     return checkSuperExpression(node);
61489                 case 100 /* NullKeyword */:
61490                     return nullWideningType;
61491                 case 14 /* NoSubstitutionTemplateLiteral */:
61492                 case 10 /* StringLiteral */:
61493                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
61494                 case 8 /* NumericLiteral */:
61495                     checkGrammarNumericLiteral(node);
61496                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
61497                 case 9 /* BigIntLiteral */:
61498                     checkGrammarBigIntLiteral(node);
61499                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
61500                 case 106 /* TrueKeyword */:
61501                     return trueType;
61502                 case 91 /* FalseKeyword */:
61503                     return falseType;
61504                 case 211 /* TemplateExpression */:
61505                     return checkTemplateExpression(node);
61506                 case 13 /* RegularExpressionLiteral */:
61507                     return globalRegExpType;
61508                 case 192 /* ArrayLiteralExpression */:
61509                     return checkArrayLiteral(node, checkMode, forceTuple);
61510                 case 193 /* ObjectLiteralExpression */:
61511                     return checkObjectLiteral(node, checkMode);
61512                 case 194 /* PropertyAccessExpression */:
61513                     return checkPropertyAccessExpression(node);
61514                 case 153 /* QualifiedName */:
61515                     return checkQualifiedName(node);
61516                 case 195 /* ElementAccessExpression */:
61517                     return checkIndexedAccess(node);
61518                 case 196 /* CallExpression */:
61519                     if (node.expression.kind === 96 /* ImportKeyword */) {
61520                         return checkImportCallExpression(node);
61521                     }
61522                 // falls through
61523                 case 197 /* NewExpression */:
61524                     return checkCallExpression(node, checkMode);
61525                 case 198 /* TaggedTemplateExpression */:
61526                     return checkTaggedTemplateExpression(node);
61527                 case 200 /* ParenthesizedExpression */:
61528                     return checkParenthesizedExpression(node, checkMode);
61529                 case 214 /* ClassExpression */:
61530                     return checkClassExpression(node);
61531                 case 201 /* FunctionExpression */:
61532                 case 202 /* ArrowFunction */:
61533                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
61534                 case 204 /* TypeOfExpression */:
61535                     return checkTypeOfExpression(node);
61536                 case 199 /* TypeAssertionExpression */:
61537                 case 217 /* AsExpression */:
61538                     return checkAssertion(node);
61539                 case 218 /* NonNullExpression */:
61540                     return checkNonNullAssertion(node);
61541                 case 219 /* MetaProperty */:
61542                     return checkMetaProperty(node);
61543                 case 203 /* DeleteExpression */:
61544                     return checkDeleteExpression(node);
61545                 case 205 /* VoidExpression */:
61546                     return checkVoidExpression(node);
61547                 case 206 /* AwaitExpression */:
61548                     return checkAwaitExpression(node);
61549                 case 207 /* PrefixUnaryExpression */:
61550                     return checkPrefixUnaryExpression(node);
61551                 case 208 /* PostfixUnaryExpression */:
61552                     return checkPostfixUnaryExpression(node);
61553                 case 209 /* BinaryExpression */:
61554                     return checkBinaryExpression(node, checkMode);
61555                 case 210 /* ConditionalExpression */:
61556                     return checkConditionalExpression(node, checkMode);
61557                 case 213 /* SpreadElement */:
61558                     return checkSpreadExpression(node, checkMode);
61559                 case 215 /* OmittedExpression */:
61560                     return undefinedWideningType;
61561                 case 212 /* YieldExpression */:
61562                     return checkYieldExpression(node);
61563                 case 220 /* SyntheticExpression */:
61564                     return node.type;
61565                 case 276 /* JsxExpression */:
61566                     return checkJsxExpression(node, checkMode);
61567                 case 266 /* JsxElement */:
61568                     return checkJsxElement(node, checkMode);
61569                 case 267 /* JsxSelfClosingElement */:
61570                     return checkJsxSelfClosingElement(node, checkMode);
61571                 case 270 /* JsxFragment */:
61572                     return checkJsxFragment(node);
61573                 case 274 /* JsxAttributes */:
61574                     return checkJsxAttributes(node, checkMode);
61575                 case 268 /* JsxOpeningElement */:
61576                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
61577             }
61578             return errorType;
61579         }
61580         // DECLARATION AND STATEMENT TYPE CHECKING
61581         function checkTypeParameter(node) {
61582             // Grammar Checking
61583             if (node.expression) {
61584                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
61585             }
61586             checkSourceElement(node.constraint);
61587             checkSourceElement(node.default);
61588             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
61589             // Resolve base constraint to reveal circularity errors
61590             getBaseConstraintOfType(typeParameter);
61591             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
61592                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
61593             }
61594             var constraintType = getConstraintOfTypeParameter(typeParameter);
61595             var defaultType = getDefaultFromTypeParameter(typeParameter);
61596             if (constraintType && defaultType) {
61597                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
61598             }
61599             if (produceDiagnostics) {
61600                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
61601             }
61602         }
61603         function checkParameter(node) {
61604             // Grammar checking
61605             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
61606             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
61607             // or if its FunctionBody is strict code(11.1.5).
61608             checkGrammarDecoratorsAndModifiers(node);
61609             checkVariableLikeDeclaration(node);
61610             var func = ts.getContainingFunction(node);
61611             if (ts.hasModifier(node, 92 /* ParameterPropertyModifier */)) {
61612                 if (!(func.kind === 162 /* Constructor */ && ts.nodeIsPresent(func.body))) {
61613                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
61614                 }
61615                 if (func.kind === 162 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
61616                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
61617                 }
61618             }
61619             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
61620                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
61621             }
61622             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
61623                 if (func.parameters.indexOf(node) !== 0) {
61624                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
61625                 }
61626                 if (func.kind === 162 /* Constructor */ || func.kind === 166 /* ConstructSignature */ || func.kind === 171 /* ConstructorType */) {
61627                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
61628                 }
61629                 if (func.kind === 202 /* ArrowFunction */) {
61630                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
61631                 }
61632                 if (func.kind === 163 /* GetAccessor */ || func.kind === 164 /* SetAccessor */) {
61633                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
61634                 }
61635             }
61636             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
61637             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
61638             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
61639                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
61640             }
61641         }
61642         function checkTypePredicate(node) {
61643             var parent = getTypePredicateParent(node);
61644             if (!parent) {
61645                 // The parent must not be valid.
61646                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
61647                 return;
61648             }
61649             var signature = getSignatureFromDeclaration(parent);
61650             var typePredicate = getTypePredicateOfSignature(signature);
61651             if (!typePredicate) {
61652                 return;
61653             }
61654             checkSourceElement(node.type);
61655             var parameterName = node.parameterName;
61656             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
61657                 getTypeFromThisTypeNode(parameterName);
61658             }
61659             else {
61660                 if (typePredicate.parameterIndex >= 0) {
61661                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
61662                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
61663                     }
61664                     else {
61665                         if (typePredicate.type) {
61666                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
61667                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
61668                             /*headMessage*/ undefined, leadingError);
61669                         }
61670                     }
61671                 }
61672                 else if (parameterName) {
61673                     var hasReportedError = false;
61674                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
61675                         var name = _a[_i].name;
61676                         if (ts.isBindingPattern(name) &&
61677                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
61678                             hasReportedError = true;
61679                             break;
61680                         }
61681                     }
61682                     if (!hasReportedError) {
61683                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
61684                     }
61685                 }
61686             }
61687         }
61688         function getTypePredicateParent(node) {
61689             switch (node.parent.kind) {
61690                 case 202 /* ArrowFunction */:
61691                 case 165 /* CallSignature */:
61692                 case 244 /* FunctionDeclaration */:
61693                 case 201 /* FunctionExpression */:
61694                 case 170 /* FunctionType */:
61695                 case 161 /* MethodDeclaration */:
61696                 case 160 /* MethodSignature */:
61697                     var parent = node.parent;
61698                     if (node === parent.type) {
61699                         return parent;
61700                     }
61701             }
61702         }
61703         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
61704             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
61705                 var element = _a[_i];
61706                 if (ts.isOmittedExpression(element)) {
61707                     continue;
61708                 }
61709                 var name = element.name;
61710                 if (name.kind === 75 /* Identifier */ && name.escapedText === predicateVariableName) {
61711                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
61712                     return true;
61713                 }
61714                 else if (name.kind === 190 /* ArrayBindingPattern */ || name.kind === 189 /* ObjectBindingPattern */) {
61715                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
61716                         return true;
61717                     }
61718                 }
61719             }
61720         }
61721         function checkSignatureDeclaration(node) {
61722             // Grammar checking
61723             if (node.kind === 167 /* IndexSignature */) {
61724                 checkGrammarIndexSignature(node);
61725             }
61726             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
61727             else if (node.kind === 170 /* FunctionType */ || node.kind === 244 /* FunctionDeclaration */ || node.kind === 171 /* ConstructorType */ ||
61728                 node.kind === 165 /* CallSignature */ || node.kind === 162 /* Constructor */ ||
61729                 node.kind === 166 /* ConstructSignature */) {
61730                 checkGrammarFunctionLikeDeclaration(node);
61731             }
61732             var functionFlags = ts.getFunctionFlags(node);
61733             if (!(functionFlags & 4 /* Invalid */)) {
61734                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
61735                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
61736                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
61737                 }
61738                 // Async functions prior to ES2017 require the __awaiter helper
61739                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
61740                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
61741                 }
61742                 // Generator functions, Async functions, and Async Generator functions prior to
61743                 // ES2015 require the __generator helper
61744                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
61745                     checkExternalEmitHelpers(node, 128 /* Generator */);
61746                 }
61747             }
61748             checkTypeParameters(node.typeParameters);
61749             ts.forEach(node.parameters, checkParameter);
61750             // TODO(rbuckton): Should we start checking JSDoc types?
61751             if (node.type) {
61752                 checkSourceElement(node.type);
61753             }
61754             if (produceDiagnostics) {
61755                 checkCollisionWithArgumentsInGeneratedCode(node);
61756                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
61757                 if (noImplicitAny && !returnTypeNode) {
61758                     switch (node.kind) {
61759                         case 166 /* ConstructSignature */:
61760                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61761                             break;
61762                         case 165 /* CallSignature */:
61763                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
61764                             break;
61765                     }
61766                 }
61767                 if (returnTypeNode) {
61768                     var functionFlags_1 = ts.getFunctionFlags(node);
61769                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
61770                         var returnType = getTypeFromTypeNode(returnTypeNode);
61771                         if (returnType === voidType) {
61772                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
61773                         }
61774                         else {
61775                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
61776                             // However, that would not catch the error in the following case.
61777                             //
61778                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
61779                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
61780                             //
61781                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
61782                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
61783                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
61784                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
61785                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
61786                         }
61787                     }
61788                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
61789                         checkAsyncFunctionReturnType(node, returnTypeNode);
61790                     }
61791                 }
61792                 if (node.kind !== 167 /* IndexSignature */ && node.kind !== 300 /* JSDocFunctionType */) {
61793                     registerForUnusedIdentifiersCheck(node);
61794                 }
61795             }
61796         }
61797         function checkClassForDuplicateDeclarations(node) {
61798             var instanceNames = ts.createUnderscoreEscapedMap();
61799             var staticNames = ts.createUnderscoreEscapedMap();
61800             // instance and static private identifiers share the same scope
61801             var privateIdentifiers = ts.createUnderscoreEscapedMap();
61802             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61803                 var member = _a[_i];
61804                 if (member.kind === 162 /* Constructor */) {
61805                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
61806                         var param = _c[_b];
61807                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
61808                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
61809                         }
61810                     }
61811                 }
61812                 else {
61813                     var isStatic = ts.hasModifier(member, 32 /* Static */);
61814                     var name = member.name;
61815                     if (!name) {
61816                         return;
61817                     }
61818                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
61819                         isStatic ? staticNames :
61820                             instanceNames;
61821                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
61822                     if (memberName) {
61823                         switch (member.kind) {
61824                             case 163 /* GetAccessor */:
61825                                 addName(names, name, memberName, 1 /* GetAccessor */);
61826                                 break;
61827                             case 164 /* SetAccessor */:
61828                                 addName(names, name, memberName, 2 /* SetAccessor */);
61829                                 break;
61830                             case 159 /* PropertyDeclaration */:
61831                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
61832                                 break;
61833                             case 161 /* MethodDeclaration */:
61834                                 addName(names, name, memberName, 8 /* Method */);
61835                                 break;
61836                         }
61837                     }
61838                 }
61839             }
61840             function addName(names, location, name, meaning) {
61841                 var prev = names.get(name);
61842                 if (prev) {
61843                     if (prev & 8 /* Method */) {
61844                         if (meaning !== 8 /* Method */) {
61845                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61846                         }
61847                     }
61848                     else if (prev & meaning) {
61849                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
61850                     }
61851                     else {
61852                         names.set(name, prev | meaning);
61853                     }
61854                 }
61855                 else {
61856                     names.set(name, meaning);
61857                 }
61858             }
61859         }
61860         /**
61861          * Static members being set on a constructor function may conflict with built-in properties
61862          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
61863          * built-in properties. This check issues a transpile error when a class has a static
61864          * member with the same name as a non-writable built-in property.
61865          *
61866          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
61867          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
61868          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
61869          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
61870          */
61871         function checkClassForStaticPropertyNameConflicts(node) {
61872             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61873                 var member = _a[_i];
61874                 var memberNameNode = member.name;
61875                 var isStatic = ts.hasModifier(member, 32 /* Static */);
61876                 if (isStatic && memberNameNode) {
61877                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
61878                     switch (memberName) {
61879                         case "name":
61880                         case "length":
61881                         case "caller":
61882                         case "arguments":
61883                         case "prototype":
61884                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
61885                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
61886                             error(memberNameNode, message, memberName, className);
61887                             break;
61888                     }
61889                 }
61890             }
61891         }
61892         function checkObjectTypeForDuplicateDeclarations(node) {
61893             var names = ts.createMap();
61894             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
61895                 var member = _a[_i];
61896                 if (member.kind === 158 /* PropertySignature */) {
61897                     var memberName = void 0;
61898                     var name = member.name;
61899                     switch (name.kind) {
61900                         case 10 /* StringLiteral */:
61901                         case 8 /* NumericLiteral */:
61902                             memberName = name.text;
61903                             break;
61904                         case 75 /* Identifier */:
61905                             memberName = ts.idText(name);
61906                             break;
61907                         default:
61908                             continue;
61909                     }
61910                     if (names.get(memberName)) {
61911                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
61912                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
61913                     }
61914                     else {
61915                         names.set(memberName, true);
61916                     }
61917                 }
61918             }
61919         }
61920         function checkTypeForDuplicateIndexSignatures(node) {
61921             if (node.kind === 246 /* InterfaceDeclaration */) {
61922                 var nodeSymbol = getSymbolOfNode(node);
61923                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
61924                 // to prevent this run check only for the first declaration of a given kind
61925                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
61926                     return;
61927                 }
61928             }
61929             // TypeScript 1.0 spec (April 2014)
61930             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
61931             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
61932             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
61933             if (indexSymbol) {
61934                 var seenNumericIndexer = false;
61935                 var seenStringIndexer = false;
61936                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
61937                     var decl = _a[_i];
61938                     var declaration = decl;
61939                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
61940                         switch (declaration.parameters[0].type.kind) {
61941                             case 143 /* StringKeyword */:
61942                                 if (!seenStringIndexer) {
61943                                     seenStringIndexer = true;
61944                                 }
61945                                 else {
61946                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
61947                                 }
61948                                 break;
61949                             case 140 /* NumberKeyword */:
61950                                 if (!seenNumericIndexer) {
61951                                     seenNumericIndexer = true;
61952                                 }
61953                                 else {
61954                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
61955                                 }
61956                                 break;
61957                         }
61958                     }
61959                 }
61960             }
61961         }
61962         function checkPropertyDeclaration(node) {
61963             // Grammar checking
61964             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
61965                 checkGrammarComputedPropertyName(node.name);
61966             checkVariableLikeDeclaration(node);
61967             // Private class fields transformation relies on WeakMaps.
61968             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
61969                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
61970                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
61971                 }
61972             }
61973         }
61974         function checkPropertySignature(node) {
61975             if (ts.isPrivateIdentifier(node.name)) {
61976                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
61977             }
61978             return checkPropertyDeclaration(node);
61979         }
61980         function checkMethodDeclaration(node) {
61981             // Grammar checking
61982             if (!checkGrammarMethod(node))
61983                 checkGrammarComputedPropertyName(node.name);
61984             if (ts.isPrivateIdentifier(node.name)) {
61985                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
61986             }
61987             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
61988             checkFunctionOrMethodDeclaration(node);
61989             // Abstract methods cannot have an implementation.
61990             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
61991             if (ts.hasModifier(node, 128 /* Abstract */) && node.kind === 161 /* MethodDeclaration */ && node.body) {
61992                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
61993             }
61994         }
61995         function checkConstructorDeclaration(node) {
61996             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
61997             checkSignatureDeclaration(node);
61998             // Grammar check for checking only related to constructorDeclaration
61999             if (!checkGrammarConstructorTypeParameters(node))
62000                 checkGrammarConstructorTypeAnnotation(node);
62001             checkSourceElement(node.body);
62002             var symbol = getSymbolOfNode(node);
62003             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
62004             // Only type check the symbol once
62005             if (node === firstDeclaration) {
62006                 checkFunctionOrConstructorSymbol(symbol);
62007             }
62008             // exit early in the case of signature - super checks are not relevant to them
62009             if (ts.nodeIsMissing(node.body)) {
62010                 return;
62011             }
62012             if (!produceDiagnostics) {
62013                 return;
62014             }
62015             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
62016                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
62017                     return true;
62018                 }
62019                 return n.kind === 159 /* PropertyDeclaration */ &&
62020                     !ts.hasModifier(n, 32 /* Static */) &&
62021                     !!n.initializer;
62022             }
62023             // TS 1.0 spec (April 2014): 8.3.2
62024             // Constructors of classes with no extends clause may not contain super calls, whereas
62025             // constructors of derived classes must contain at least one super call somewhere in their function body.
62026             var containingClassDecl = node.parent;
62027             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
62028                 captureLexicalThis(node.parent, containingClassDecl);
62029                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
62030                 var superCall = getSuperCallInConstructor(node);
62031                 if (superCall) {
62032                     if (classExtendsNull) {
62033                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
62034                     }
62035                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
62036                     // if both of the following are true:
62037                     // - The containing class is a derived class.
62038                     // - The constructor declares parameter properties
62039                     //   or the containing class declares instance member variables with initializers.
62040                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
62041                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
62042                             ts.some(node.parameters, function (p) { return ts.hasModifier(p, 92 /* ParameterPropertyModifier */); }));
62043                     // Skip past any prologue directives to find the first statement
62044                     // to ensure that it was a super call.
62045                     if (superCallShouldBeFirst) {
62046                         var statements = node.body.statements;
62047                         var superCallStatement = void 0;
62048                         for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
62049                             var statement = statements_3[_i];
62050                             if (statement.kind === 226 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
62051                                 superCallStatement = statement;
62052                                 break;
62053                             }
62054                             if (!ts.isPrologueDirective(statement)) {
62055                                 break;
62056                             }
62057                         }
62058                         if (!superCallStatement) {
62059                             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);
62060                         }
62061                     }
62062                 }
62063                 else if (!classExtendsNull) {
62064                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
62065                 }
62066             }
62067         }
62068         function checkAccessorDeclaration(node) {
62069             if (produceDiagnostics) {
62070                 // Grammar checking accessors
62071                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
62072                     checkGrammarComputedPropertyName(node.name);
62073                 checkDecorators(node);
62074                 checkSignatureDeclaration(node);
62075                 if (node.kind === 163 /* GetAccessor */) {
62076                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
62077                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
62078                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
62079                         }
62080                     }
62081                 }
62082                 // Do not use hasDynamicName here, because that returns false for well known symbols.
62083                 // We want to perform checkComputedPropertyName for all computed properties, including
62084                 // well known symbols.
62085                 if (node.name.kind === 154 /* ComputedPropertyName */) {
62086                     checkComputedPropertyName(node.name);
62087                 }
62088                 if (ts.isPrivateIdentifier(node.name)) {
62089                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
62090                 }
62091                 if (!hasNonBindableDynamicName(node)) {
62092                     // TypeScript 1.0 spec (April 2014): 8.4.3
62093                     // Accessors for the same member name must specify the same accessibility.
62094                     var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
62095                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
62096                     if (otherAccessor) {
62097                         var nodeFlags = ts.getModifierFlags(node);
62098                         var otherFlags = ts.getModifierFlags(otherAccessor);
62099                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
62100                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
62101                         }
62102                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
62103                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
62104                         }
62105                         // TypeScript 1.0 spec (April 2014): 4.5
62106                         // If both accessors include type annotations, the specified types must be identical.
62107                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
62108                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
62109                     }
62110                 }
62111                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
62112                 if (node.kind === 163 /* GetAccessor */) {
62113                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
62114                 }
62115             }
62116             checkSourceElement(node.body);
62117         }
62118         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
62119             var firstType = getAnnotatedType(first);
62120             var secondType = getAnnotatedType(second);
62121             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
62122                 error(first, message);
62123             }
62124         }
62125         function checkMissingDeclaration(node) {
62126             checkDecorators(node);
62127         }
62128         function getEffectiveTypeArguments(node, typeParameters) {
62129             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
62130         }
62131         function checkTypeArgumentConstraints(node, typeParameters) {
62132             var typeArguments;
62133             var mapper;
62134             var result = true;
62135             for (var i = 0; i < typeParameters.length; i++) {
62136                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
62137                 if (constraint) {
62138                     if (!typeArguments) {
62139                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
62140                         mapper = createTypeMapper(typeParameters, typeArguments);
62141                     }
62142                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
62143                 }
62144             }
62145             return result;
62146         }
62147         function getTypeParametersForTypeReference(node) {
62148             var type = getTypeFromTypeReference(node);
62149             if (type !== errorType) {
62150                 var symbol = getNodeLinks(node).resolvedSymbol;
62151                 if (symbol) {
62152                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
62153                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
62154                 }
62155             }
62156             return undefined;
62157         }
62158         function checkTypeReferenceNode(node) {
62159             checkGrammarTypeArguments(node, node.typeArguments);
62160             if (node.kind === 169 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
62161                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
62162             }
62163             ts.forEach(node.typeArguments, checkSourceElement);
62164             var type = getTypeFromTypeReference(node);
62165             if (type !== errorType) {
62166                 if (node.typeArguments && produceDiagnostics) {
62167                     var typeParameters = getTypeParametersForTypeReference(node);
62168                     if (typeParameters) {
62169                         checkTypeArgumentConstraints(node, typeParameters);
62170                     }
62171                 }
62172                 if (type.flags & 32 /* Enum */ && getNodeLinks(node).resolvedSymbol.flags & 8 /* EnumMember */) {
62173                     error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
62174                 }
62175             }
62176         }
62177         function getTypeArgumentConstraint(node) {
62178             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
62179             if (!typeReferenceNode)
62180                 return undefined;
62181             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
62182             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
62183             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
62184         }
62185         function checkTypeQuery(node) {
62186             getTypeFromTypeQueryNode(node);
62187         }
62188         function checkTypeLiteral(node) {
62189             ts.forEach(node.members, checkSourceElement);
62190             if (produceDiagnostics) {
62191                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
62192                 checkIndexConstraints(type);
62193                 checkTypeForDuplicateIndexSignatures(node);
62194                 checkObjectTypeForDuplicateDeclarations(node);
62195             }
62196         }
62197         function checkArrayType(node) {
62198             checkSourceElement(node.elementType);
62199         }
62200         function checkTupleType(node) {
62201             var elementTypes = node.elementTypes;
62202             var seenOptionalElement = false;
62203             for (var i = 0; i < elementTypes.length; i++) {
62204                 var e = elementTypes[i];
62205                 if (e.kind === 177 /* RestType */) {
62206                     if (i !== elementTypes.length - 1) {
62207                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
62208                         break;
62209                     }
62210                     if (!isArrayType(getTypeFromTypeNode(e.type))) {
62211                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
62212                     }
62213                 }
62214                 else if (e.kind === 176 /* OptionalType */) {
62215                     seenOptionalElement = true;
62216                 }
62217                 else if (seenOptionalElement) {
62218                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
62219                     break;
62220                 }
62221             }
62222             ts.forEach(node.elementTypes, checkSourceElement);
62223         }
62224         function checkUnionOrIntersectionType(node) {
62225             ts.forEach(node.types, checkSourceElement);
62226         }
62227         function checkIndexedAccessIndexType(type, accessNode) {
62228             if (!(type.flags & 8388608 /* IndexedAccess */)) {
62229                 return type;
62230             }
62231             // Check if the index type is assignable to 'keyof T' for the object type.
62232             var objectType = type.objectType;
62233             var indexType = type.indexType;
62234             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
62235                 if (accessNode.kind === 195 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
62236                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
62237                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
62238                 }
62239                 return type;
62240             }
62241             // Check if we're indexing with a numeric type and if either object or index types
62242             // is a generic type with a constraint that has a numeric index signature.
62243             var apparentObjectType = getApparentType(objectType);
62244             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
62245                 return type;
62246             }
62247             if (isGenericObjectType(objectType)) {
62248                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
62249                 if (propertyName_1) {
62250                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
62251                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
62252                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
62253                         return errorType;
62254                     }
62255                 }
62256             }
62257             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
62258             return errorType;
62259         }
62260         function checkIndexedAccessType(node) {
62261             checkSourceElement(node.objectType);
62262             checkSourceElement(node.indexType);
62263             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
62264         }
62265         function checkMappedType(node) {
62266             checkSourceElement(node.typeParameter);
62267             checkSourceElement(node.type);
62268             if (!node.type) {
62269                 reportImplicitAny(node, anyType);
62270             }
62271             var type = getTypeFromMappedTypeNode(node);
62272             var constraintType = getConstraintTypeFromMappedType(type);
62273             checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
62274         }
62275         function checkThisType(node) {
62276             getTypeFromThisTypeNode(node);
62277         }
62278         function checkTypeOperator(node) {
62279             checkGrammarTypeOperatorNode(node);
62280             checkSourceElement(node.type);
62281         }
62282         function checkConditionalType(node) {
62283             ts.forEachChild(node, checkSourceElement);
62284         }
62285         function checkInferType(node) {
62286             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 180 /* ConditionalType */ && n.parent.extendsType === n; })) {
62287                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
62288             }
62289             checkSourceElement(node.typeParameter);
62290             registerForUnusedIdentifiersCheck(node);
62291         }
62292         function checkImportType(node) {
62293             checkSourceElement(node.argument);
62294             getTypeFromTypeNode(node);
62295         }
62296         function isPrivateWithinAmbient(node) {
62297             return (ts.hasModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
62298         }
62299         function getEffectiveDeclarationFlags(n, flagsToCheck) {
62300             var flags = ts.getCombinedModifierFlags(n);
62301             // children of classes (even ambient classes) should not be marked as ambient or export
62302             // because those flags have no useful semantics there.
62303             if (n.parent.kind !== 246 /* InterfaceDeclaration */ &&
62304                 n.parent.kind !== 245 /* ClassDeclaration */ &&
62305                 n.parent.kind !== 214 /* ClassExpression */ &&
62306                 n.flags & 8388608 /* Ambient */) {
62307                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
62308                     // It is nested in an ambient context, which means it is automatically exported
62309                     flags |= 1 /* Export */;
62310                 }
62311                 flags |= 2 /* Ambient */;
62312             }
62313             return flags & flagsToCheck;
62314         }
62315         function checkFunctionOrConstructorSymbol(symbol) {
62316             if (!produceDiagnostics) {
62317                 return;
62318             }
62319             function getCanonicalOverload(overloads, implementation) {
62320                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
62321                 // Error on all deviations from this canonical set of flags
62322                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
62323                 // report the errors on those. To achieve this, we will say that the implementation is
62324                 // the canonical signature only if it is in the same container as the first overload
62325                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
62326                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
62327             }
62328             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
62329                 // Error if some overloads have a flag that is not shared by all overloads. To find the
62330                 // deviations, we XOR someOverloadFlags with allOverloadFlags
62331                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
62332                 if (someButNotAllOverloadFlags !== 0) {
62333                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
62334                     ts.forEach(overloads, function (o) {
62335                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
62336                         if (deviation & 1 /* Export */) {
62337                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
62338                         }
62339                         else if (deviation & 2 /* Ambient */) {
62340                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
62341                         }
62342                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
62343                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
62344                         }
62345                         else if (deviation & 128 /* Abstract */) {
62346                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
62347                         }
62348                     });
62349                 }
62350             }
62351             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
62352                 if (someHaveQuestionToken !== allHaveQuestionToken) {
62353                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
62354                     ts.forEach(overloads, function (o) {
62355                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
62356                         if (deviation) {
62357                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
62358                         }
62359                     });
62360                 }
62361             }
62362             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
62363             var someNodeFlags = 0 /* None */;
62364             var allNodeFlags = flagsToCheck;
62365             var someHaveQuestionToken = false;
62366             var allHaveQuestionToken = true;
62367             var hasOverloads = false;
62368             var bodyDeclaration;
62369             var lastSeenNonAmbientDeclaration;
62370             var previousDeclaration;
62371             var declarations = symbol.declarations;
62372             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
62373             function reportImplementationExpectedError(node) {
62374                 if (node.name && ts.nodeIsMissing(node.name)) {
62375                     return;
62376                 }
62377                 var seen = false;
62378                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
62379                     if (seen) {
62380                         return c;
62381                     }
62382                     else {
62383                         seen = c === node;
62384                     }
62385                 });
62386                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
62387                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
62388                 if (subsequentNode && subsequentNode.pos === node.end) {
62389                     if (subsequentNode.kind === node.kind) {
62390                         var errorNode_1 = subsequentNode.name || subsequentNode;
62391                         var subsequentName = subsequentNode.name;
62392                         if (node.name && subsequentName && (
62393                         // both are private identifiers
62394                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
62395                             // Both are computed property names
62396                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
62397                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
62398                             // Both are literal property names that are the same.
62399                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
62400                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
62401                             var reportError = (node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */) &&
62402                                 ts.hasModifier(node, 32 /* Static */) !== ts.hasModifier(subsequentNode, 32 /* Static */);
62403                             // we can get here in two cases
62404                             // 1. mixed static and instance class members
62405                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
62406                             // here we'll report error only for the first case since for second we should already report error in binder
62407                             if (reportError) {
62408                                 var diagnostic = ts.hasModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
62409                                 error(errorNode_1, diagnostic);
62410                             }
62411                             return;
62412                         }
62413                         if (ts.nodeIsPresent(subsequentNode.body)) {
62414                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
62415                             return;
62416                         }
62417                     }
62418                 }
62419                 var errorNode = node.name || node;
62420                 if (isConstructor) {
62421                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
62422                 }
62423                 else {
62424                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
62425                     // the node in question is abstract.
62426                     if (ts.hasModifier(node, 128 /* Abstract */)) {
62427                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
62428                     }
62429                     else {
62430                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
62431                     }
62432                 }
62433             }
62434             var duplicateFunctionDeclaration = false;
62435             var multipleConstructorImplementation = false;
62436             var hasNonAmbientClass = false;
62437             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
62438                 var current = declarations_4[_i];
62439                 var node = current;
62440                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
62441                 var inAmbientContextOrInterface = node.parent.kind === 246 /* InterfaceDeclaration */ || node.parent.kind === 173 /* TypeLiteral */ || inAmbientContext;
62442                 if (inAmbientContextOrInterface) {
62443                     // check if declarations are consecutive only if they are non-ambient
62444                     // 1. ambient declarations can be interleaved
62445                     // i.e. this is legal
62446                     //     declare function foo();
62447                     //     declare function bar();
62448                     //     declare function foo();
62449                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
62450                     previousDeclaration = undefined;
62451                 }
62452                 if ((node.kind === 245 /* ClassDeclaration */ || node.kind === 214 /* ClassExpression */) && !inAmbientContext) {
62453                     hasNonAmbientClass = true;
62454                 }
62455                 if (node.kind === 244 /* FunctionDeclaration */ || node.kind === 161 /* MethodDeclaration */ || node.kind === 160 /* MethodSignature */ || node.kind === 162 /* Constructor */) {
62456                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
62457                     someNodeFlags |= currentNodeFlags;
62458                     allNodeFlags &= currentNodeFlags;
62459                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
62460                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
62461                     if (ts.nodeIsPresent(node.body) && bodyDeclaration) {
62462                         if (isConstructor) {
62463                             multipleConstructorImplementation = true;
62464                         }
62465                         else {
62466                             duplicateFunctionDeclaration = true;
62467                         }
62468                     }
62469                     else if (previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) {
62470                         reportImplementationExpectedError(previousDeclaration);
62471                     }
62472                     if (ts.nodeIsPresent(node.body)) {
62473                         if (!bodyDeclaration) {
62474                             bodyDeclaration = node;
62475                         }
62476                     }
62477                     else {
62478                         hasOverloads = true;
62479                     }
62480                     previousDeclaration = node;
62481                     if (!inAmbientContextOrInterface) {
62482                         lastSeenNonAmbientDeclaration = node;
62483                     }
62484                 }
62485             }
62486             if (multipleConstructorImplementation) {
62487                 ts.forEach(declarations, function (declaration) {
62488                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
62489                 });
62490             }
62491             if (duplicateFunctionDeclaration) {
62492                 ts.forEach(declarations, function (declaration) {
62493                     error(ts.getNameOfDeclaration(declaration), ts.Diagnostics.Duplicate_function_implementation);
62494                 });
62495             }
62496             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
62497                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
62498                 // TODO: The below just replicates our older error from when classes and functions were
62499                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
62500                 // might be warranted. :shrug:
62501                 ts.forEach(declarations, function (declaration) {
62502                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
62503                 });
62504             }
62505             // Abstract methods can't have an implementation -- in particular, they don't need one.
62506             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
62507                 !ts.hasModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
62508                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
62509             }
62510             if (hasOverloads) {
62511                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
62512                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
62513                 if (bodyDeclaration) {
62514                     var signatures = getSignaturesOfSymbol(symbol);
62515                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
62516                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
62517                         var signature = signatures_10[_a];
62518                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
62519                             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));
62520                             break;
62521                         }
62522                     }
62523                 }
62524             }
62525         }
62526         function checkExportsOnMergedDeclarations(node) {
62527             if (!produceDiagnostics) {
62528                 return;
62529             }
62530             // if localSymbol is defined on node then node itself is exported - check is required
62531             var symbol = node.localSymbol;
62532             if (!symbol) {
62533                 // local symbol is undefined => this declaration is non-exported.
62534                 // however symbol might contain other declarations that are exported
62535                 symbol = getSymbolOfNode(node);
62536                 if (!symbol.exportSymbol) {
62537                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
62538                     return;
62539                 }
62540             }
62541             // run the check only for the first declaration in the list
62542             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
62543                 return;
62544             }
62545             var exportedDeclarationSpaces = 0 /* None */;
62546             var nonExportedDeclarationSpaces = 0 /* None */;
62547             var defaultExportedDeclarationSpaces = 0 /* None */;
62548             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
62549                 var d = _a[_i];
62550                 var declarationSpaces = getDeclarationSpaces(d);
62551                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
62552                 if (effectiveDeclarationFlags & 1 /* Export */) {
62553                     if (effectiveDeclarationFlags & 512 /* Default */) {
62554                         defaultExportedDeclarationSpaces |= declarationSpaces;
62555                     }
62556                     else {
62557                         exportedDeclarationSpaces |= declarationSpaces;
62558                     }
62559                 }
62560                 else {
62561                     nonExportedDeclarationSpaces |= declarationSpaces;
62562                 }
62563             }
62564             // Spaces for anything not declared a 'default export'.
62565             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
62566             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
62567             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
62568             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
62569                 // declaration spaces for exported and non-exported declarations intersect
62570                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
62571                     var d = _c[_b];
62572                     var declarationSpaces = getDeclarationSpaces(d);
62573                     var name = ts.getNameOfDeclaration(d);
62574                     // Only error on the declarations that contributed to the intersecting spaces.
62575                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
62576                         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));
62577                     }
62578                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
62579                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
62580                     }
62581                 }
62582             }
62583             function getDeclarationSpaces(decl) {
62584                 var d = decl;
62585                 switch (d.kind) {
62586                     case 246 /* InterfaceDeclaration */:
62587                     case 247 /* TypeAliasDeclaration */:
62588                     // A jsdoc typedef and callback are, by definition, type aliases.
62589                     // falls through
62590                     case 322 /* JSDocTypedefTag */:
62591                     case 315 /* JSDocCallbackTag */:
62592                     case 316 /* JSDocEnumTag */:
62593                         return 2 /* ExportType */;
62594                     case 249 /* ModuleDeclaration */:
62595                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
62596                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
62597                             : 4 /* ExportNamespace */;
62598                     case 245 /* ClassDeclaration */:
62599                     case 248 /* EnumDeclaration */:
62600                     case 284 /* EnumMember */:
62601                         return 2 /* ExportType */ | 1 /* ExportValue */;
62602                     case 290 /* SourceFile */:
62603                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
62604                     case 259 /* ExportAssignment */:
62605                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
62606                         if (!ts.isEntityNameExpression(d.expression)) {
62607                             return 1 /* ExportValue */;
62608                         }
62609                         d = d.expression;
62610                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
62611                     // falls through
62612                     case 253 /* ImportEqualsDeclaration */:
62613                     case 256 /* NamespaceImport */:
62614                     case 255 /* ImportClause */:
62615                         var result_10 = 0 /* None */;
62616                         var target = resolveAlias(getSymbolOfNode(d));
62617                         ts.forEach(target.declarations, function (d) { result_10 |= getDeclarationSpaces(d); });
62618                         return result_10;
62619                     case 242 /* VariableDeclaration */:
62620                     case 191 /* BindingElement */:
62621                     case 244 /* FunctionDeclaration */:
62622                     case 258 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
62623                     case 75 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
62624                         // Identifiers are used as declarations of assignment declarations whose parents may be
62625                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
62626                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
62627                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
62628                         // all of which are pretty much always values, or at least imply a value meaning.
62629                         // It may be apprpriate to treat these as aliases in the future.
62630                         return 1 /* ExportValue */;
62631                     default:
62632                         return ts.Debug.failBadSyntaxKind(d);
62633                 }
62634             }
62635         }
62636         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
62637             var promisedType = getPromisedTypeOfPromise(type, errorNode);
62638             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62639         }
62640         /**
62641          * Gets the "promised type" of a promise.
62642          * @param type The type of the promise.
62643          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
62644          */
62645         function getPromisedTypeOfPromise(type, errorNode) {
62646             //
62647             //  { // type
62648             //      then( // thenFunction
62649             //          onfulfilled: ( // onfulfilledParameterType
62650             //              value: T // valueParameterType
62651             //          ) => any
62652             //      ): any;
62653             //  }
62654             //
62655             if (isTypeAny(type)) {
62656                 return undefined;
62657             }
62658             var typeAsPromise = type;
62659             if (typeAsPromise.promisedTypeOfPromise) {
62660                 return typeAsPromise.promisedTypeOfPromise;
62661             }
62662             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
62663                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
62664             }
62665             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
62666             if (isTypeAny(thenFunction)) {
62667                 return undefined;
62668             }
62669             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
62670             if (thenSignatures.length === 0) {
62671                 if (errorNode) {
62672                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
62673                 }
62674                 return undefined;
62675             }
62676             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
62677             if (isTypeAny(onfulfilledParameterType)) {
62678                 return undefined;
62679             }
62680             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
62681             if (onfulfilledParameterSignatures.length === 0) {
62682                 if (errorNode) {
62683                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
62684                 }
62685                 return undefined;
62686             }
62687             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
62688         }
62689         /**
62690          * Gets the "awaited type" of a type.
62691          * @param type The type to await.
62692          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
62693          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
62694          * The runtime behavior of the `await` keyword.
62695          */
62696         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62697             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
62698             return awaitedType || errorType;
62699         }
62700         /**
62701          * Determines whether a type has a callable `then` member.
62702          */
62703         function isThenableType(type) {
62704             var thenFunction = getTypeOfPropertyOfType(type, "then");
62705             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
62706         }
62707         /**
62708          * Gets the "awaited type" of a type.
62709          *
62710          * The "awaited type" of an expression is its "promised type" if the expression is a
62711          * Promise-like type; otherwise, it is the type of the expression. If the "promised
62712          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
62713          * non-promise type is found.
62714          *
62715          * This is used to reflect the runtime behavior of the `await` keyword.
62716          */
62717         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
62718             if (isTypeAny(type)) {
62719                 return type;
62720             }
62721             var typeAsAwaitable = type;
62722             if (typeAsAwaitable.awaitedTypeOfType) {
62723                 return typeAsAwaitable.awaitedTypeOfType;
62724             }
62725             // For a union, get a union of the awaited types of each constituent.
62726             //
62727             return typeAsAwaitable.awaitedTypeOfType =
62728                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
62729         }
62730         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
62731             var typeAsAwaitable = type;
62732             if (typeAsAwaitable.awaitedTypeOfType) {
62733                 return typeAsAwaitable.awaitedTypeOfType;
62734             }
62735             var promisedType = getPromisedTypeOfPromise(type);
62736             if (promisedType) {
62737                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
62738                     // Verify that we don't have a bad actor in the form of a promise whose
62739                     // promised type is the same as the promise type, or a mutually recursive
62740                     // promise. If so, we return undefined as we cannot guess the shape. If this
62741                     // were the actual case in the JavaScript, this Promise would never resolve.
62742                     //
62743                     // An example of a bad actor with a singly-recursive promise type might
62744                     // be:
62745                     //
62746                     //  interface BadPromise {
62747                     //      then(
62748                     //          onfulfilled: (value: BadPromise) => any,
62749                     //          onrejected: (error: any) => any): BadPromise;
62750                     //  }
62751                     //
62752                     // The above interface will pass the PromiseLike check, and return a
62753                     // promised type of `BadPromise`. Since this is a self reference, we
62754                     // don't want to keep recursing ad infinitum.
62755                     //
62756                     // An example of a bad actor in the form of a mutually-recursive
62757                     // promise type might be:
62758                     //
62759                     //  interface BadPromiseA {
62760                     //      then(
62761                     //          onfulfilled: (value: BadPromiseB) => any,
62762                     //          onrejected: (error: any) => any): BadPromiseB;
62763                     //  }
62764                     //
62765                     //  interface BadPromiseB {
62766                     //      then(
62767                     //          onfulfilled: (value: BadPromiseA) => any,
62768                     //          onrejected: (error: any) => any): BadPromiseA;
62769                     //  }
62770                     //
62771                     if (errorNode) {
62772                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
62773                     }
62774                     return undefined;
62775                 }
62776                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
62777                 // See the comments above for more information.
62778                 awaitedTypeStack.push(type.id);
62779                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
62780                 awaitedTypeStack.pop();
62781                 if (!awaitedType) {
62782                     return undefined;
62783                 }
62784                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
62785             }
62786             // The type was not a promise, so it could not be unwrapped any further.
62787             // As long as the type does not have a callable "then" property, it is
62788             // safe to return the type; otherwise, an error is reported and we return
62789             // undefined.
62790             //
62791             // An example of a non-promise "thenable" might be:
62792             //
62793             //  await { then(): void {} }
62794             //
62795             // The "thenable" does not match the minimal definition for a promise. When
62796             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
62797             // will never settle. We treat this as an error to help flag an early indicator
62798             // of a runtime problem. If the user wants to return this value from an async
62799             // function, they would need to wrap it in some other value. If they want it to
62800             // be treated as a promise, they can cast to <any>.
62801             if (isThenableType(type)) {
62802                 if (errorNode) {
62803                     if (!diagnosticMessage)
62804                         return ts.Debug.fail();
62805                     error(errorNode, diagnosticMessage, arg0);
62806                 }
62807                 return undefined;
62808             }
62809             return typeAsAwaitable.awaitedTypeOfType = type;
62810         }
62811         /**
62812          * Checks the return type of an async function to ensure it is a compatible
62813          * Promise implementation.
62814          *
62815          * This checks that an async function has a valid Promise-compatible return type.
62816          * An async function has a valid Promise-compatible return type if the resolved value
62817          * of the return type has a construct signature that takes in an `initializer` function
62818          * that in turn supplies a `resolve` function as one of its arguments and results in an
62819          * object with a callable `then` signature.
62820          *
62821          * @param node The signature to check
62822          */
62823         function checkAsyncFunctionReturnType(node, returnTypeNode) {
62824             // As part of our emit for an async function, we will need to emit the entity name of
62825             // the return type annotation as an expression. To meet the necessary runtime semantics
62826             // for __awaiter, we must also check that the type of the declaration (e.g. the static
62827             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
62828             //
62829             // An example might be (from lib.es6.d.ts):
62830             //
62831             //  interface Promise<T> { ... }
62832             //  interface PromiseConstructor {
62833             //      new <T>(...): Promise<T>;
62834             //  }
62835             //  declare var Promise: PromiseConstructor;
62836             //
62837             // When an async function declares a return type annotation of `Promise<T>`, we
62838             // need to get the type of the `Promise` variable declaration above, which would
62839             // be `PromiseConstructor`.
62840             //
62841             // The same case applies to a class:
62842             //
62843             //  declare class Promise<T> {
62844             //      constructor(...);
62845             //      then<U>(...): Promise<U>;
62846             //  }
62847             //
62848             var returnType = getTypeFromTypeNode(returnTypeNode);
62849             if (languageVersion >= 2 /* ES2015 */) {
62850                 if (returnType === errorType) {
62851                     return;
62852                 }
62853                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
62854                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
62855                     // The promise type was not a valid type reference to the global promise type, so we
62856                     // report an error and return the unknown type.
62857                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
62858                     return;
62859                 }
62860             }
62861             else {
62862                 // Always mark the type node as referenced if it points to a value
62863                 markTypeNodeAsReferenced(returnTypeNode);
62864                 if (returnType === errorType) {
62865                     return;
62866                 }
62867                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
62868                 if (promiseConstructorName === undefined) {
62869                     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));
62870                     return;
62871                 }
62872                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
62873                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
62874                 if (promiseConstructorType === errorType) {
62875                     if (promiseConstructorName.kind === 75 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
62876                         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);
62877                     }
62878                     else {
62879                         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));
62880                     }
62881                     return;
62882                 }
62883                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
62884                 if (globalPromiseConstructorLikeType === emptyObjectType) {
62885                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
62886                     // compatibility with __awaiter.
62887                     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));
62888                     return;
62889                 }
62890                 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)) {
62891                     return;
62892                 }
62893                 // Verify there is no local declaration that could collide with the promise constructor.
62894                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
62895                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
62896                 if (collidingSymbol) {
62897                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
62898                     return;
62899                 }
62900             }
62901             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);
62902         }
62903         /** Check a decorator */
62904         function checkDecorator(node) {
62905             var signature = getResolvedSignature(node);
62906             var returnType = getReturnTypeOfSignature(signature);
62907             if (returnType.flags & 1 /* Any */) {
62908                 return;
62909             }
62910             var expectedReturnType;
62911             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
62912             var errorInfo;
62913             switch (node.parent.kind) {
62914                 case 245 /* ClassDeclaration */:
62915                     var classSymbol = getSymbolOfNode(node.parent);
62916                     var classConstructorType = getTypeOfSymbol(classSymbol);
62917                     expectedReturnType = getUnionType([classConstructorType, voidType]);
62918                     break;
62919                 case 156 /* Parameter */:
62920                     expectedReturnType = voidType;
62921                     errorInfo = ts.chainDiagnosticMessages(
62922                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
62923                     break;
62924                 case 159 /* PropertyDeclaration */:
62925                     expectedReturnType = voidType;
62926                     errorInfo = ts.chainDiagnosticMessages(
62927                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
62928                     break;
62929                 case 161 /* MethodDeclaration */:
62930                 case 163 /* GetAccessor */:
62931                 case 164 /* SetAccessor */:
62932                     var methodType = getTypeOfNode(node.parent);
62933                     var descriptorType = createTypedPropertyDescriptorType(methodType);
62934                     expectedReturnType = getUnionType([descriptorType, voidType]);
62935                     break;
62936                 default:
62937                     return ts.Debug.fail();
62938             }
62939             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
62940         }
62941         /**
62942          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
62943          * marked as referenced to prevent import elision.
62944          */
62945         function markTypeNodeAsReferenced(node) {
62946             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
62947         }
62948         function markEntityNameOrEntityExpressionAsReference(typeName) {
62949             if (!typeName)
62950                 return;
62951             var rootName = ts.getFirstIdentifier(typeName);
62952             var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
62953             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
62954             if (rootSymbol
62955                 && rootSymbol.flags & 2097152 /* Alias */
62956                 && symbolIsValue(rootSymbol)
62957                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
62958                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
62959                 markAliasSymbolAsReferenced(rootSymbol);
62960             }
62961         }
62962         /**
62963          * This function marks the type used for metadata decorator as referenced if it is import
62964          * from external module.
62965          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
62966          * union and intersection type
62967          * @param node
62968          */
62969         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
62970             var entityName = getEntityNameForDecoratorMetadata(node);
62971             if (entityName && ts.isEntityName(entityName)) {
62972                 markEntityNameOrEntityExpressionAsReference(entityName);
62973             }
62974         }
62975         function getEntityNameForDecoratorMetadata(node) {
62976             if (node) {
62977                 switch (node.kind) {
62978                     case 179 /* IntersectionType */:
62979                     case 178 /* UnionType */:
62980                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
62981                     case 180 /* ConditionalType */:
62982                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
62983                     case 182 /* ParenthesizedType */:
62984                         return getEntityNameForDecoratorMetadata(node.type);
62985                     case 169 /* TypeReference */:
62986                         return node.typeName;
62987                 }
62988             }
62989         }
62990         function getEntityNameForDecoratorMetadataFromTypeList(types) {
62991             var commonEntityName;
62992             for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
62993                 var typeNode = types_20[_i];
62994                 while (typeNode.kind === 182 /* ParenthesizedType */) {
62995                     typeNode = typeNode.type; // Skip parens if need be
62996                 }
62997                 if (typeNode.kind === 137 /* NeverKeyword */) {
62998                     continue; // Always elide `never` from the union/intersection if possible
62999                 }
63000                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
63001                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
63002                 }
63003                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
63004                 if (!individualEntityName) {
63005                     // Individual is something like string number
63006                     // So it would be serialized to either that type or object
63007                     // Safe to return here
63008                     return undefined;
63009                 }
63010                 if (commonEntityName) {
63011                     // Note this is in sync with the transformation that happens for type node.
63012                     // Keep this in sync with serializeUnionOrIntersectionType
63013                     // Verify if they refer to same entity and is identifier
63014                     // return undefined if they dont match because we would emit object
63015                     if (!ts.isIdentifier(commonEntityName) ||
63016                         !ts.isIdentifier(individualEntityName) ||
63017                         commonEntityName.escapedText !== individualEntityName.escapedText) {
63018                         return undefined;
63019                     }
63020                 }
63021                 else {
63022                     commonEntityName = individualEntityName;
63023                 }
63024             }
63025             return commonEntityName;
63026         }
63027         function getParameterTypeNodeForDecoratorCheck(node) {
63028             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
63029             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
63030         }
63031         /** Check the decorators of a node */
63032         function checkDecorators(node) {
63033             if (!node.decorators) {
63034                 return;
63035             }
63036             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
63037             // checkGrammarDecorators.
63038             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
63039                 return;
63040             }
63041             if (!compilerOptions.experimentalDecorators) {
63042                 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);
63043             }
63044             var firstDecorator = node.decorators[0];
63045             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
63046             if (node.kind === 156 /* Parameter */) {
63047                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
63048             }
63049             if (compilerOptions.emitDecoratorMetadata) {
63050                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
63051                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
63052                 switch (node.kind) {
63053                     case 245 /* ClassDeclaration */:
63054                         var constructor = ts.getFirstConstructorWithBody(node);
63055                         if (constructor) {
63056                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
63057                                 var parameter = _a[_i];
63058                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63059                             }
63060                         }
63061                         break;
63062                     case 163 /* GetAccessor */:
63063                     case 164 /* SetAccessor */:
63064                         var otherKind = node.kind === 163 /* GetAccessor */ ? 164 /* SetAccessor */ : 163 /* GetAccessor */;
63065                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
63066                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
63067                         break;
63068                     case 161 /* MethodDeclaration */:
63069                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
63070                             var parameter = _c[_b];
63071                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63072                         }
63073                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
63074                         break;
63075                     case 159 /* PropertyDeclaration */:
63076                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
63077                         break;
63078                     case 156 /* Parameter */:
63079                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
63080                         var containingSignature = node.parent;
63081                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
63082                             var parameter = _e[_d];
63083                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
63084                         }
63085                         break;
63086                 }
63087             }
63088             ts.forEach(node.decorators, checkDecorator);
63089         }
63090         function checkFunctionDeclaration(node) {
63091             if (produceDiagnostics) {
63092                 checkFunctionOrMethodDeclaration(node);
63093                 checkGrammarForGenerator(node);
63094                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63095                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63096             }
63097         }
63098         function checkJSDocTypeAliasTag(node) {
63099             if (!node.typeExpression) {
63100                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
63101                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
63102             }
63103             if (node.name) {
63104                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
63105             }
63106             checkSourceElement(node.typeExpression);
63107         }
63108         function checkJSDocTemplateTag(node) {
63109             checkSourceElement(node.constraint);
63110             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
63111                 var tp = _a[_i];
63112                 checkSourceElement(tp);
63113             }
63114         }
63115         function checkJSDocTypeTag(node) {
63116             checkSourceElement(node.typeExpression);
63117         }
63118         function checkJSDocParameterTag(node) {
63119             checkSourceElement(node.typeExpression);
63120             if (!ts.getParameterSymbolFromJSDoc(node)) {
63121                 var decl = ts.getHostSignatureFromJSDoc(node);
63122                 // don't issue an error for invalid hosts -- just functions --
63123                 // and give a better error message when the host function mentions `arguments`
63124                 // but the tag doesn't have an array type
63125                 if (decl) {
63126                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
63127                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
63128                         return;
63129                     }
63130                     if (!containsArgumentsReference(decl)) {
63131                         if (ts.isQualifiedName(node.name)) {
63132                             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));
63133                         }
63134                         else {
63135                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
63136                         }
63137                     }
63138                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
63139                         node.typeExpression && node.typeExpression.type &&
63140                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
63141                         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 === 153 /* QualifiedName */ ? node.name.right : node.name));
63142                     }
63143                 }
63144             }
63145         }
63146         function checkJSDocPropertyTag(node) {
63147             checkSourceElement(node.typeExpression);
63148         }
63149         function checkJSDocFunctionType(node) {
63150             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
63151                 reportImplicitAny(node, anyType);
63152             }
63153             checkSignatureDeclaration(node);
63154         }
63155         function checkJSDocImplementsTag(node) {
63156             var classLike = ts.getEffectiveJSDocHost(node);
63157             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63158                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63159             }
63160         }
63161         function checkJSDocAugmentsTag(node) {
63162             var classLike = ts.getEffectiveJSDocHost(node);
63163             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
63164                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
63165                 return;
63166             }
63167             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
63168             ts.Debug.assert(augmentsTags.length > 0);
63169             if (augmentsTags.length > 1) {
63170                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
63171             }
63172             var name = getIdentifierFromEntityNameExpression(node.class.expression);
63173             var extend = ts.getClassExtendsHeritageElement(classLike);
63174             if (extend) {
63175                 var className = getIdentifierFromEntityNameExpression(extend.expression);
63176                 if (className && name.escapedText !== className.escapedText) {
63177                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
63178                 }
63179             }
63180         }
63181         function getIdentifierFromEntityNameExpression(node) {
63182             switch (node.kind) {
63183                 case 75 /* Identifier */:
63184                     return node;
63185                 case 194 /* PropertyAccessExpression */:
63186                     return node.name;
63187                 default:
63188                     return undefined;
63189             }
63190         }
63191         function checkFunctionOrMethodDeclaration(node) {
63192             checkDecorators(node);
63193             checkSignatureDeclaration(node);
63194             var functionFlags = ts.getFunctionFlags(node);
63195             // Do not use hasDynamicName here, because that returns false for well known symbols.
63196             // We want to perform checkComputedPropertyName for all computed properties, including
63197             // well known symbols.
63198             if (node.name && node.name.kind === 154 /* ComputedPropertyName */) {
63199                 // This check will account for methods in class/interface declarations,
63200                 // as well as accessors in classes/object literals
63201                 checkComputedPropertyName(node.name);
63202             }
63203             if (!hasNonBindableDynamicName(node)) {
63204                 // first we want to check the local symbol that contain this declaration
63205                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
63206                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
63207                 var symbol = getSymbolOfNode(node);
63208                 var localSymbol = node.localSymbol || symbol;
63209                 // Since the javascript won't do semantic analysis like typescript,
63210                 // if the javascript file comes before the typescript file and both contain same name functions,
63211                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
63212                 var firstDeclaration = ts.find(localSymbol.declarations, 
63213                 // Get first non javascript function declaration
63214                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
63215                 // Only type check the symbol once
63216                 if (node === firstDeclaration) {
63217                     checkFunctionOrConstructorSymbol(localSymbol);
63218                 }
63219                 if (symbol.parent) {
63220                     // run check once for the first declaration
63221                     if (ts.getDeclarationOfKind(symbol, node.kind) === node) {
63222                         // run check on export symbol to check that modifiers agree across all exported declarations
63223                         checkFunctionOrConstructorSymbol(symbol);
63224                     }
63225                 }
63226             }
63227             var body = node.kind === 160 /* MethodSignature */ ? undefined : node.body;
63228             checkSourceElement(body);
63229             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
63230             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
63231                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
63232                 // in an ambient context
63233                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
63234                     reportImplicitAny(node, anyType);
63235                 }
63236                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
63237                     // A generator with a body and no type annotation can still cause errors. It can error if the
63238                     // yielded values have no common supertype, or it can give an implicit any error if it has no
63239                     // yielded values. The only way to trigger these errors is to try checking its return type.
63240                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
63241                 }
63242             }
63243             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
63244             if (ts.isInJSFile(node)) {
63245                 var typeTag = ts.getJSDocTypeTag(node);
63246                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
63247                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
63248                 }
63249             }
63250         }
63251         function registerForUnusedIdentifiersCheck(node) {
63252             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
63253             if (produceDiagnostics) {
63254                 var sourceFile = ts.getSourceFileOfNode(node);
63255                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
63256                 if (!potentiallyUnusedIdentifiers) {
63257                     potentiallyUnusedIdentifiers = [];
63258                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
63259                 }
63260                 // TODO: GH#22580
63261                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
63262                 potentiallyUnusedIdentifiers.push(node);
63263             }
63264         }
63265         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
63266             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
63267                 var node = potentiallyUnusedIdentifiers_1[_i];
63268                 switch (node.kind) {
63269                     case 245 /* ClassDeclaration */:
63270                     case 214 /* ClassExpression */:
63271                         checkUnusedClassMembers(node, addDiagnostic);
63272                         checkUnusedTypeParameters(node, addDiagnostic);
63273                         break;
63274                     case 290 /* SourceFile */:
63275                     case 249 /* ModuleDeclaration */:
63276                     case 223 /* Block */:
63277                     case 251 /* CaseBlock */:
63278                     case 230 /* ForStatement */:
63279                     case 231 /* ForInStatement */:
63280                     case 232 /* ForOfStatement */:
63281                         checkUnusedLocalsAndParameters(node, addDiagnostic);
63282                         break;
63283                     case 162 /* Constructor */:
63284                     case 201 /* FunctionExpression */:
63285                     case 244 /* FunctionDeclaration */:
63286                     case 202 /* ArrowFunction */:
63287                     case 161 /* MethodDeclaration */:
63288                     case 163 /* GetAccessor */:
63289                     case 164 /* SetAccessor */:
63290                         if (node.body) { // Don't report unused parameters in overloads
63291                             checkUnusedLocalsAndParameters(node, addDiagnostic);
63292                         }
63293                         checkUnusedTypeParameters(node, addDiagnostic);
63294                         break;
63295                     case 160 /* MethodSignature */:
63296                     case 165 /* CallSignature */:
63297                     case 166 /* ConstructSignature */:
63298                     case 170 /* FunctionType */:
63299                     case 171 /* ConstructorType */:
63300                     case 247 /* TypeAliasDeclaration */:
63301                     case 246 /* InterfaceDeclaration */:
63302                         checkUnusedTypeParameters(node, addDiagnostic);
63303                         break;
63304                     case 181 /* InferType */:
63305                         checkUnusedInferTypeParameter(node, addDiagnostic);
63306                         break;
63307                     default:
63308                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
63309                 }
63310             }
63311         }
63312         function errorUnusedLocal(declaration, name, addDiagnostic) {
63313             var node = ts.getNameOfDeclaration(declaration) || declaration;
63314             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
63315             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
63316         }
63317         function isIdentifierThatStartsWithUnderscore(node) {
63318             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
63319         }
63320         function checkUnusedClassMembers(node, addDiagnostic) {
63321             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
63322                 var member = _a[_i];
63323                 switch (member.kind) {
63324                     case 161 /* MethodDeclaration */:
63325                     case 159 /* PropertyDeclaration */:
63326                     case 163 /* GetAccessor */:
63327                     case 164 /* SetAccessor */:
63328                         if (member.kind === 164 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
63329                             // Already would have reported an error on the getter.
63330                             break;
63331                         }
63332                         var symbol = getSymbolOfNode(member);
63333                         if (!symbol.isReferenced
63334                             && (ts.hasModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
63335                             && !(member.flags & 8388608 /* Ambient */)) {
63336                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
63337                         }
63338                         break;
63339                     case 162 /* Constructor */:
63340                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
63341                             var parameter = _c[_b];
63342                             if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) {
63343                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
63344                             }
63345                         }
63346                         break;
63347                     case 167 /* IndexSignature */:
63348                     case 222 /* SemicolonClassElement */:
63349                         // Can't be private
63350                         break;
63351                     default:
63352                         ts.Debug.fail();
63353                 }
63354             }
63355         }
63356         function checkUnusedInferTypeParameter(node, addDiagnostic) {
63357             var typeParameter = node.typeParameter;
63358             if (isTypeParameterUnused(typeParameter)) {
63359                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
63360             }
63361         }
63362         function checkUnusedTypeParameters(node, addDiagnostic) {
63363             // Only report errors on the last declaration for the type parameter container;
63364             // this ensures that all uses have been accounted for.
63365             if (ts.last(getSymbolOfNode(node).declarations) !== node)
63366                 return;
63367             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
63368             var seenParentsWithEveryUnused = new ts.NodeSet();
63369             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
63370                 var typeParameter = typeParameters_3[_i];
63371                 if (!isTypeParameterUnused(typeParameter))
63372                     continue;
63373                 var name = ts.idText(typeParameter.name);
63374                 var parent = typeParameter.parent;
63375                 if (parent.kind !== 181 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
63376                     if (seenParentsWithEveryUnused.tryAdd(parent)) {
63377                         var range = ts.isJSDocTemplateTag(parent)
63378                             // Whole @template tag
63379                             ? ts.rangeOfNode(parent)
63380                             // Include the `<>` in the error message
63381                             : ts.rangeOfTypeParameters(parent.typeParameters);
63382                         var only = parent.typeParameters.length === 1;
63383                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
63384                         var arg0 = only ? name : undefined;
63385                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
63386                     }
63387                 }
63388                 else {
63389                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
63390                 }
63391             }
63392         }
63393         function isTypeParameterUnused(typeParameter) {
63394             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
63395         }
63396         function addToGroup(map, key, value, getKey) {
63397             var keyString = String(getKey(key));
63398             var group = map.get(keyString);
63399             if (group) {
63400                 group[1].push(value);
63401             }
63402             else {
63403                 map.set(keyString, [key, [value]]);
63404             }
63405         }
63406         function tryGetRootParameterDeclaration(node) {
63407             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
63408         }
63409         function isValidUnusedLocalDeclaration(declaration) {
63410             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
63411                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
63412                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
63413                         ts.isForOfStatement(ancestor) ? true : "quit";
63414                 });
63415             }
63416             return ts.isAmbientModule(declaration) ||
63417                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
63418         }
63419         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
63420             // 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.
63421             var unusedImports = ts.createMap();
63422             var unusedDestructures = ts.createMap();
63423             var unusedVariables = ts.createMap();
63424             nodeWithLocals.locals.forEach(function (local) {
63425                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
63426                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
63427                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
63428                     return;
63429                 }
63430                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
63431                     var declaration = _a[_i];
63432                     if (isValidUnusedLocalDeclaration(declaration)) {
63433                         continue;
63434                     }
63435                     if (isImportedDeclaration(declaration)) {
63436                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
63437                     }
63438                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
63439                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
63440                         var lastElement = ts.last(declaration.parent.elements);
63441                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
63442                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
63443                         }
63444                     }
63445                     else if (ts.isVariableDeclaration(declaration)) {
63446                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
63447                     }
63448                     else {
63449                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
63450                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
63451                         if (parameter && name) {
63452                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
63453                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
63454                             }
63455                         }
63456                         else {
63457                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
63458                         }
63459                     }
63460                 }
63461             });
63462             unusedImports.forEach(function (_a) {
63463                 var importClause = _a[0], unuseds = _a[1];
63464                 var importDecl = importClause.parent;
63465                 var nDeclarations = (importClause.name ? 1 : 0) +
63466                     (importClause.namedBindings ?
63467                         (importClause.namedBindings.kind === 256 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
63468                         : 0);
63469                 if (nDeclarations === unuseds.length) {
63470                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
63471                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
63472                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
63473                 }
63474                 else {
63475                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
63476                         var unused = unuseds_1[_i];
63477                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
63478                     }
63479                 }
63480             });
63481             unusedDestructures.forEach(function (_a) {
63482                 var bindingPattern = _a[0], bindingElements = _a[1];
63483                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
63484                 if (bindingPattern.elements.length === bindingElements.length) {
63485                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 242 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 243 /* VariableDeclarationList */) {
63486                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
63487                     }
63488                     else {
63489                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
63490                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
63491                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
63492                     }
63493                 }
63494                 else {
63495                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
63496                         var e = bindingElements_1[_i];
63497                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
63498                     }
63499                 }
63500             });
63501             unusedVariables.forEach(function (_a) {
63502                 var declarationList = _a[0], declarations = _a[1];
63503                 if (declarationList.declarations.length === declarations.length) {
63504                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
63505                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
63506                         : ts.createDiagnosticForNode(declarationList.parent.kind === 225 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
63507                 }
63508                 else {
63509                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
63510                         var decl = declarations_5[_i];
63511                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
63512                     }
63513                 }
63514             });
63515         }
63516         function bindingNameText(name) {
63517             switch (name.kind) {
63518                 case 75 /* Identifier */:
63519                     return ts.idText(name);
63520                 case 190 /* ArrayBindingPattern */:
63521                 case 189 /* ObjectBindingPattern */:
63522                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
63523                 default:
63524                     return ts.Debug.assertNever(name);
63525             }
63526         }
63527         function isImportedDeclaration(node) {
63528             return node.kind === 255 /* ImportClause */ || node.kind === 258 /* ImportSpecifier */ || node.kind === 256 /* NamespaceImport */;
63529         }
63530         function importClauseFromImported(decl) {
63531             return decl.kind === 255 /* ImportClause */ ? decl : decl.kind === 256 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
63532         }
63533         function checkBlock(node) {
63534             // Grammar checking for SyntaxKind.Block
63535             if (node.kind === 223 /* Block */) {
63536                 checkGrammarStatementInAmbientContext(node);
63537             }
63538             if (ts.isFunctionOrModuleBlock(node)) {
63539                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
63540                 ts.forEach(node.statements, checkSourceElement);
63541                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
63542             }
63543             else {
63544                 ts.forEach(node.statements, checkSourceElement);
63545             }
63546             if (node.locals) {
63547                 registerForUnusedIdentifiersCheck(node);
63548             }
63549         }
63550         function checkCollisionWithArgumentsInGeneratedCode(node) {
63551             // no rest parameters \ declaration context \ overload - no codegen impact
63552             if (languageVersion >= 2 /* ES2015 */ || compilerOptions.noEmit || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
63553                 return;
63554             }
63555             ts.forEach(node.parameters, function (p) {
63556                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
63557                     error(p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
63558                 }
63559             });
63560         }
63561         function needCollisionCheckForIdentifier(node, identifier, name) {
63562             if (!(identifier && identifier.escapedText === name)) {
63563                 return false;
63564             }
63565             if (node.kind === 159 /* PropertyDeclaration */ ||
63566                 node.kind === 158 /* PropertySignature */ ||
63567                 node.kind === 161 /* MethodDeclaration */ ||
63568                 node.kind === 160 /* MethodSignature */ ||
63569                 node.kind === 163 /* GetAccessor */ ||
63570                 node.kind === 164 /* SetAccessor */) {
63571                 // it is ok to have member named '_super' or '_this' - member access is always qualified
63572                 return false;
63573             }
63574             if (node.flags & 8388608 /* Ambient */) {
63575                 // ambient context - no codegen impact
63576                 return false;
63577             }
63578             var root = ts.getRootDeclaration(node);
63579             if (root.kind === 156 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
63580                 // just an overload - no codegen impact
63581                 return false;
63582             }
63583             return true;
63584         }
63585         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
63586         function checkIfThisIsCapturedInEnclosingScope(node) {
63587             ts.findAncestor(node, function (current) {
63588                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
63589                     var isDeclaration_1 = node.kind !== 75 /* Identifier */;
63590                     if (isDeclaration_1) {
63591                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
63592                     }
63593                     else {
63594                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
63595                     }
63596                     return true;
63597                 }
63598                 return false;
63599             });
63600         }
63601         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
63602             ts.findAncestor(node, function (current) {
63603                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
63604                     var isDeclaration_2 = node.kind !== 75 /* Identifier */;
63605                     if (isDeclaration_2) {
63606                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
63607                     }
63608                     else {
63609                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
63610                     }
63611                     return true;
63612                 }
63613                 return false;
63614             });
63615         }
63616         function checkWeakMapCollision(node) {
63617             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
63618             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
63619                 error(node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
63620             }
63621         }
63622         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
63623             // No need to check for require or exports for ES6 modules and later
63624             if (moduleKind >= ts.ModuleKind.ES2015 || compilerOptions.noEmit) {
63625                 return;
63626             }
63627             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
63628                 return;
63629             }
63630             // Uninstantiated modules shouldnt do this check
63631             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63632                 return;
63633             }
63634             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63635             var parent = getDeclarationContainer(node);
63636             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
63637                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
63638                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
63639             }
63640         }
63641         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
63642             if (languageVersion >= 4 /* ES2017 */ || compilerOptions.noEmit || !needCollisionCheckForIdentifier(node, name, "Promise")) {
63643                 return;
63644             }
63645             // Uninstantiated modules shouldnt do this check
63646             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
63647                 return;
63648             }
63649             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
63650             var parent = getDeclarationContainer(node);
63651             if (parent.kind === 290 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
63652                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
63653                 error(name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, ts.declarationNameToString(name), ts.declarationNameToString(name));
63654             }
63655         }
63656         function checkVarDeclaredNamesNotShadowed(node) {
63657             // - ScriptBody : StatementList
63658             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63659             // also occurs in the VarDeclaredNames of StatementList.
63660             // - Block : { StatementList }
63661             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
63662             // also occurs in the VarDeclaredNames of StatementList.
63663             // Variable declarations are hoisted to the top of their function scope. They can shadow
63664             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
63665             // by the binder as the declaration scope is different.
63666             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
63667             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
63668             // block declared value. this is fine for let, but not const.
63669             // Only consider declarations with initializers, uninitialized const declarations will not
63670             // step on a let/const variable.
63671             // Do not consider const and const declarations, as duplicate block-scoped declarations
63672             // are handled by the binder.
63673             // We are only looking for const declarations that step on let\const declarations from a
63674             // different scope. e.g.:
63675             //      {
63676             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
63677             //          const x = 0; // symbol for this declaration will be 'symbol'
63678             //      }
63679             // skip block-scoped variables and parameters
63680             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
63681                 return;
63682             }
63683             // skip variable declarations that don't have initializers
63684             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
63685             // so we'll always treat binding elements as initialized
63686             if (node.kind === 242 /* VariableDeclaration */ && !node.initializer) {
63687                 return;
63688             }
63689             var symbol = getSymbolOfNode(node);
63690             if (symbol.flags & 1 /* FunctionScopedVariable */) {
63691                 if (!ts.isIdentifier(node.name))
63692                     return ts.Debug.fail();
63693                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
63694                 if (localDeclarationSymbol &&
63695                     localDeclarationSymbol !== symbol &&
63696                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
63697                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
63698                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 243 /* VariableDeclarationList */);
63699                         var container = varDeclList.parent.kind === 225 /* VariableStatement */ && varDeclList.parent.parent
63700                             ? varDeclList.parent.parent
63701                             : undefined;
63702                         // names of block-scoped and function scoped variables can collide only
63703                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
63704                         var namesShareScope = container &&
63705                             (container.kind === 223 /* Block */ && ts.isFunctionLike(container.parent) ||
63706                                 container.kind === 250 /* ModuleBlock */ ||
63707                                 container.kind === 249 /* ModuleDeclaration */ ||
63708                                 container.kind === 290 /* SourceFile */);
63709                         // here we know that function scoped variable is shadowed by block scoped one
63710                         // if they are defined in the same scope - binder has already reported redeclaration error
63711                         // otherwise if variable has an initializer - show error that initialization will fail
63712                         // since LHS will be block scoped name instead of function scoped
63713                         if (!namesShareScope) {
63714                             var name = symbolToString(localDeclarationSymbol);
63715                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
63716                         }
63717                     }
63718                 }
63719             }
63720         }
63721         function convertAutoToAny(type) {
63722             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
63723         }
63724         // Check variable, parameter, or property declaration
63725         function checkVariableLikeDeclaration(node) {
63726             checkDecorators(node);
63727             if (!ts.isBindingElement(node)) {
63728                 checkSourceElement(node.type);
63729             }
63730             // JSDoc `function(string, string): string` syntax results in parameters with no name
63731             if (!node.name) {
63732                 return;
63733             }
63734             // For a computed property, just check the initializer and exit
63735             // Do not use hasDynamicName here, because that returns false for well known symbols.
63736             // We want to perform checkComputedPropertyName for all computed properties, including
63737             // well known symbols.
63738             if (node.name.kind === 154 /* ComputedPropertyName */) {
63739                 checkComputedPropertyName(node.name);
63740                 if (node.initializer) {
63741                     checkExpressionCached(node.initializer);
63742                 }
63743             }
63744             if (node.kind === 191 /* BindingElement */) {
63745                 if (node.parent.kind === 189 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
63746                     checkExternalEmitHelpers(node, 4 /* Rest */);
63747                 }
63748                 // check computed properties inside property names of binding elements
63749                 if (node.propertyName && node.propertyName.kind === 154 /* ComputedPropertyName */) {
63750                     checkComputedPropertyName(node.propertyName);
63751                 }
63752                 // check private/protected variable access
63753                 var parent = node.parent.parent;
63754                 var parentType = getTypeForBindingElementParent(parent);
63755                 var name = node.propertyName || node.name;
63756                 if (parentType && !ts.isBindingPattern(name)) {
63757                     var exprType = getLiteralTypeFromPropertyName(name);
63758                     if (isTypeUsableAsPropertyName(exprType)) {
63759                         var nameText = getPropertyNameFromType(exprType);
63760                         var property = getPropertyOfType(parentType, nameText);
63761                         if (property) {
63762                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
63763                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 102 /* SuperKeyword */, parentType, property);
63764                         }
63765                     }
63766                 }
63767             }
63768             // For a binding pattern, check contained binding elements
63769             if (ts.isBindingPattern(node.name)) {
63770                 if (node.name.kind === 190 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
63771                     checkExternalEmitHelpers(node, 512 /* Read */);
63772                 }
63773                 ts.forEach(node.name.elements, checkSourceElement);
63774             }
63775             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
63776             if (node.initializer && ts.getRootDeclaration(node).kind === 156 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
63777                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
63778                 return;
63779             }
63780             // For a binding pattern, validate the initializer and exit
63781             if (ts.isBindingPattern(node.name)) {
63782                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 231 /* ForInStatement */;
63783                 var needCheckWidenedType = node.name.elements.length === 0;
63784                 if (needCheckInitializer || needCheckWidenedType) {
63785                     // Don't validate for-in initializer as it is already an error
63786                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
63787                     if (needCheckInitializer) {
63788                         var initializerType = checkExpressionCached(node.initializer);
63789                         if (strictNullChecks && needCheckWidenedType) {
63790                             checkNonNullNonVoidType(initializerType, node);
63791                         }
63792                         else {
63793                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
63794                         }
63795                     }
63796                     // check the binding pattern with empty elements
63797                     if (needCheckWidenedType) {
63798                         if (ts.isArrayBindingPattern(node.name)) {
63799                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
63800                         }
63801                         else if (strictNullChecks) {
63802                             checkNonNullNonVoidType(widenedType, node);
63803                         }
63804                     }
63805                 }
63806                 return;
63807             }
63808             var symbol = getSymbolOfNode(node);
63809             var type = convertAutoToAny(getTypeOfSymbol(symbol));
63810             if (node === symbol.valueDeclaration) {
63811                 // Node is the primary declaration of the symbol, just validate the initializer
63812                 // Don't validate for-in initializer as it is already an error
63813                 var initializer = ts.getEffectiveInitializer(node);
63814                 if (initializer) {
63815                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
63816                         ts.isObjectLiteralExpression(initializer) &&
63817                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
63818                         ts.hasEntries(symbol.exports);
63819                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 231 /* ForInStatement */) {
63820                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
63821                     }
63822                 }
63823                 if (symbol.declarations.length > 1) {
63824                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
63825                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63826                     }
63827                 }
63828             }
63829             else {
63830                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
63831                 // initializer is consistent with type associated with the node
63832                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
63833                 if (type !== errorType && declarationType !== errorType &&
63834                     !isTypeIdenticalTo(type, declarationType) &&
63835                     !(symbol.flags & 67108864 /* Assignment */)) {
63836                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
63837                 }
63838                 if (node.initializer) {
63839                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
63840                 }
63841                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
63842                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
63843                 }
63844             }
63845             if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */) {
63846                 // We know we don't have a binding pattern or computed name here
63847                 checkExportsOnMergedDeclarations(node);
63848                 if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
63849                     checkVarDeclaredNamesNotShadowed(node);
63850                 }
63851                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
63852                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
63853                 if (!compilerOptions.noEmit && languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
63854                     potentialWeakMapCollisions.push(node);
63855                 }
63856             }
63857         }
63858         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
63859             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
63860             var message = nextDeclaration.kind === 159 /* PropertyDeclaration */ || nextDeclaration.kind === 158 /* PropertySignature */
63861                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
63862                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
63863             var declName = ts.declarationNameToString(nextDeclarationName);
63864             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
63865             if (firstDeclaration) {
63866                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
63867             }
63868         }
63869         function areDeclarationFlagsIdentical(left, right) {
63870             if ((left.kind === 156 /* Parameter */ && right.kind === 242 /* VariableDeclaration */) ||
63871                 (left.kind === 242 /* VariableDeclaration */ && right.kind === 156 /* Parameter */)) {
63872                 // Differences in optionality between parameters and variables are allowed.
63873                 return true;
63874             }
63875             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
63876                 return false;
63877             }
63878             var interestingFlags = 8 /* Private */ |
63879                 16 /* Protected */ |
63880                 256 /* Async */ |
63881                 128 /* Abstract */ |
63882                 64 /* Readonly */ |
63883                 32 /* Static */;
63884             return ts.getSelectedModifierFlags(left, interestingFlags) === ts.getSelectedModifierFlags(right, interestingFlags);
63885         }
63886         function checkVariableDeclaration(node) {
63887             checkGrammarVariableDeclaration(node);
63888             return checkVariableLikeDeclaration(node);
63889         }
63890         function checkBindingElement(node) {
63891             checkGrammarBindingElement(node);
63892             return checkVariableLikeDeclaration(node);
63893         }
63894         function checkVariableStatement(node) {
63895             // Grammar checking
63896             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
63897                 checkGrammarForDisallowedLetOrConstStatement(node);
63898             ts.forEach(node.declarationList.declarations, checkSourceElement);
63899         }
63900         function checkExpressionStatement(node) {
63901             // Grammar checking
63902             checkGrammarStatementInAmbientContext(node);
63903             checkExpression(node.expression);
63904         }
63905         function checkIfStatement(node) {
63906             // Grammar checking
63907             checkGrammarStatementInAmbientContext(node);
63908             var type = checkTruthinessExpression(node.expression);
63909             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
63910             checkSourceElement(node.thenStatement);
63911             if (node.thenStatement.kind === 224 /* EmptyStatement */) {
63912                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
63913             }
63914             checkSourceElement(node.elseStatement);
63915         }
63916         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
63917             if (!strictNullChecks) {
63918                 return;
63919             }
63920             var testedNode = ts.isIdentifier(condExpr)
63921                 ? condExpr
63922                 : ts.isPropertyAccessExpression(condExpr)
63923                     ? condExpr.name
63924                     : undefined;
63925             if (!testedNode) {
63926                 return;
63927             }
63928             var possiblyFalsy = getFalsyFlags(type);
63929             if (possiblyFalsy) {
63930                 return;
63931             }
63932             // While it technically should be invalid for any known-truthy value
63933             // to be tested, we de-scope to functions unrefenced in the block as a
63934             // heuristic to identify the most common bugs. There are too many
63935             // false positives for values sourced from type definitions without
63936             // strictNullChecks otherwise.
63937             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
63938             if (callSignatures.length === 0) {
63939                 return;
63940             }
63941             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
63942             if (!testedFunctionSymbol) {
63943                 return;
63944             }
63945             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
63946                 if (ts.isIdentifier(childNode)) {
63947                     var childSymbol = getSymbolAtLocation(childNode);
63948                     if (childSymbol && childSymbol === testedFunctionSymbol) {
63949                         // If the test was a simple identifier, the above check is sufficient
63950                         if (ts.isIdentifier(condExpr)) {
63951                             return true;
63952                         }
63953                         // Otherwise we need to ensure the symbol is called on the same target
63954                         var testedExpression = testedNode.parent;
63955                         var childExpression = childNode.parent;
63956                         while (testedExpression && childExpression) {
63957                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
63958                                 testedExpression.kind === 104 /* ThisKeyword */ && childExpression.kind === 104 /* ThisKeyword */) {
63959                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
63960                             }
63961                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
63962                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
63963                                     return false;
63964                                 }
63965                                 childExpression = childExpression.expression;
63966                                 testedExpression = testedExpression.expression;
63967                             }
63968                             else {
63969                                 return false;
63970                             }
63971                         }
63972                     }
63973                 }
63974                 return ts.forEachChild(childNode, check);
63975             });
63976             if (!functionIsUsedInBody) {
63977                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
63978             }
63979         }
63980         function checkDoStatement(node) {
63981             // Grammar checking
63982             checkGrammarStatementInAmbientContext(node);
63983             checkSourceElement(node.statement);
63984             checkTruthinessExpression(node.expression);
63985         }
63986         function checkWhileStatement(node) {
63987             // Grammar checking
63988             checkGrammarStatementInAmbientContext(node);
63989             checkTruthinessExpression(node.expression);
63990             checkSourceElement(node.statement);
63991         }
63992         function checkTruthinessOfType(type, node) {
63993             if (type.flags & 16384 /* Void */) {
63994                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
63995             }
63996             return type;
63997         }
63998         function checkTruthinessExpression(node, checkMode) {
63999             return checkTruthinessOfType(checkExpression(node, checkMode), node);
64000         }
64001         function checkForStatement(node) {
64002             // Grammar checking
64003             if (!checkGrammarStatementInAmbientContext(node)) {
64004                 if (node.initializer && node.initializer.kind === 243 /* VariableDeclarationList */) {
64005                     checkGrammarVariableDeclarationList(node.initializer);
64006                 }
64007             }
64008             if (node.initializer) {
64009                 if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64010                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
64011                 }
64012                 else {
64013                     checkExpression(node.initializer);
64014                 }
64015             }
64016             if (node.condition)
64017                 checkTruthinessExpression(node.condition);
64018             if (node.incrementor)
64019                 checkExpression(node.incrementor);
64020             checkSourceElement(node.statement);
64021             if (node.locals) {
64022                 registerForUnusedIdentifiersCheck(node);
64023             }
64024         }
64025         function checkForOfStatement(node) {
64026             checkGrammarForInOrForOfStatement(node);
64027             if (node.awaitModifier) {
64028                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
64029                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
64030                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
64031                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
64032                 }
64033             }
64034             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
64035                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
64036                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
64037             }
64038             // Check the LHS and RHS
64039             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
64040             // via checkRightHandSideOfForOf.
64041             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
64042             // Then check that the RHS is assignable to it.
64043             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64044                 checkForInOrForOfVariableDeclaration(node);
64045             }
64046             else {
64047                 var varExpr = node.initializer;
64048                 var iteratedType = checkRightHandSideOfForOf(node);
64049                 // There may be a destructuring assignment on the left side
64050                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64051                     // iteratedType may be undefined. In this case, we still want to check the structure of
64052                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
64053                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
64054                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
64055                 }
64056                 else {
64057                     var leftType = checkExpression(varExpr);
64058                     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);
64059                     // iteratedType will be undefined if the rightType was missing properties/signatures
64060                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
64061                     // because we accessed properties from anyType, or it may have led to an error inside
64062                     // getElementTypeOfIterable.
64063                     if (iteratedType) {
64064                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
64065                     }
64066                 }
64067             }
64068             checkSourceElement(node.statement);
64069             if (node.locals) {
64070                 registerForUnusedIdentifiersCheck(node);
64071             }
64072         }
64073         function checkForInStatement(node) {
64074             // Grammar checking
64075             checkGrammarForInOrForOfStatement(node);
64076             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
64077             // TypeScript 1.0 spec (April 2014): 5.4
64078             // In a 'for-in' statement of the form
64079             // for (let VarDecl in Expr) Statement
64080             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
64081             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64082             if (node.initializer.kind === 243 /* VariableDeclarationList */) {
64083                 var variable = node.initializer.declarations[0];
64084                 if (variable && ts.isBindingPattern(variable.name)) {
64085                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64086                 }
64087                 checkForInOrForOfVariableDeclaration(node);
64088             }
64089             else {
64090                 // In a 'for-in' statement of the form
64091                 // for (Var in Expr) Statement
64092                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
64093                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
64094                 var varExpr = node.initializer;
64095                 var leftType = checkExpression(varExpr);
64096                 if (varExpr.kind === 192 /* ArrayLiteralExpression */ || varExpr.kind === 193 /* ObjectLiteralExpression */) {
64097                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
64098                 }
64099                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
64100                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
64101                 }
64102                 else {
64103                     // run check only former check succeeded to avoid cascading errors
64104                     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);
64105                 }
64106             }
64107             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
64108             // in this case error about missing name is already reported - do not report extra one
64109             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
64110                 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));
64111             }
64112             checkSourceElement(node.statement);
64113             if (node.locals) {
64114                 registerForUnusedIdentifiersCheck(node);
64115             }
64116         }
64117         function checkForInOrForOfVariableDeclaration(iterationStatement) {
64118             var variableDeclarationList = iterationStatement.initializer;
64119             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
64120             if (variableDeclarationList.declarations.length >= 1) {
64121                 var decl = variableDeclarationList.declarations[0];
64122                 checkVariableDeclaration(decl);
64123             }
64124         }
64125         function checkRightHandSideOfForOf(statement) {
64126             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
64127             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
64128         }
64129         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
64130             if (isTypeAny(inputType)) {
64131                 return inputType;
64132             }
64133             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
64134         }
64135         /**
64136          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
64137          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
64138          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
64139          */
64140         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
64141             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
64142             if (inputType === neverType) {
64143                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
64144                 return undefined;
64145             }
64146             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
64147             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
64148             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
64149             // or higher, when inside of an async generator or for-await-if, or when
64150             // downlevelIteration is requested.
64151             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
64152                 // We only report errors for an invalid iterable type in ES2015 or higher.
64153                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
64154                 if (checkAssignability) {
64155                     if (iterationTypes) {
64156                         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 :
64157                             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 :
64158                                 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 :
64159                                     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 :
64160                                         undefined;
64161                         if (diagnostic) {
64162                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
64163                         }
64164                     }
64165                 }
64166                 if (iterationTypes || uplevelIteration) {
64167                     return iterationTypes && iterationTypes.yieldType;
64168                 }
64169             }
64170             var arrayType = inputType;
64171             var reportedError = false;
64172             var hasStringConstituent = false;
64173             // If strings are permitted, remove any string-like constituents from the array type.
64174             // This allows us to find other non-string element types from an array unioned with
64175             // a string.
64176             if (use & 4 /* AllowsStringInputFlag */) {
64177                 if (arrayType.flags & 1048576 /* Union */) {
64178                     // After we remove all types that are StringLike, we will know if there was a string constituent
64179                     // based on whether the result of filter is a new array.
64180                     var arrayTypes = inputType.types;
64181                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 132 /* StringLike */); });
64182                     if (filteredTypes !== arrayTypes) {
64183                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
64184                     }
64185                 }
64186                 else if (arrayType.flags & 132 /* StringLike */) {
64187                     arrayType = neverType;
64188                 }
64189                 hasStringConstituent = arrayType !== inputType;
64190                 if (hasStringConstituent) {
64191                     if (languageVersion < 1 /* ES5 */) {
64192                         if (errorNode) {
64193                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
64194                             reportedError = true;
64195                         }
64196                     }
64197                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
64198                     // arrayOrStringType was a string.
64199                     if (arrayType.flags & 131072 /* Never */) {
64200                         return stringType;
64201                     }
64202                 }
64203             }
64204             if (!isArrayLikeType(arrayType)) {
64205                 if (errorNode && !reportedError) {
64206                     // Which error we report depends on whether we allow strings or if there was a
64207                     // string constituent. For example, if the input type is number | string, we
64208                     // want to say that number is not an array type. But if the input was just
64209                     // number and string input is allowed, we want to say that number is not an
64210                     // array type or a string type.
64211                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
64212                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
64213                         ? downlevelIteration
64214                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
64215                             : yieldType
64216                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64217                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
64218                         : downlevelIteration
64219                             ? [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]
64220                             : yieldType
64221                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
64222                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
64223                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
64224                 }
64225                 return hasStringConstituent ? stringType : undefined;
64226             }
64227             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
64228             if (hasStringConstituent && arrayElementType) {
64229                 // This is just an optimization for the case where arrayOrStringType is string | string[]
64230                 if (arrayElementType.flags & 132 /* StringLike */) {
64231                     return stringType;
64232                 }
64233                 return getUnionType([arrayElementType, stringType], 2 /* Subtype */);
64234             }
64235             return arrayElementType;
64236         }
64237         /**
64238          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
64239          */
64240         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
64241             if (isTypeAny(inputType)) {
64242                 return undefined;
64243             }
64244             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
64245             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
64246         }
64247         function createIterationTypes(yieldType, returnType, nextType) {
64248             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
64249             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
64250             // as it is combined via `getIntersectionType` when merging iteration types.
64251             if (yieldType === void 0) { yieldType = neverType; }
64252             if (returnType === void 0) { returnType = neverType; }
64253             if (nextType === void 0) { nextType = unknownType; }
64254             // Use the cache only for intrinsic types to keep it small as they are likely to be
64255             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
64256             // are also cached on the type they are requested for, so we shouldn't need to maintain
64257             // the cache for less-frequently used types.
64258             if (yieldType.flags & 67359327 /* Intrinsic */ &&
64259                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
64260                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
64261                 var id = getTypeListId([yieldType, returnType, nextType]);
64262                 var iterationTypes = iterationTypesCache.get(id);
64263                 if (!iterationTypes) {
64264                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
64265                     iterationTypesCache.set(id, iterationTypes);
64266                 }
64267                 return iterationTypes;
64268             }
64269             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
64270         }
64271         /**
64272          * Combines multiple `IterationTypes` records.
64273          *
64274          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
64275          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
64276          * for the combined iteration types.
64277          */
64278         function combineIterationTypes(array) {
64279             var yieldTypes;
64280             var returnTypes;
64281             var nextTypes;
64282             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
64283                 var iterationTypes = array_10[_i];
64284                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
64285                     continue;
64286                 }
64287                 if (iterationTypes === anyIterationTypes) {
64288                     return anyIterationTypes;
64289                 }
64290                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
64291                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64292                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
64293             }
64294             if (yieldTypes || returnTypes || nextTypes) {
64295                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
64296             }
64297             return noIterationTypes;
64298         }
64299         function getCachedIterationTypes(type, cacheKey) {
64300             return type[cacheKey];
64301         }
64302         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
64303             return type[cacheKey] = cachedTypes;
64304         }
64305         /**
64306          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
64307          *
64308          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
64309          *
64310          * Another thing to note is that at any step of this process, we could run into a dead end,
64311          * meaning either the property is missing, or we run into the anyType. If either of these things
64312          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
64313          * is missing, and the previous step did not result in `any`, then we also give an error if the
64314          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
64315          * type.
64316          *
64317          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
64318          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
64319          * method.
64320          *
64321          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
64322          *
64323          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
64324          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
64325          */
64326         function getIterationTypesOfIterable(type, use, errorNode) {
64327             if (isTypeAny(type)) {
64328                 return anyIterationTypes;
64329             }
64330             if (!(type.flags & 1048576 /* Union */)) {
64331                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
64332                 if (iterationTypes_1 === noIterationTypes) {
64333                     if (errorNode) {
64334                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64335                     }
64336                     return undefined;
64337                 }
64338                 return iterationTypes_1;
64339             }
64340             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
64341             var cachedTypes = getCachedIterationTypes(type, cacheKey);
64342             if (cachedTypes)
64343                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
64344             var allIterationTypes;
64345             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
64346                 var constituent = _a[_i];
64347                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
64348                 if (iterationTypes_2 === noIterationTypes) {
64349                     if (errorNode) {
64350                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
64351                         errorNode = undefined;
64352                     }
64353                 }
64354                 else {
64355                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
64356                 }
64357             }
64358             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
64359             setCachedIterationTypes(type, cacheKey, iterationTypes);
64360             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64361         }
64362         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
64363             if (iterationTypes === noIterationTypes)
64364                 return noIterationTypes;
64365             if (iterationTypes === anyIterationTypes)
64366                 return anyIterationTypes;
64367             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
64368             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
64369         }
64370         /**
64371          * Gets the *yield*, *return*, and *next* types from a non-union type.
64372          *
64373          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
64374          * returned to indicate to the caller that it should report an error. Otherwise, an
64375          * `IterationTypes` record is returned.
64376          *
64377          * NOTE: You probably don't want to call this directly and should be calling
64378          * `getIterationTypesOfIterable` instead.
64379          */
64380         function getIterationTypesOfIterableWorker(type, use, errorNode) {
64381             if (isTypeAny(type)) {
64382                 return anyIterationTypes;
64383             }
64384             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64385                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
64386                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
64387                 if (iterationTypes) {
64388                     return iterationTypes;
64389                 }
64390             }
64391             if (use & 1 /* AllowsSyncIterablesFlag */) {
64392                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
64393                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
64394                 if (iterationTypes) {
64395                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64396                         // for a sync iterable in an async context, only use the cached types if they are valid.
64397                         if (iterationTypes !== noIterationTypes) {
64398                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
64399                         }
64400                     }
64401                     else {
64402                         return iterationTypes;
64403                     }
64404                 }
64405             }
64406             if (use & 2 /* AllowsAsyncIterablesFlag */) {
64407                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
64408                 if (iterationTypes !== noIterationTypes) {
64409                     return iterationTypes;
64410                 }
64411             }
64412             if (use & 1 /* AllowsSyncIterablesFlag */) {
64413                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
64414                 if (iterationTypes !== noIterationTypes) {
64415                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
64416                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
64417                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
64418                             : noIterationTypes);
64419                     }
64420                     else {
64421                         return iterationTypes;
64422                     }
64423                 }
64424             }
64425             return noIterationTypes;
64426         }
64427         /**
64428          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
64429          * `AsyncIterable`-like type from the cache.
64430          *
64431          * NOTE: You probably don't want to call this directly and should be calling
64432          * `getIterationTypesOfIterable` instead.
64433          */
64434         function getIterationTypesOfIterableCached(type, resolver) {
64435             return getCachedIterationTypes(type, resolver.iterableCacheKey);
64436         }
64437         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
64438             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
64439                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
64440             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
64441         }
64442         /**
64443          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64444          * type from from common heuristics.
64445          *
64446          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64447          * returned. If we found iteration types, an `IterationTypes` record is returned.
64448          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64449          * exhaustive analysis.
64450          *
64451          * NOTE: You probably don't want to call this directly and should be calling
64452          * `getIterationTypesOfIterable` instead.
64453          */
64454         function getIterationTypesOfIterableFast(type, resolver) {
64455             // As an optimization, if the type is an instantiation of one of the following global types, then
64456             // just grab its related type argument:
64457             // - `Iterable<T>` or `AsyncIterable<T>`
64458             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64459             var globalType;
64460             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
64461                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
64462                 var yieldType = getTypeArguments(type)[0];
64463                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
64464                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
64465                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
64466                 // different definitions.
64467                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
64468                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64469             }
64470             // As an optimization, if the type is an instantiation of the following global type, then
64471             // just grab its related type arguments:
64472             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64473             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64474                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64475                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
64476             }
64477         }
64478         /**
64479          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
64480          * type from its members.
64481          *
64482          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64483          * record is returned. Otherwise, `noIterationTypes` is returned.
64484          *
64485          * NOTE: You probably don't want to call this directly and should be calling
64486          * `getIterationTypesOfIterable` instead.
64487          */
64488         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
64489             var _a;
64490             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
64491             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
64492             if (isTypeAny(methodType)) {
64493                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
64494             }
64495             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
64496             if (!ts.some(signatures)) {
64497                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
64498             }
64499             var iteratorType = getUnionType(ts.map(signatures, getReturnTypeOfSignature), 2 /* Subtype */);
64500             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
64501             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
64502         }
64503         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
64504             var message = allowAsyncIterables
64505                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
64506                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
64507             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
64508         }
64509         /**
64510          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
64511          *
64512          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64513          * record is returned. Otherwise, `undefined` is returned.
64514          */
64515         function getIterationTypesOfIterator(type, resolver, errorNode) {
64516             if (isTypeAny(type)) {
64517                 return anyIterationTypes;
64518             }
64519             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
64520                 getIterationTypesOfIteratorFast(type, resolver) ||
64521                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
64522             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
64523         }
64524         /**
64525          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64526          * cache.
64527          *
64528          * NOTE: You probably don't want to call this directly and should be calling
64529          * `getIterationTypesOfIterator` instead.
64530          */
64531         function getIterationTypesOfIteratorCached(type, resolver) {
64532             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
64533         }
64534         /**
64535          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
64536          * cache or from common heuristics.
64537          *
64538          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
64539          * returned. If we found iteration types, an `IterationTypes` record is returned.
64540          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
64541          * exhaustive analysis.
64542          *
64543          * NOTE: You probably don't want to call this directly and should be calling
64544          * `getIterationTypesOfIterator` instead.
64545          */
64546         function getIterationTypesOfIteratorFast(type, resolver) {
64547             // As an optimization, if the type is an instantiation of one of the following global types,
64548             // then just grab its related type argument:
64549             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
64550             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
64551             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
64552             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
64553             if (isReferenceToType(type, globalType)) {
64554                 var yieldType = getTypeArguments(type)[0];
64555                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
64556                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
64557                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
64558                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
64559                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
64560                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
64561                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64562             }
64563             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
64564                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
64565                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
64566                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
64567             }
64568         }
64569         function isIteratorResult(type, kind) {
64570             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
64571             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
64572             // > If the end was not reached `done` is `false` and a value is available.
64573             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
64574             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
64575             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
64576         }
64577         function isYieldIteratorResult(type) {
64578             return isIteratorResult(type, 0 /* Yield */);
64579         }
64580         function isReturnIteratorResult(type) {
64581             return isIteratorResult(type, 1 /* Return */);
64582         }
64583         /**
64584          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
64585          *
64586          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
64587          * returned to indicate to the caller that it should handle the error. Otherwise, an
64588          * `IterationTypes` record is returned.
64589          */
64590         function getIterationTypesOfIteratorResult(type) {
64591             if (isTypeAny(type)) {
64592                 return anyIterationTypes;
64593             }
64594             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
64595             if (cachedTypes) {
64596                 return cachedTypes;
64597             }
64598             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
64599             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
64600             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
64601                 var yieldType_1 = getTypeArguments(type)[0];
64602                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
64603             }
64604             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
64605                 var returnType_1 = getTypeArguments(type)[0];
64606                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
64607             }
64608             // Choose any constituents that can produce the requested iteration type.
64609             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
64610             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
64611             var returnIteratorResult = filterType(type, isReturnIteratorResult);
64612             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
64613             if (!yieldType && !returnType) {
64614                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
64615             }
64616             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
64617             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
64618             // > `value` property may be absent from the conforming object if it does not inherit an explicit
64619             // > `value` property.
64620             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
64621         }
64622         /**
64623          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
64624          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
64625          *
64626          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64627          * record is returned. Otherwise, we return `undefined`.
64628          */
64629         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
64630             var method = getPropertyOfType(type, methodName);
64631             // Ignore 'return' or 'throw' if they are missing.
64632             if (!method && methodName !== "next") {
64633                 return undefined;
64634             }
64635             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
64636                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
64637                 : undefined;
64638             if (isTypeAny(methodType)) {
64639                 // `return()` and `throw()` don't provide a *next* type.
64640                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
64641             }
64642             // Both async and non-async iterators *must* have a `next` method.
64643             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
64644             if (methodSignatures.length === 0) {
64645                 if (errorNode) {
64646                     var diagnostic = methodName === "next"
64647                         ? resolver.mustHaveANextMethodDiagnostic
64648                         : resolver.mustBeAMethodDiagnostic;
64649                     error(errorNode, diagnostic, methodName);
64650                 }
64651                 return methodName === "next" ? anyIterationTypes : undefined;
64652             }
64653             // Extract the first parameter and return type of each signature.
64654             var methodParameterTypes;
64655             var methodReturnTypes;
64656             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
64657                 var signature = methodSignatures_1[_i];
64658                 if (methodName !== "throw" && ts.some(signature.parameters)) {
64659                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
64660                 }
64661                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
64662             }
64663             // Resolve the *next* or *return* type from the first parameter of a `next()` or
64664             // `return()` method, respectively.
64665             var returnTypes;
64666             var nextType;
64667             if (methodName !== "throw") {
64668                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
64669                 if (methodName === "next") {
64670                     // The value of `next(value)` is *not* awaited by async generators
64671                     nextType = methodParameterType;
64672                 }
64673                 else if (methodName === "return") {
64674                     // The value of `return(value)` *is* awaited by async generators
64675                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
64676                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
64677                 }
64678             }
64679             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
64680             var yieldType;
64681             var methodReturnType = methodReturnTypes ? getUnionType(methodReturnTypes, 2 /* Subtype */) : neverType;
64682             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
64683             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
64684             if (iterationTypes === noIterationTypes) {
64685                 if (errorNode) {
64686                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
64687                 }
64688                 yieldType = anyType;
64689                 returnTypes = ts.append(returnTypes, anyType);
64690             }
64691             else {
64692                 yieldType = iterationTypes.yieldType;
64693                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
64694             }
64695             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
64696         }
64697         /**
64698          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
64699          * type from its members.
64700          *
64701          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
64702          * record is returned. Otherwise, `noIterationTypes` is returned.
64703          *
64704          * NOTE: You probably don't want to call this directly and should be calling
64705          * `getIterationTypesOfIterator` instead.
64706          */
64707         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
64708             var iterationTypes = combineIterationTypes([
64709                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
64710                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
64711                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
64712             ]);
64713             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
64714         }
64715         /**
64716          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
64717          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
64718          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
64719          */
64720         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
64721             if (isTypeAny(returnType)) {
64722                 return undefined;
64723             }
64724             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
64725             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
64726         }
64727         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
64728             if (isTypeAny(type)) {
64729                 return anyIterationTypes;
64730             }
64731             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64732             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
64733             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
64734                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
64735         }
64736         function checkBreakOrContinueStatement(node) {
64737             // Grammar checking
64738             if (!checkGrammarStatementInAmbientContext(node))
64739                 checkGrammarBreakOrContinueStatement(node);
64740             // TODO: Check that target label is valid
64741         }
64742         function unwrapReturnType(returnType, functionFlags) {
64743             var _a, _b;
64744             var isGenerator = !!(functionFlags & 1 /* Generator */);
64745             var isAsync = !!(functionFlags & 2 /* Async */);
64746             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
64747                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
64748                     returnType;
64749         }
64750         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
64751             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
64752             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
64753         }
64754         function checkReturnStatement(node) {
64755             var _a;
64756             // Grammar checking
64757             if (checkGrammarStatementInAmbientContext(node)) {
64758                 return;
64759             }
64760             var func = ts.getContainingFunction(node);
64761             if (!func) {
64762                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
64763                 return;
64764             }
64765             var signature = getSignatureFromDeclaration(func);
64766             var returnType = getReturnTypeOfSignature(signature);
64767             var functionFlags = ts.getFunctionFlags(func);
64768             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
64769                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
64770                 if (func.kind === 164 /* SetAccessor */) {
64771                     if (node.expression) {
64772                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
64773                     }
64774                 }
64775                 else if (func.kind === 162 /* Constructor */) {
64776                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
64777                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
64778                     }
64779                 }
64780                 else if (getReturnTypeFromAnnotation(func)) {
64781                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
64782                     var unwrappedExprType = functionFlags & 2 /* Async */
64783                         ? 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)
64784                         : exprType;
64785                     if (unwrappedReturnType) {
64786                         // If the function has a return type, but promisedType is
64787                         // undefined, an error will be reported in checkAsyncFunctionReturnType
64788                         // so we don't need to report one here.
64789                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
64790                     }
64791                 }
64792             }
64793             else if (func.kind !== 162 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
64794                 // The function has a return type, but the return statement doesn't have an expression.
64795                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
64796             }
64797         }
64798         function checkWithStatement(node) {
64799             // Grammar checking for withStatement
64800             if (!checkGrammarStatementInAmbientContext(node)) {
64801                 if (node.flags & 32768 /* AwaitContext */) {
64802                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
64803                 }
64804             }
64805             checkExpression(node.expression);
64806             var sourceFile = ts.getSourceFileOfNode(node);
64807             if (!hasParseDiagnostics(sourceFile)) {
64808                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
64809                 var end = node.statement.pos;
64810                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
64811             }
64812         }
64813         function checkSwitchStatement(node) {
64814             // Grammar checking
64815             checkGrammarStatementInAmbientContext(node);
64816             var firstDefaultClause;
64817             var hasDuplicateDefaultClause = false;
64818             var expressionType = checkExpression(node.expression);
64819             var expressionIsLiteral = isLiteralType(expressionType);
64820             ts.forEach(node.caseBlock.clauses, function (clause) {
64821                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
64822                 if (clause.kind === 278 /* DefaultClause */ && !hasDuplicateDefaultClause) {
64823                     if (firstDefaultClause === undefined) {
64824                         firstDefaultClause = clause;
64825                     }
64826                     else {
64827                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
64828                         hasDuplicateDefaultClause = true;
64829                     }
64830                 }
64831                 if (produceDiagnostics && clause.kind === 277 /* CaseClause */) {
64832                     // TypeScript 1.0 spec (April 2014): 5.9
64833                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
64834                     // to or from the type of the 'switch' expression.
64835                     var caseType = checkExpression(clause.expression);
64836                     var caseIsLiteral = isLiteralType(caseType);
64837                     var comparedExpressionType = expressionType;
64838                     if (!caseIsLiteral || !expressionIsLiteral) {
64839                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
64840                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
64841                     }
64842                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
64843                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
64844                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
64845                     }
64846                 }
64847                 ts.forEach(clause.statements, checkSourceElement);
64848                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
64849                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
64850                 }
64851             });
64852             if (node.caseBlock.locals) {
64853                 registerForUnusedIdentifiersCheck(node.caseBlock);
64854             }
64855         }
64856         function checkLabeledStatement(node) {
64857             // Grammar checking
64858             if (!checkGrammarStatementInAmbientContext(node)) {
64859                 ts.findAncestor(node.parent, function (current) {
64860                     if (ts.isFunctionLike(current)) {
64861                         return "quit";
64862                     }
64863                     if (current.kind === 238 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
64864                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
64865                         return true;
64866                     }
64867                     return false;
64868                 });
64869             }
64870             // ensure that label is unique
64871             checkSourceElement(node.statement);
64872         }
64873         function checkThrowStatement(node) {
64874             // Grammar checking
64875             if (!checkGrammarStatementInAmbientContext(node)) {
64876                 if (node.expression === undefined) {
64877                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
64878                 }
64879             }
64880             if (node.expression) {
64881                 checkExpression(node.expression);
64882             }
64883         }
64884         function checkTryStatement(node) {
64885             // Grammar checking
64886             checkGrammarStatementInAmbientContext(node);
64887             checkBlock(node.tryBlock);
64888             var catchClause = node.catchClause;
64889             if (catchClause) {
64890                 // Grammar checking
64891                 if (catchClause.variableDeclaration) {
64892                     if (catchClause.variableDeclaration.type) {
64893                         grammarErrorOnFirstToken(catchClause.variableDeclaration.type, ts.Diagnostics.Catch_clause_variable_cannot_have_a_type_annotation);
64894                     }
64895                     else if (catchClause.variableDeclaration.initializer) {
64896                         grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
64897                     }
64898                     else {
64899                         var blockLocals_1 = catchClause.block.locals;
64900                         if (blockLocals_1) {
64901                             ts.forEachKey(catchClause.locals, function (caughtName) {
64902                                 var blockLocal = blockLocals_1.get(caughtName);
64903                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
64904                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
64905                                 }
64906                             });
64907                         }
64908                     }
64909                 }
64910                 checkBlock(catchClause.block);
64911             }
64912             if (node.finallyBlock) {
64913                 checkBlock(node.finallyBlock);
64914             }
64915         }
64916         function checkIndexConstraints(type) {
64917             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
64918             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
64919             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
64920             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
64921             if (stringIndexType || numberIndexType) {
64922                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
64923                     var propType = getTypeOfSymbol(prop);
64924                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64925                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64926                 });
64927                 var classDeclaration = type.symbol.valueDeclaration;
64928                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
64929                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
64930                         var member = _a[_i];
64931                         // Only process instance properties with computed names here.
64932                         // Static properties cannot be in conflict with indexers,
64933                         // and properties with literal names were already checked.
64934                         if (!ts.hasModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
64935                             var symbol = getSymbolOfNode(member);
64936                             var propType = getTypeOfSymbol(symbol);
64937                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
64938                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
64939                         }
64940                     }
64941                 }
64942             }
64943             var errorNode;
64944             if (stringIndexType && numberIndexType) {
64945                 errorNode = declaredNumberIndexer || declaredStringIndexer;
64946                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
64947                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
64948                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
64949                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
64950                 }
64951             }
64952             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
64953                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
64954             }
64955             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
64956                 // ESSymbol properties apply to neither string nor numeric indexers.
64957                 if (!indexType || ts.isKnownSymbol(prop)) {
64958                     return;
64959                 }
64960                 var propDeclaration = prop.valueDeclaration;
64961                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
64962                 if (name && ts.isPrivateIdentifier(name)) {
64963                     return;
64964                 }
64965                 // index is numeric and property name is not valid numeric literal
64966                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
64967                     return;
64968                 }
64969                 // perform property check if property or indexer is declared in 'type'
64970                 // this allows us to rule out cases when both property and indexer are inherited from the base class
64971                 var errorNode;
64972                 if (propDeclaration && name &&
64973                     (propDeclaration.kind === 209 /* BinaryExpression */ ||
64974                         name.kind === 154 /* ComputedPropertyName */ ||
64975                         prop.parent === containingType.symbol)) {
64976                     errorNode = propDeclaration;
64977                 }
64978                 else if (indexDeclaration) {
64979                     errorNode = indexDeclaration;
64980                 }
64981                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
64982                     // for interfaces property and indexer might be inherited from different bases
64983                     // check if any base class already has both property and indexer.
64984                     // check should be performed only if 'type' is the first type that brings property\indexer together
64985                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
64986                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
64987                 }
64988                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
64989                     var errorMessage = indexKind === 0 /* String */
64990                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
64991                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
64992                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
64993                 }
64994             }
64995         }
64996         function checkTypeNameIsReserved(name, message) {
64997             // TS 1.0 spec (April 2014): 3.6.1
64998             // The predefined type keywords are reserved and cannot be used as names of user defined types.
64999             switch (name.escapedText) {
65000                 case "any":
65001                 case "unknown":
65002                 case "number":
65003                 case "bigint":
65004                 case "boolean":
65005                 case "string":
65006                 case "symbol":
65007                 case "void":
65008                 case "object":
65009                     error(name, message, name.escapedText);
65010             }
65011         }
65012         /**
65013          * The name cannot be used as 'Object' of user defined types with special target.
65014          */
65015         function checkClassNameCollisionWithObject(name) {
65016             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
65017                 && moduleKind < ts.ModuleKind.ES2015) {
65018                 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
65019             }
65020         }
65021         /**
65022          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
65023          */
65024         function checkTypeParameters(typeParameterDeclarations) {
65025             if (typeParameterDeclarations) {
65026                 var seenDefault = false;
65027                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
65028                     var node = typeParameterDeclarations[i];
65029                     checkTypeParameter(node);
65030                     if (produceDiagnostics) {
65031                         if (node.default) {
65032                             seenDefault = true;
65033                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
65034                         }
65035                         else if (seenDefault) {
65036                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
65037                         }
65038                         for (var j = 0; j < i; j++) {
65039                             if (typeParameterDeclarations[j].symbol === node.symbol) {
65040                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
65041                             }
65042                         }
65043                     }
65044                 }
65045             }
65046         }
65047         /** Check that type parameter defaults only reference previously declared type parameters */
65048         function checkTypeParametersNotReferenced(root, typeParameters, index) {
65049             visit(root);
65050             function visit(node) {
65051                 if (node.kind === 169 /* TypeReference */) {
65052                     var type = getTypeFromTypeReference(node);
65053                     if (type.flags & 262144 /* TypeParameter */) {
65054                         for (var i = index; i < typeParameters.length; i++) {
65055                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
65056                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
65057                             }
65058                         }
65059                     }
65060                 }
65061                 ts.forEachChild(node, visit);
65062             }
65063         }
65064         /** Check that type parameter lists are identical across multiple declarations */
65065         function checkTypeParameterListsIdentical(symbol) {
65066             if (symbol.declarations.length === 1) {
65067                 return;
65068             }
65069             var links = getSymbolLinks(symbol);
65070             if (!links.typeParametersChecked) {
65071                 links.typeParametersChecked = true;
65072                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
65073                 if (declarations.length <= 1) {
65074                     return;
65075                 }
65076                 var type = getDeclaredTypeOfSymbol(symbol);
65077                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
65078                     // Report an error on every conflicting declaration.
65079                     var name = symbolToString(symbol);
65080                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
65081                         var declaration = declarations_6[_i];
65082                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
65083                     }
65084                 }
65085             }
65086         }
65087         function areTypeParametersIdentical(declarations, targetParameters) {
65088             var maxTypeArgumentCount = ts.length(targetParameters);
65089             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
65090             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
65091                 var declaration = declarations_7[_i];
65092                 // If this declaration has too few or too many type parameters, we report an error
65093                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
65094                 var numTypeParameters = sourceParameters.length;
65095                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
65096                     return false;
65097                 }
65098                 for (var i = 0; i < numTypeParameters; i++) {
65099                     var source = sourceParameters[i];
65100                     var target = targetParameters[i];
65101                     // If the type parameter node does not have the same as the resolved type
65102                     // parameter at this position, we report an error.
65103                     if (source.name.escapedText !== target.symbol.escapedName) {
65104                         return false;
65105                     }
65106                     // If the type parameter node does not have an identical constraint as the resolved
65107                     // type parameter at this position, we report an error.
65108                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
65109                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
65110                     var targetConstraint = getConstraintOfTypeParameter(target);
65111                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
65112                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
65113                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
65114                         return false;
65115                     }
65116                     // If the type parameter node has a default and it is not identical to the default
65117                     // for the type parameter at this position, we report an error.
65118                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
65119                     var targetDefault = getDefaultFromTypeParameter(target);
65120                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
65121                         return false;
65122                     }
65123                 }
65124             }
65125             return true;
65126         }
65127         function checkClassExpression(node) {
65128             checkClassLikeDeclaration(node);
65129             checkNodeDeferred(node);
65130             return getTypeOfSymbol(getSymbolOfNode(node));
65131         }
65132         function checkClassExpressionDeferred(node) {
65133             ts.forEach(node.members, checkSourceElement);
65134             registerForUnusedIdentifiersCheck(node);
65135         }
65136         function checkClassDeclaration(node) {
65137             if (!node.name && !ts.hasModifier(node, 512 /* Default */)) {
65138                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
65139             }
65140             checkClassLikeDeclaration(node);
65141             ts.forEach(node.members, checkSourceElement);
65142             registerForUnusedIdentifiersCheck(node);
65143         }
65144         function checkClassLikeDeclaration(node) {
65145             checkGrammarClassLikeDeclaration(node);
65146             checkDecorators(node);
65147             if (node.name) {
65148                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
65149                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65150                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65151                 if (!(node.flags & 8388608 /* Ambient */)) {
65152                     checkClassNameCollisionWithObject(node.name);
65153                 }
65154             }
65155             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
65156             checkExportsOnMergedDeclarations(node);
65157             var symbol = getSymbolOfNode(node);
65158             var type = getDeclaredTypeOfSymbol(symbol);
65159             var typeWithThis = getTypeWithThisArgument(type);
65160             var staticType = getTypeOfSymbol(symbol);
65161             checkTypeParameterListsIdentical(symbol);
65162             checkClassForDuplicateDeclarations(node);
65163             // Only check for reserved static identifiers on non-ambient context.
65164             if (!(node.flags & 8388608 /* Ambient */)) {
65165                 checkClassForStaticPropertyNameConflicts(node);
65166             }
65167             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
65168             if (baseTypeNode) {
65169                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65170                 if (languageVersion < 2 /* ES2015 */) {
65171                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
65172                 }
65173                 // check both @extends and extends if both are specified.
65174                 var extendsNode = ts.getClassExtendsHeritageElement(node);
65175                 if (extendsNode && extendsNode !== baseTypeNode) {
65176                     checkExpression(extendsNode.expression);
65177                 }
65178                 var baseTypes = getBaseTypes(type);
65179                 if (baseTypes.length && produceDiagnostics) {
65180                     var baseType_1 = baseTypes[0];
65181                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
65182                     var staticBaseType = getApparentType(baseConstructorType);
65183                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
65184                     checkSourceElement(baseTypeNode.expression);
65185                     if (ts.some(baseTypeNode.typeArguments)) {
65186                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
65187                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
65188                             var constructor = _a[_i];
65189                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
65190                                 break;
65191                             }
65192                         }
65193                     }
65194                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
65195                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65196                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
65197                     }
65198                     else {
65199                         // Report static side error only when instance type is assignable
65200                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
65201                     }
65202                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
65203                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
65204                     }
65205                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
65206                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
65207                         // that all instantiated base constructor signatures return the same type.
65208                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
65209                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
65210                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
65211                         }
65212                     }
65213                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
65214                 }
65215             }
65216             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
65217             if (implementedTypeNodes) {
65218                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
65219                     var typeRefNode = implementedTypeNodes_1[_b];
65220                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
65221                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
65222                     }
65223                     checkTypeReferenceNode(typeRefNode);
65224                     if (produceDiagnostics) {
65225                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
65226                         if (t !== errorType) {
65227                             if (isValidBaseType(t)) {
65228                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
65229                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
65230                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
65231                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
65232                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
65233                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
65234                                 }
65235                             }
65236                             else {
65237                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
65238                             }
65239                         }
65240                     }
65241                 }
65242             }
65243             if (produceDiagnostics) {
65244                 checkIndexConstraints(type);
65245                 checkTypeForDuplicateIndexSignatures(node);
65246                 checkPropertyInitialization(node);
65247             }
65248         }
65249         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
65250             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
65251             var issuedMemberError = false;
65252             var _loop_19 = function (member) {
65253                 if (ts.hasStaticModifier(member)) {
65254                     return "continue";
65255                 }
65256                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
65257                 if (declaredProp) {
65258                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
65259                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
65260                     if (prop && baseProp) {
65261                         var rootChain = function () { return ts.chainDiagnosticMessages(
65262                         /*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)); };
65263                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
65264                             issuedMemberError = true;
65265                         }
65266                     }
65267                 }
65268             };
65269             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65270                 var member = _a[_i];
65271                 _loop_19(member);
65272             }
65273             if (!issuedMemberError) {
65274                 // check again with diagnostics to generate a less-specific error
65275                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
65276             }
65277         }
65278         function checkBaseTypeAccessibility(type, node) {
65279             var signatures = getSignaturesOfType(type, 1 /* Construct */);
65280             if (signatures.length) {
65281                 var declaration = signatures[0].declaration;
65282                 if (declaration && ts.hasModifier(declaration, 8 /* Private */)) {
65283                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65284                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
65285                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
65286                     }
65287                 }
65288             }
65289         }
65290         function getTargetSymbol(s) {
65291             // if symbol is instantiated its flags are not copied from the 'target'
65292             // so we'll need to get back original 'target' symbol to work with correct set of flags
65293             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
65294         }
65295         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
65296             return ts.filter(symbol.declarations, function (d) {
65297                 return d.kind === 245 /* ClassDeclaration */ || d.kind === 246 /* InterfaceDeclaration */;
65298             });
65299         }
65300         function checkKindsOfPropertyMemberOverrides(type, baseType) {
65301             // TypeScript 1.0 spec (April 2014): 8.2.3
65302             // A derived class inherits all members from its base class it doesn't override.
65303             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
65304             // Both public and private property members are inherited, but only public property members can be overridden.
65305             // A property member in a derived class is said to override a property member in a base class
65306             // when the derived class property member has the same name and kind(instance or static)
65307             // as the base class property member.
65308             // The type of an overriding property member must be assignable(section 3.8.4)
65309             // to the type of the overridden property member, or otherwise a compile - time error occurs.
65310             // Base class instance member functions can be overridden by derived class instance member functions,
65311             // but not by other kinds of members.
65312             // Base class instance member variables and accessors can be overridden by
65313             // derived class instance member variables and accessors, but not by other kinds of members.
65314             // NOTE: assignability is checked in checkClassDeclaration
65315             var baseProperties = getPropertiesOfType(baseType);
65316             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
65317                 var baseProperty = baseProperties_1[_i];
65318                 var base = getTargetSymbol(baseProperty);
65319                 if (base.flags & 4194304 /* Prototype */) {
65320                     continue;
65321                 }
65322                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
65323                 if (!baseSymbol) {
65324                     continue;
65325                 }
65326                 var derived = getTargetSymbol(baseSymbol);
65327                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
65328                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
65329                 // In order to resolve whether the inherited method was overridden in the base class or not,
65330                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
65331                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
65332                 if (derived === base) {
65333                     // derived class inherits base without override/redeclaration
65334                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
65335                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
65336                     // If there is no declaration for the derived class (as in the case of class expressions),
65337                     // then the class cannot be declared abstract.
65338                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasModifier(derivedClassDecl, 128 /* Abstract */))) {
65339                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
65340                         // (The class may have more than one base type via declaration merging with an interface with the
65341                         // same name.)
65342                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
65343                             var otherBaseType = _b[_a];
65344                             if (otherBaseType === baseType)
65345                                 continue;
65346                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
65347                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
65348                             if (derivedElsewhere && derivedElsewhere !== base) {
65349                                 continue basePropertyCheck;
65350                             }
65351                         }
65352                         if (derivedClassDecl.kind === 214 /* ClassExpression */) {
65353                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
65354                         }
65355                         else {
65356                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
65357                         }
65358                     }
65359                 }
65360                 else {
65361                     // derived overrides base.
65362                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
65363                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
65364                         // either base or derived property is private - not override, skip it
65365                         continue;
65366                     }
65367                     var errorMessage = void 0;
65368                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
65369                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
65370                     if (basePropertyFlags && derivedPropertyFlags) {
65371                         // property/accessor is overridden with property/accessor
65372                         if (!compilerOptions.useDefineForClassFields
65373                             || baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
65374                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 246 /* InterfaceDeclaration */
65375                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
65376                             // when the base property is abstract or from an interface, base/derived flags don't need to match
65377                             // same when the derived property is from an assignment
65378                             continue;
65379                         }
65380                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
65381                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
65382                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
65383                             var errorMessage_1 = overriddenInstanceProperty ?
65384                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
65385                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
65386                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
65387                         }
65388                         else {
65389                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 159 /* PropertyDeclaration */ && !d.initializer; });
65390                             if (uninitialized
65391                                 && !(derived.flags & 33554432 /* Transient */)
65392                                 && !(baseDeclarationFlags & 128 /* Abstract */)
65393                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
65394                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
65395                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
65396                                 var propName = uninitialized.name;
65397                                 if (uninitialized.exclamationToken
65398                                     || !constructor
65399                                     || !ts.isIdentifier(propName)
65400                                     || !strictNullChecks
65401                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65402                                     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;
65403                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
65404                                 }
65405                             }
65406                         }
65407                         // correct case
65408                         continue;
65409                     }
65410                     else if (isPrototypeProperty(base)) {
65411                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
65412                             // method is overridden with method or property -- correct case
65413                             continue;
65414                         }
65415                         else {
65416                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
65417                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
65418                         }
65419                     }
65420                     else if (base.flags & 98304 /* Accessor */) {
65421                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
65422                     }
65423                     else {
65424                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
65425                     }
65426                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
65427                 }
65428             }
65429         }
65430         function getNonInterhitedProperties(type, baseTypes, properties) {
65431             if (!ts.length(baseTypes)) {
65432                 return properties;
65433             }
65434             var seen = ts.createUnderscoreEscapedMap();
65435             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
65436             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
65437                 var base = baseTypes_2[_i];
65438                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65439                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
65440                     var prop = properties_4[_a];
65441                     var existing = seen.get(prop.escapedName);
65442                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
65443                         seen.delete(prop.escapedName);
65444                     }
65445                 }
65446             }
65447             return ts.arrayFrom(seen.values());
65448         }
65449         function checkInheritedPropertiesAreIdentical(type, typeNode) {
65450             var baseTypes = getBaseTypes(type);
65451             if (baseTypes.length < 2) {
65452                 return true;
65453             }
65454             var seen = ts.createUnderscoreEscapedMap();
65455             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
65456             var ok = true;
65457             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
65458                 var base = baseTypes_3[_i];
65459                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
65460                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
65461                     var prop = properties_6[_a];
65462                     var existing = seen.get(prop.escapedName);
65463                     if (!existing) {
65464                         seen.set(prop.escapedName, { prop: prop, containingType: base });
65465                     }
65466                     else {
65467                         var isInheritedProperty = existing.containingType !== type;
65468                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
65469                             ok = false;
65470                             var typeName1 = typeToString(existing.containingType);
65471                             var typeName2 = typeToString(base);
65472                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
65473                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
65474                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
65475                         }
65476                     }
65477                 }
65478             }
65479             return ok;
65480         }
65481         function checkPropertyInitialization(node) {
65482             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
65483                 return;
65484             }
65485             var constructor = findConstructorDeclaration(node);
65486             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65487                 var member = _a[_i];
65488                 if (ts.getModifierFlags(member) & 2 /* Ambient */) {
65489                     continue;
65490                 }
65491                 if (isInstancePropertyWithoutInitializer(member)) {
65492                     var propName = member.name;
65493                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
65494                         var type = getTypeOfSymbol(getSymbolOfNode(member));
65495                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
65496                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
65497                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
65498                             }
65499                         }
65500                     }
65501                 }
65502             }
65503         }
65504         function isInstancePropertyWithoutInitializer(node) {
65505             return node.kind === 159 /* PropertyDeclaration */ &&
65506                 !ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
65507                 !node.exclamationToken &&
65508                 !node.initializer;
65509         }
65510         function isPropertyInitializedInConstructor(propName, propType, constructor) {
65511             var reference = ts.createPropertyAccess(ts.createThis(), propName);
65512             reference.expression.parent = reference;
65513             reference.parent = constructor;
65514             reference.flowNode = constructor.returnFlowNode;
65515             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
65516             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
65517         }
65518         function checkInterfaceDeclaration(node) {
65519             // Grammar checking
65520             if (!checkGrammarDecoratorsAndModifiers(node))
65521                 checkGrammarInterfaceDeclaration(node);
65522             checkTypeParameters(node.typeParameters);
65523             if (produceDiagnostics) {
65524                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
65525                 checkExportsOnMergedDeclarations(node);
65526                 var symbol = getSymbolOfNode(node);
65527                 checkTypeParameterListsIdentical(symbol);
65528                 // Only check this symbol once
65529                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 246 /* InterfaceDeclaration */);
65530                 if (node === firstInterfaceDecl) {
65531                     var type = getDeclaredTypeOfSymbol(symbol);
65532                     var typeWithThis = getTypeWithThisArgument(type);
65533                     // run subsequent checks only if first set succeeded
65534                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
65535                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
65536                             var baseType = _a[_i];
65537                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
65538                         }
65539                         checkIndexConstraints(type);
65540                     }
65541                 }
65542                 checkObjectTypeForDuplicateDeclarations(node);
65543             }
65544             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
65545                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
65546                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
65547                 }
65548                 checkTypeReferenceNode(heritageElement);
65549             });
65550             ts.forEach(node.members, checkSourceElement);
65551             if (produceDiagnostics) {
65552                 checkTypeForDuplicateIndexSignatures(node);
65553                 registerForUnusedIdentifiersCheck(node);
65554             }
65555         }
65556         function checkTypeAliasDeclaration(node) {
65557             // Grammar checking
65558             checkGrammarDecoratorsAndModifiers(node);
65559             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
65560             checkExportsOnMergedDeclarations(node);
65561             checkTypeParameters(node.typeParameters);
65562             checkSourceElement(node.type);
65563             registerForUnusedIdentifiersCheck(node);
65564         }
65565         function computeEnumMemberValues(node) {
65566             var nodeLinks = getNodeLinks(node);
65567             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
65568                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
65569                 var autoValue = 0;
65570                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
65571                     var member = _a[_i];
65572                     var value = computeMemberValue(member, autoValue);
65573                     getNodeLinks(member).enumMemberValue = value;
65574                     autoValue = typeof value === "number" ? value + 1 : undefined;
65575                 }
65576             }
65577         }
65578         function computeMemberValue(member, autoValue) {
65579             if (ts.isComputedNonLiteralName(member.name)) {
65580                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
65581             }
65582             else {
65583                 var text = ts.getTextOfPropertyName(member.name);
65584                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
65585                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
65586                 }
65587             }
65588             if (member.initializer) {
65589                 return computeConstantValue(member);
65590             }
65591             // In ambient non-const numeric enum declarations, enum members without initializers are
65592             // considered computed members (as opposed to having auto-incremented values).
65593             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
65594                 return undefined;
65595             }
65596             // If the member declaration specifies no value, the member is considered a constant enum member.
65597             // If the member is the first member in the enum declaration, it is assigned the value zero.
65598             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
65599             // occurs if the immediately preceding member is not a constant enum member.
65600             if (autoValue !== undefined) {
65601                 return autoValue;
65602             }
65603             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
65604             return undefined;
65605         }
65606         function computeConstantValue(member) {
65607             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
65608             var isConstEnum = ts.isEnumConst(member.parent);
65609             var initializer = member.initializer;
65610             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
65611             if (value !== undefined) {
65612                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
65613                     error(initializer, isNaN(value) ?
65614                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
65615                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
65616                 }
65617             }
65618             else if (enumKind === 1 /* Literal */) {
65619                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
65620                 return 0;
65621             }
65622             else if (isConstEnum) {
65623                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
65624             }
65625             else if (member.parent.flags & 8388608 /* Ambient */) {
65626                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
65627             }
65628             else {
65629                 // Only here do we need to check that the initializer is assignable to the enum type.
65630                 var source = checkExpression(initializer);
65631                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
65632                     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));
65633                 }
65634                 else {
65635                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
65636                 }
65637             }
65638             return value;
65639             function evaluate(expr) {
65640                 switch (expr.kind) {
65641                     case 207 /* PrefixUnaryExpression */:
65642                         var value_2 = evaluate(expr.operand);
65643                         if (typeof value_2 === "number") {
65644                             switch (expr.operator) {
65645                                 case 39 /* PlusToken */: return value_2;
65646                                 case 40 /* MinusToken */: return -value_2;
65647                                 case 54 /* TildeToken */: return ~value_2;
65648                             }
65649                         }
65650                         break;
65651                     case 209 /* BinaryExpression */:
65652                         var left = evaluate(expr.left);
65653                         var right = evaluate(expr.right);
65654                         if (typeof left === "number" && typeof right === "number") {
65655                             switch (expr.operatorToken.kind) {
65656                                 case 51 /* BarToken */: return left | right;
65657                                 case 50 /* AmpersandToken */: return left & right;
65658                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
65659                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
65660                                 case 47 /* LessThanLessThanToken */: return left << right;
65661                                 case 52 /* CaretToken */: return left ^ right;
65662                                 case 41 /* AsteriskToken */: return left * right;
65663                                 case 43 /* SlashToken */: return left / right;
65664                                 case 39 /* PlusToken */: return left + right;
65665                                 case 40 /* MinusToken */: return left - right;
65666                                 case 44 /* PercentToken */: return left % right;
65667                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
65668                             }
65669                         }
65670                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
65671                             return left + right;
65672                         }
65673                         break;
65674                     case 10 /* StringLiteral */:
65675                     case 14 /* NoSubstitutionTemplateLiteral */:
65676                         return expr.text;
65677                     case 8 /* NumericLiteral */:
65678                         checkGrammarNumericLiteral(expr);
65679                         return +expr.text;
65680                     case 200 /* ParenthesizedExpression */:
65681                         return evaluate(expr.expression);
65682                     case 75 /* Identifier */:
65683                         var identifier = expr;
65684                         if (isInfinityOrNaNString(identifier.escapedText)) {
65685                             return +(identifier.escapedText);
65686                         }
65687                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
65688                     case 195 /* ElementAccessExpression */:
65689                     case 194 /* PropertyAccessExpression */:
65690                         var ex = expr;
65691                         if (isConstantMemberAccess(ex)) {
65692                             var type = getTypeOfExpression(ex.expression);
65693                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
65694                                 var name = void 0;
65695                                 if (ex.kind === 194 /* PropertyAccessExpression */) {
65696                                     name = ex.name.escapedText;
65697                                 }
65698                                 else {
65699                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
65700                                 }
65701                                 return evaluateEnumMember(expr, type.symbol, name);
65702                             }
65703                         }
65704                         break;
65705                 }
65706                 return undefined;
65707             }
65708             function evaluateEnumMember(expr, enumSymbol, name) {
65709                 var memberSymbol = enumSymbol.exports.get(name);
65710                 if (memberSymbol) {
65711                     var declaration = memberSymbol.valueDeclaration;
65712                     if (declaration !== member) {
65713                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
65714                             return getEnumMemberValue(declaration);
65715                         }
65716                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
65717                         return 0;
65718                     }
65719                     else {
65720                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
65721                     }
65722                 }
65723                 return undefined;
65724             }
65725         }
65726         function isConstantMemberAccess(node) {
65727             return node.kind === 75 /* Identifier */ ||
65728                 node.kind === 194 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
65729                 node.kind === 195 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
65730                     ts.isStringLiteralLike(node.argumentExpression);
65731         }
65732         function checkEnumDeclaration(node) {
65733             if (!produceDiagnostics) {
65734                 return;
65735             }
65736             // Grammar checking
65737             checkGrammarDecoratorsAndModifiers(node);
65738             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
65739             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65740             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65741             checkExportsOnMergedDeclarations(node);
65742             node.members.forEach(checkEnumMember);
65743             computeEnumMemberValues(node);
65744             // Spec 2014 - Section 9.3:
65745             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
65746             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
65747             // for the first member.
65748             //
65749             // Only perform this check once per symbol
65750             var enumSymbol = getSymbolOfNode(node);
65751             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
65752             if (node === firstDeclaration) {
65753                 if (enumSymbol.declarations.length > 1) {
65754                     var enumIsConst_1 = ts.isEnumConst(node);
65755                     // check that const is placed\omitted on all enum declarations
65756                     ts.forEach(enumSymbol.declarations, function (decl) {
65757                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
65758                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
65759                         }
65760                     });
65761                 }
65762                 var seenEnumMissingInitialInitializer_1 = false;
65763                 ts.forEach(enumSymbol.declarations, function (declaration) {
65764                     // return true if we hit a violation of the rule, false otherwise
65765                     if (declaration.kind !== 248 /* EnumDeclaration */) {
65766                         return false;
65767                     }
65768                     var enumDeclaration = declaration;
65769                     if (!enumDeclaration.members.length) {
65770                         return false;
65771                     }
65772                     var firstEnumMember = enumDeclaration.members[0];
65773                     if (!firstEnumMember.initializer) {
65774                         if (seenEnumMissingInitialInitializer_1) {
65775                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
65776                         }
65777                         else {
65778                             seenEnumMissingInitialInitializer_1 = true;
65779                         }
65780                     }
65781                 });
65782             }
65783         }
65784         function checkEnumMember(node) {
65785             if (ts.isPrivateIdentifier(node.name)) {
65786                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
65787             }
65788         }
65789         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
65790             var declarations = symbol.declarations;
65791             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
65792                 var declaration = declarations_8[_i];
65793                 if ((declaration.kind === 245 /* ClassDeclaration */ ||
65794                     (declaration.kind === 244 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
65795                     !(declaration.flags & 8388608 /* Ambient */)) {
65796                     return declaration;
65797                 }
65798             }
65799             return undefined;
65800         }
65801         function inSameLexicalScope(node1, node2) {
65802             var container1 = ts.getEnclosingBlockScopeContainer(node1);
65803             var container2 = ts.getEnclosingBlockScopeContainer(node2);
65804             if (isGlobalSourceFile(container1)) {
65805                 return isGlobalSourceFile(container2);
65806             }
65807             else if (isGlobalSourceFile(container2)) {
65808                 return false;
65809             }
65810             else {
65811                 return container1 === container2;
65812             }
65813         }
65814         function checkModuleDeclaration(node) {
65815             if (produceDiagnostics) {
65816                 // Grammar checking
65817                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
65818                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
65819                 if (isGlobalAugmentation && !inAmbientContext) {
65820                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
65821                 }
65822                 var isAmbientExternalModule = ts.isAmbientModule(node);
65823                 var contextErrorMessage = isAmbientExternalModule
65824                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
65825                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
65826                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
65827                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
65828                     return;
65829                 }
65830                 if (!checkGrammarDecoratorsAndModifiers(node)) {
65831                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
65832                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
65833                     }
65834                 }
65835                 if (ts.isIdentifier(node.name)) {
65836                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
65837                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
65838                 }
65839                 checkExportsOnMergedDeclarations(node);
65840                 var symbol = getSymbolOfNode(node);
65841                 // The following checks only apply on a non-ambient instantiated module declaration.
65842                 if (symbol.flags & 512 /* ValueModule */
65843                     && !inAmbientContext
65844                     && symbol.declarations.length > 1
65845                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
65846                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
65847                     if (firstNonAmbientClassOrFunc) {
65848                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
65849                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
65850                         }
65851                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
65852                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
65853                         }
65854                     }
65855                     // if the module merges with a class declaration in the same lexical scope,
65856                     // we need to track this to ensure the correct emit.
65857                     var mergedClass = ts.getDeclarationOfKind(symbol, 245 /* ClassDeclaration */);
65858                     if (mergedClass &&
65859                         inSameLexicalScope(node, mergedClass)) {
65860                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
65861                     }
65862                 }
65863                 if (isAmbientExternalModule) {
65864                     if (ts.isExternalModuleAugmentation(node)) {
65865                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
65866                         // otherwise we'll be swamped in cascading errors.
65867                         // We can detect if augmentation was applied using following rules:
65868                         // - augmentation for a global scope is always applied
65869                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
65870                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
65871                         if (checkBody && node.body) {
65872                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
65873                                 var statement = _a[_i];
65874                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
65875                             }
65876                         }
65877                     }
65878                     else if (isGlobalSourceFile(node.parent)) {
65879                         if (isGlobalAugmentation) {
65880                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65881                         }
65882                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
65883                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
65884                         }
65885                     }
65886                     else {
65887                         if (isGlobalAugmentation) {
65888                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
65889                         }
65890                         else {
65891                             // Node is not an augmentation and is not located on the script level.
65892                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
65893                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
65894                         }
65895                     }
65896                 }
65897             }
65898             if (node.body) {
65899                 checkSourceElement(node.body);
65900                 if (!ts.isGlobalScopeAugmentation(node)) {
65901                     registerForUnusedIdentifiersCheck(node);
65902                 }
65903             }
65904         }
65905         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
65906             switch (node.kind) {
65907                 case 225 /* VariableStatement */:
65908                     // error each individual name in variable statement instead of marking the entire variable statement
65909                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
65910                         var decl = _a[_i];
65911                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
65912                     }
65913                     break;
65914                 case 259 /* ExportAssignment */:
65915                 case 260 /* ExportDeclaration */:
65916                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
65917                     break;
65918                 case 253 /* ImportEqualsDeclaration */:
65919                 case 254 /* ImportDeclaration */:
65920                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
65921                     break;
65922                 case 191 /* BindingElement */:
65923                 case 242 /* VariableDeclaration */:
65924                     var name = node.name;
65925                     if (ts.isBindingPattern(name)) {
65926                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
65927                             var el = _c[_b];
65928                             // mark individual names in binding pattern
65929                             checkModuleAugmentationElement(el, isGlobalAugmentation);
65930                         }
65931                         break;
65932                     }
65933                 // falls through
65934                 case 245 /* ClassDeclaration */:
65935                 case 248 /* EnumDeclaration */:
65936                 case 244 /* FunctionDeclaration */:
65937                 case 246 /* InterfaceDeclaration */:
65938                 case 249 /* ModuleDeclaration */:
65939                 case 247 /* TypeAliasDeclaration */:
65940                     if (isGlobalAugmentation) {
65941                         return;
65942                     }
65943                     var symbol = getSymbolOfNode(node);
65944                     if (symbol) {
65945                         // module augmentations cannot introduce new names on the top level scope of the module
65946                         // this is done it two steps
65947                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
65948                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
65949                         var reportError = !(symbol.flags & 33554432 /* Transient */);
65950                         if (!reportError) {
65951                             // symbol should not originate in augmentation
65952                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
65953                         }
65954                     }
65955                     break;
65956             }
65957         }
65958         function getFirstNonModuleExportsIdentifier(node) {
65959             switch (node.kind) {
65960                 case 75 /* Identifier */:
65961                     return node;
65962                 case 153 /* QualifiedName */:
65963                     do {
65964                         node = node.left;
65965                     } while (node.kind !== 75 /* Identifier */);
65966                     return node;
65967                 case 194 /* PropertyAccessExpression */:
65968                     do {
65969                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
65970                             return node.name;
65971                         }
65972                         node = node.expression;
65973                     } while (node.kind !== 75 /* Identifier */);
65974                     return node;
65975             }
65976         }
65977         function checkExternalImportOrExportDeclaration(node) {
65978             var moduleName = ts.getExternalModuleName(node);
65979             if (!moduleName || ts.nodeIsMissing(moduleName)) {
65980                 // Should be a parse error.
65981                 return false;
65982             }
65983             if (!ts.isStringLiteral(moduleName)) {
65984                 error(moduleName, ts.Diagnostics.String_literal_expected);
65985                 return false;
65986             }
65987             var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
65988             if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule) {
65989                 error(moduleName, node.kind === 260 /* ExportDeclaration */ ?
65990                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
65991                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
65992                 return false;
65993             }
65994             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
65995                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
65996                 // no need to do this again.
65997                 if (!isTopLevelInExternalModuleAugmentation(node)) {
65998                     // TypeScript 1.0 spec (April 2013): 12.1.6
65999                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
66000                     // other external modules only through top - level external module names.
66001                     // Relative external module names are not permitted.
66002                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
66003                     return false;
66004                 }
66005             }
66006             return true;
66007         }
66008         function checkAliasSymbol(node) {
66009             var symbol = getSymbolOfNode(node);
66010             var target = resolveAlias(symbol);
66011             var shouldSkipWithJSExpandoTargets = symbol.flags & 67108864 /* Assignment */;
66012             if (!shouldSkipWithJSExpandoTargets && target !== unknownSymbol) {
66013                 // For external modules symbol represents local symbol for an alias.
66014                 // This local symbol will merge any other local declarations (excluding other aliases)
66015                 // and symbol.flags will contains combined representation for all merged declaration.
66016                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
66017                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
66018                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
66019                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
66020                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
66021                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
66022                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
66023                 if (target.flags & excludedMeanings) {
66024                     var message = node.kind === 263 /* ExportSpecifier */ ?
66025                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
66026                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
66027                     error(node, message, symbolToString(symbol));
66028                 }
66029                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
66030                 if (compilerOptions.isolatedModules
66031                     && node.kind === 263 /* ExportSpecifier */
66032                     && !node.parent.parent.isTypeOnly
66033                     && !(target.flags & 111551 /* Value */)
66034                     && !(node.flags & 8388608 /* Ambient */)) {
66035                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
66036                 }
66037             }
66038         }
66039         function checkImportBinding(node) {
66040             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
66041             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
66042             checkAliasSymbol(node);
66043         }
66044         function checkImportDeclaration(node) {
66045             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66046                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66047                 return;
66048             }
66049             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66050                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
66051             }
66052             if (checkExternalImportOrExportDeclaration(node)) {
66053                 var importClause = node.importClause;
66054                 if (importClause && !checkGrammarImportClause(importClause)) {
66055                     if (importClause.name) {
66056                         checkImportBinding(importClause);
66057                     }
66058                     if (importClause.namedBindings) {
66059                         if (importClause.namedBindings.kind === 256 /* NamespaceImport */) {
66060                             checkImportBinding(importClause.namedBindings);
66061                         }
66062                         else {
66063                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
66064                             if (moduleExisted) {
66065                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
66066                             }
66067                         }
66068                     }
66069                 }
66070             }
66071         }
66072         function checkImportEqualsDeclaration(node) {
66073             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
66074                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
66075                 return;
66076             }
66077             checkGrammarDecoratorsAndModifiers(node);
66078             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
66079                 checkImportBinding(node);
66080                 if (ts.hasModifier(node, 1 /* Export */)) {
66081                     markExportAsReferenced(node);
66082                 }
66083                 if (node.moduleReference.kind !== 265 /* ExternalModuleReference */) {
66084                     var target = resolveAlias(getSymbolOfNode(node));
66085                     if (target !== unknownSymbol) {
66086                         if (target.flags & 111551 /* Value */) {
66087                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
66088                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
66089                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
66090                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
66091                             }
66092                         }
66093                         if (target.flags & 788968 /* Type */) {
66094                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
66095                         }
66096                     }
66097                 }
66098                 else {
66099                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
66100                         // Import equals declaration is deprecated in es6 or above
66101                         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);
66102                     }
66103                 }
66104             }
66105         }
66106         function checkExportDeclaration(node) {
66107             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
66108                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
66109                 return;
66110             }
66111             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66112                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
66113             }
66114             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
66115                 checkExternalEmitHelpers(node, 1048576 /* CreateBinding */);
66116             }
66117             checkGrammarExportDeclaration(node);
66118             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
66119                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
66120                     // export { x, y }
66121                     // export { x, y } from "foo"
66122                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
66123                     var inAmbientExternalModule = node.parent.kind === 250 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
66124                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 250 /* ModuleBlock */ &&
66125                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
66126                     if (node.parent.kind !== 290 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
66127                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
66128                     }
66129                 }
66130                 else {
66131                     // export * from "foo"
66132                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
66133                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
66134                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
66135                     }
66136                     else if (node.exportClause) {
66137                         checkAliasSymbol(node.exportClause);
66138                     }
66139                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
66140                         checkExternalEmitHelpers(node, 65536 /* ExportStar */);
66141                     }
66142                 }
66143             }
66144         }
66145         function checkGrammarExportDeclaration(node) {
66146             var _a;
66147             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 261 /* NamedExports */;
66148             if (isTypeOnlyExportStar) {
66149                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
66150             }
66151             return !isTypeOnlyExportStar;
66152         }
66153         function checkGrammarModuleElementContext(node, errorMessage) {
66154             var isInAppropriateContext = node.parent.kind === 290 /* SourceFile */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 249 /* ModuleDeclaration */;
66155             if (!isInAppropriateContext) {
66156                 grammarErrorOnFirstToken(node, errorMessage);
66157             }
66158             return !isInAppropriateContext;
66159         }
66160         function importClauseContainsReferencedImport(importClause) {
66161             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66162                 return !!getSymbolOfNode(declaration).isReferenced;
66163             });
66164         }
66165         function importClauseContainsConstEnumUsedAsValue(importClause) {
66166             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
66167                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
66168             });
66169         }
66170         function checkImportsForTypeOnlyConversion(sourceFile) {
66171             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
66172                 var statement = _a[_i];
66173                 if (ts.isImportDeclaration(statement) &&
66174                     statement.importClause &&
66175                     !statement.importClause.isTypeOnly &&
66176                     importClauseContainsReferencedImport(statement.importClause) &&
66177                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
66178                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
66179                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
66180                 }
66181             }
66182         }
66183         function checkExportSpecifier(node) {
66184             checkAliasSymbol(node);
66185             if (ts.getEmitDeclarations(compilerOptions)) {
66186                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
66187             }
66188             if (!node.parent.parent.moduleSpecifier) {
66189                 var exportedName = node.propertyName || node.name;
66190                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
66191                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
66192                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
66193                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
66194                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
66195                 }
66196                 else {
66197                     markExportAsReferenced(node);
66198                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
66199                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
66200                         checkExpressionCached(node.propertyName || node.name);
66201                     }
66202                 }
66203             }
66204         }
66205         function checkExportAssignment(node) {
66206             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
66207                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
66208                 return;
66209             }
66210             var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
66211             if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
66212                 if (node.isExportEquals) {
66213                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
66214                 }
66215                 else {
66216                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
66217                 }
66218                 return;
66219             }
66220             // Grammar checking
66221             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasModifiers(node)) {
66222                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
66223             }
66224             if (node.expression.kind === 75 /* Identifier */) {
66225                 var id = node.expression;
66226                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
66227                 if (sym) {
66228                     markAliasReferenced(sym, id);
66229                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
66230                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
66231                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
66232                         // However if it is a value, we need to check it's being used correctly
66233                         checkExpressionCached(node.expression);
66234                     }
66235                 }
66236                 if (ts.getEmitDeclarations(compilerOptions)) {
66237                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
66238                 }
66239             }
66240             else {
66241                 checkExpressionCached(node.expression);
66242             }
66243             checkExternalModuleExports(container);
66244             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
66245                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
66246             }
66247             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
66248                 if (moduleKind >= ts.ModuleKind.ES2015) {
66249                     // export assignment is not supported in es6 modules
66250                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
66251                 }
66252                 else if (moduleKind === ts.ModuleKind.System) {
66253                     // system modules does not support export assignment
66254                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
66255                 }
66256             }
66257         }
66258         function hasExportedMembers(moduleSymbol) {
66259             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
66260         }
66261         function checkExternalModuleExports(node) {
66262             var moduleSymbol = getSymbolOfNode(node);
66263             var links = getSymbolLinks(moduleSymbol);
66264             if (!links.exportsChecked) {
66265                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
66266                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
66267                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
66268                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
66269                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
66270                     }
66271                 }
66272                 // Checks for export * conflicts
66273                 var exports_2 = getExportsOfModule(moduleSymbol);
66274                 if (exports_2) {
66275                     exports_2.forEach(function (_a, id) {
66276                         var declarations = _a.declarations, flags = _a.flags;
66277                         if (id === "__export") {
66278                             return;
66279                         }
66280                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
66281                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
66282                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
66283                             return;
66284                         }
66285                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
66286                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
66287                             // it is legal to merge type alias with other values
66288                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
66289                             return;
66290                         }
66291                         if (exportedDeclarationsCount > 1) {
66292                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
66293                                 var declaration = declarations_9[_i];
66294                                 if (isNotOverload(declaration)) {
66295                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
66296                                 }
66297                             }
66298                         }
66299                     });
66300                 }
66301                 links.exportsChecked = true;
66302             }
66303         }
66304         function checkSourceElement(node) {
66305             if (node) {
66306                 var saveCurrentNode = currentNode;
66307                 currentNode = node;
66308                 instantiationCount = 0;
66309                 checkSourceElementWorker(node);
66310                 currentNode = saveCurrentNode;
66311             }
66312         }
66313         function checkSourceElementWorker(node) {
66314             if (ts.isInJSFile(node)) {
66315                 ts.forEach(node.jsDoc, function (_a) {
66316                     var tags = _a.tags;
66317                     return ts.forEach(tags, checkSourceElement);
66318                 });
66319             }
66320             var kind = node.kind;
66321             if (cancellationToken) {
66322                 // Only bother checking on a few construct kinds.  We don't want to be excessively
66323                 // hitting the cancellation token on every node we check.
66324                 switch (kind) {
66325                     case 249 /* ModuleDeclaration */:
66326                     case 245 /* ClassDeclaration */:
66327                     case 246 /* InterfaceDeclaration */:
66328                     case 244 /* FunctionDeclaration */:
66329                         cancellationToken.throwIfCancellationRequested();
66330                 }
66331             }
66332             if (kind >= 225 /* FirstStatement */ && kind <= 241 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
66333                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
66334             }
66335             switch (kind) {
66336                 case 155 /* TypeParameter */:
66337                     return checkTypeParameter(node);
66338                 case 156 /* Parameter */:
66339                     return checkParameter(node);
66340                 case 159 /* PropertyDeclaration */:
66341                     return checkPropertyDeclaration(node);
66342                 case 158 /* PropertySignature */:
66343                     return checkPropertySignature(node);
66344                 case 170 /* FunctionType */:
66345                 case 171 /* ConstructorType */:
66346                 case 165 /* CallSignature */:
66347                 case 166 /* ConstructSignature */:
66348                 case 167 /* IndexSignature */:
66349                     return checkSignatureDeclaration(node);
66350                 case 161 /* MethodDeclaration */:
66351                 case 160 /* MethodSignature */:
66352                     return checkMethodDeclaration(node);
66353                 case 162 /* Constructor */:
66354                     return checkConstructorDeclaration(node);
66355                 case 163 /* GetAccessor */:
66356                 case 164 /* SetAccessor */:
66357                     return checkAccessorDeclaration(node);
66358                 case 169 /* TypeReference */:
66359                     return checkTypeReferenceNode(node);
66360                 case 168 /* TypePredicate */:
66361                     return checkTypePredicate(node);
66362                 case 172 /* TypeQuery */:
66363                     return checkTypeQuery(node);
66364                 case 173 /* TypeLiteral */:
66365                     return checkTypeLiteral(node);
66366                 case 174 /* ArrayType */:
66367                     return checkArrayType(node);
66368                 case 175 /* TupleType */:
66369                     return checkTupleType(node);
66370                 case 178 /* UnionType */:
66371                 case 179 /* IntersectionType */:
66372                     return checkUnionOrIntersectionType(node);
66373                 case 182 /* ParenthesizedType */:
66374                 case 176 /* OptionalType */:
66375                 case 177 /* RestType */:
66376                     return checkSourceElement(node.type);
66377                 case 183 /* ThisType */:
66378                     return checkThisType(node);
66379                 case 184 /* TypeOperator */:
66380                     return checkTypeOperator(node);
66381                 case 180 /* ConditionalType */:
66382                     return checkConditionalType(node);
66383                 case 181 /* InferType */:
66384                     return checkInferType(node);
66385                 case 188 /* ImportType */:
66386                     return checkImportType(node);
66387                 case 307 /* JSDocAugmentsTag */:
66388                     return checkJSDocAugmentsTag(node);
66389                 case 308 /* JSDocImplementsTag */:
66390                     return checkJSDocImplementsTag(node);
66391                 case 322 /* JSDocTypedefTag */:
66392                 case 315 /* JSDocCallbackTag */:
66393                 case 316 /* JSDocEnumTag */:
66394                     return checkJSDocTypeAliasTag(node);
66395                 case 321 /* JSDocTemplateTag */:
66396                     return checkJSDocTemplateTag(node);
66397                 case 320 /* JSDocTypeTag */:
66398                     return checkJSDocTypeTag(node);
66399                 case 317 /* JSDocParameterTag */:
66400                     return checkJSDocParameterTag(node);
66401                 case 323 /* JSDocPropertyTag */:
66402                     return checkJSDocPropertyTag(node);
66403                 case 300 /* JSDocFunctionType */:
66404                     checkJSDocFunctionType(node);
66405                 // falls through
66406                 case 298 /* JSDocNonNullableType */:
66407                 case 297 /* JSDocNullableType */:
66408                 case 295 /* JSDocAllType */:
66409                 case 296 /* JSDocUnknownType */:
66410                 case 304 /* JSDocTypeLiteral */:
66411                     checkJSDocTypeIsInJsFile(node);
66412                     ts.forEachChild(node, checkSourceElement);
66413                     return;
66414                 case 301 /* JSDocVariadicType */:
66415                     checkJSDocVariadicType(node);
66416                     return;
66417                 case 294 /* JSDocTypeExpression */:
66418                     return checkSourceElement(node.type);
66419                 case 185 /* IndexedAccessType */:
66420                     return checkIndexedAccessType(node);
66421                 case 186 /* MappedType */:
66422                     return checkMappedType(node);
66423                 case 244 /* FunctionDeclaration */:
66424                     return checkFunctionDeclaration(node);
66425                 case 223 /* Block */:
66426                 case 250 /* ModuleBlock */:
66427                     return checkBlock(node);
66428                 case 225 /* VariableStatement */:
66429                     return checkVariableStatement(node);
66430                 case 226 /* ExpressionStatement */:
66431                     return checkExpressionStatement(node);
66432                 case 227 /* IfStatement */:
66433                     return checkIfStatement(node);
66434                 case 228 /* DoStatement */:
66435                     return checkDoStatement(node);
66436                 case 229 /* WhileStatement */:
66437                     return checkWhileStatement(node);
66438                 case 230 /* ForStatement */:
66439                     return checkForStatement(node);
66440                 case 231 /* ForInStatement */:
66441                     return checkForInStatement(node);
66442                 case 232 /* ForOfStatement */:
66443                     return checkForOfStatement(node);
66444                 case 233 /* ContinueStatement */:
66445                 case 234 /* BreakStatement */:
66446                     return checkBreakOrContinueStatement(node);
66447                 case 235 /* ReturnStatement */:
66448                     return checkReturnStatement(node);
66449                 case 236 /* WithStatement */:
66450                     return checkWithStatement(node);
66451                 case 237 /* SwitchStatement */:
66452                     return checkSwitchStatement(node);
66453                 case 238 /* LabeledStatement */:
66454                     return checkLabeledStatement(node);
66455                 case 239 /* ThrowStatement */:
66456                     return checkThrowStatement(node);
66457                 case 240 /* TryStatement */:
66458                     return checkTryStatement(node);
66459                 case 242 /* VariableDeclaration */:
66460                     return checkVariableDeclaration(node);
66461                 case 191 /* BindingElement */:
66462                     return checkBindingElement(node);
66463                 case 245 /* ClassDeclaration */:
66464                     return checkClassDeclaration(node);
66465                 case 246 /* InterfaceDeclaration */:
66466                     return checkInterfaceDeclaration(node);
66467                 case 247 /* TypeAliasDeclaration */:
66468                     return checkTypeAliasDeclaration(node);
66469                 case 248 /* EnumDeclaration */:
66470                     return checkEnumDeclaration(node);
66471                 case 249 /* ModuleDeclaration */:
66472                     return checkModuleDeclaration(node);
66473                 case 254 /* ImportDeclaration */:
66474                     return checkImportDeclaration(node);
66475                 case 253 /* ImportEqualsDeclaration */:
66476                     return checkImportEqualsDeclaration(node);
66477                 case 260 /* ExportDeclaration */:
66478                     return checkExportDeclaration(node);
66479                 case 259 /* ExportAssignment */:
66480                     return checkExportAssignment(node);
66481                 case 224 /* EmptyStatement */:
66482                 case 241 /* DebuggerStatement */:
66483                     checkGrammarStatementInAmbientContext(node);
66484                     return;
66485                 case 264 /* MissingDeclaration */:
66486                     return checkMissingDeclaration(node);
66487             }
66488         }
66489         function checkJSDocTypeIsInJsFile(node) {
66490             if (!ts.isInJSFile(node)) {
66491                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
66492             }
66493         }
66494         function checkJSDocVariadicType(node) {
66495             checkJSDocTypeIsInJsFile(node);
66496             checkSourceElement(node.type);
66497             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
66498             var parent = node.parent;
66499             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66500                 if (ts.last(parent.parent.parameters) !== parent) {
66501                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66502                 }
66503                 return;
66504             }
66505             if (!ts.isJSDocTypeExpression(parent)) {
66506                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66507             }
66508             var paramTag = node.parent.parent;
66509             if (!ts.isJSDocParameterTag(paramTag)) {
66510                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
66511                 return;
66512             }
66513             var param = ts.getParameterSymbolFromJSDoc(paramTag);
66514             if (!param) {
66515                 // We will error in `checkJSDocParameterTag`.
66516                 return;
66517             }
66518             var host = ts.getHostSignatureFromJSDoc(paramTag);
66519             if (!host || ts.last(host.parameters).symbol !== param) {
66520                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
66521             }
66522         }
66523         function getTypeFromJSDocVariadicType(node) {
66524             var type = getTypeFromTypeNode(node.type);
66525             var parent = node.parent;
66526             var paramTag = node.parent.parent;
66527             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
66528                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
66529                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
66530                 if (host_1) {
66531                     /*
66532                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
66533                     So in the following situation we will not create an array type:
66534                         /** @param {...number} a * /
66535                         function f(a) {}
66536                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
66537                     */
66538                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
66539                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
66540                     if (!lastParamDeclaration ||
66541                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
66542                         return createArrayType(type);
66543                     }
66544                 }
66545             }
66546             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
66547                 return createArrayType(type);
66548             }
66549             return addOptionality(type);
66550         }
66551         // Function and class expression bodies are checked after all statements in the enclosing body. This is
66552         // to ensure constructs like the following are permitted:
66553         //     const foo = function () {
66554         //        const s = foo();
66555         //        return "hello";
66556         //     }
66557         // Here, performing a full type check of the body of the function expression whilst in the process of
66558         // determining the type of foo would cause foo to be given type any because of the recursive reference.
66559         // Delaying the type check of the body ensures foo has been assigned a type.
66560         function checkNodeDeferred(node) {
66561             var enclosingFile = ts.getSourceFileOfNode(node);
66562             var links = getNodeLinks(enclosingFile);
66563             if (!(links.flags & 1 /* TypeChecked */)) {
66564                 links.deferredNodes = links.deferredNodes || ts.createMap();
66565                 var id = "" + getNodeId(node);
66566                 links.deferredNodes.set(id, node);
66567             }
66568         }
66569         function checkDeferredNodes(context) {
66570             var links = getNodeLinks(context);
66571             if (links.deferredNodes) {
66572                 links.deferredNodes.forEach(checkDeferredNode);
66573             }
66574         }
66575         function checkDeferredNode(node) {
66576             var saveCurrentNode = currentNode;
66577             currentNode = node;
66578             instantiationCount = 0;
66579             switch (node.kind) {
66580                 case 196 /* CallExpression */:
66581                 case 197 /* NewExpression */:
66582                 case 198 /* TaggedTemplateExpression */:
66583                 case 157 /* Decorator */:
66584                 case 268 /* JsxOpeningElement */:
66585                     // These node kinds are deferred checked when overload resolution fails
66586                     // To save on work, we ensure the arguments are checked just once, in
66587                     // a deferred way
66588                     resolveUntypedCall(node);
66589                     break;
66590                 case 201 /* FunctionExpression */:
66591                 case 202 /* ArrowFunction */:
66592                 case 161 /* MethodDeclaration */:
66593                 case 160 /* MethodSignature */:
66594                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
66595                     break;
66596                 case 163 /* GetAccessor */:
66597                 case 164 /* SetAccessor */:
66598                     checkAccessorDeclaration(node);
66599                     break;
66600                 case 214 /* ClassExpression */:
66601                     checkClassExpressionDeferred(node);
66602                     break;
66603                 case 267 /* JsxSelfClosingElement */:
66604                     checkJsxSelfClosingElementDeferred(node);
66605                     break;
66606                 case 266 /* JsxElement */:
66607                     checkJsxElementDeferred(node);
66608                     break;
66609             }
66610             currentNode = saveCurrentNode;
66611         }
66612         function checkSourceFile(node) {
66613             ts.performance.mark("beforeCheck");
66614             checkSourceFileWorker(node);
66615             ts.performance.mark("afterCheck");
66616             ts.performance.measure("Check", "beforeCheck", "afterCheck");
66617         }
66618         function unusedIsError(kind, isAmbient) {
66619             if (isAmbient) {
66620                 return false;
66621             }
66622             switch (kind) {
66623                 case 0 /* Local */:
66624                     return !!compilerOptions.noUnusedLocals;
66625                 case 1 /* Parameter */:
66626                     return !!compilerOptions.noUnusedParameters;
66627                 default:
66628                     return ts.Debug.assertNever(kind);
66629             }
66630         }
66631         function getPotentiallyUnusedIdentifiers(sourceFile) {
66632             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
66633         }
66634         // Fully type check a source file and collect the relevant diagnostics.
66635         function checkSourceFileWorker(node) {
66636             var links = getNodeLinks(node);
66637             if (!(links.flags & 1 /* TypeChecked */)) {
66638                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
66639                     return;
66640                 }
66641                 // Grammar checking
66642                 checkGrammarSourceFile(node);
66643                 ts.clear(potentialThisCollisions);
66644                 ts.clear(potentialNewTargetCollisions);
66645                 ts.clear(potentialWeakMapCollisions);
66646                 ts.forEach(node.statements, checkSourceElement);
66647                 checkSourceElement(node.endOfFileToken);
66648                 checkDeferredNodes(node);
66649                 if (ts.isExternalOrCommonJsModule(node)) {
66650                     registerForUnusedIdentifiersCheck(node);
66651                 }
66652                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
66653                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
66654                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
66655                             diagnostics.add(diag);
66656                         }
66657                     });
66658                 }
66659                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
66660                     !node.isDeclarationFile &&
66661                     ts.isExternalModule(node)) {
66662                     checkImportsForTypeOnlyConversion(node);
66663                 }
66664                 if (ts.isExternalOrCommonJsModule(node)) {
66665                     checkExternalModuleExports(node);
66666                 }
66667                 if (potentialThisCollisions.length) {
66668                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
66669                     ts.clear(potentialThisCollisions);
66670                 }
66671                 if (potentialNewTargetCollisions.length) {
66672                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
66673                     ts.clear(potentialNewTargetCollisions);
66674                 }
66675                 if (potentialWeakMapCollisions.length) {
66676                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
66677                     ts.clear(potentialWeakMapCollisions);
66678                 }
66679                 links.flags |= 1 /* TypeChecked */;
66680             }
66681         }
66682         function getDiagnostics(sourceFile, ct) {
66683             try {
66684                 // Record the cancellation token so it can be checked later on during checkSourceElement.
66685                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
66686                 // this call is done.
66687                 cancellationToken = ct;
66688                 return getDiagnosticsWorker(sourceFile);
66689             }
66690             finally {
66691                 cancellationToken = undefined;
66692             }
66693         }
66694         function getDiagnosticsWorker(sourceFile) {
66695             throwIfNonDiagnosticsProducing();
66696             if (sourceFile) {
66697                 // Some global diagnostics are deferred until they are needed and
66698                 // may not be reported in the first call to getGlobalDiagnostics.
66699                 // We should catch these changes and report them.
66700                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66701                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
66702                 checkSourceFile(sourceFile);
66703                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
66704                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
66705                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
66706                     // If the arrays are not the same reference, new diagnostics were added.
66707                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
66708                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
66709                 }
66710                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
66711                     // If the arrays are the same reference, but the length has changed, a single
66712                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
66713                     // same array.
66714                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
66715                 }
66716                 return semanticDiagnostics;
66717             }
66718             // Global diagnostics are always added when a file is not provided to
66719             // getDiagnostics
66720             ts.forEach(host.getSourceFiles(), checkSourceFile);
66721             return diagnostics.getDiagnostics();
66722         }
66723         function getGlobalDiagnostics() {
66724             throwIfNonDiagnosticsProducing();
66725             return diagnostics.getGlobalDiagnostics();
66726         }
66727         function throwIfNonDiagnosticsProducing() {
66728             if (!produceDiagnostics) {
66729                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
66730             }
66731         }
66732         // Language service support
66733         function getSymbolsInScope(location, meaning) {
66734             if (location.flags & 16777216 /* InWithStatement */) {
66735                 // We cannot answer semantic questions within a with block, do not proceed any further
66736                 return [];
66737             }
66738             var symbols = ts.createSymbolTable();
66739             var isStatic = false;
66740             populateSymbols();
66741             symbols.delete("this" /* This */); // Not a symbol, a keyword
66742             return symbolsToArray(symbols);
66743             function populateSymbols() {
66744                 while (location) {
66745                     if (location.locals && !isGlobalSourceFile(location)) {
66746                         copySymbols(location.locals, meaning);
66747                     }
66748                     switch (location.kind) {
66749                         case 290 /* SourceFile */:
66750                             if (!ts.isExternalOrCommonJsModule(location))
66751                                 break;
66752                         // falls through
66753                         case 249 /* ModuleDeclaration */:
66754                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
66755                             break;
66756                         case 248 /* EnumDeclaration */:
66757                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
66758                             break;
66759                         case 214 /* ClassExpression */:
66760                             var className = location.name;
66761                             if (className) {
66762                                 copySymbol(location.symbol, meaning);
66763                             }
66764                         // this fall-through is necessary because we would like to handle
66765                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
66766                         // falls through
66767                         case 245 /* ClassDeclaration */:
66768                         case 246 /* InterfaceDeclaration */:
66769                             // If we didn't come from static member of class or interface,
66770                             // add the type parameters into the symbol table
66771                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
66772                             // Note: that the memberFlags come from previous iteration.
66773                             if (!isStatic) {
66774                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
66775                             }
66776                             break;
66777                         case 201 /* FunctionExpression */:
66778                             var funcName = location.name;
66779                             if (funcName) {
66780                                 copySymbol(location.symbol, meaning);
66781                             }
66782                             break;
66783                     }
66784                     if (ts.introducesArgumentsExoticObject(location)) {
66785                         copySymbol(argumentsSymbol, meaning);
66786                     }
66787                     isStatic = ts.hasModifier(location, 32 /* Static */);
66788                     location = location.parent;
66789                 }
66790                 copySymbols(globals, meaning);
66791             }
66792             /**
66793              * Copy the given symbol into symbol tables if the symbol has the given meaning
66794              * and it doesn't already existed in the symbol table
66795              * @param key a key for storing in symbol table; if undefined, use symbol.name
66796              * @param symbol the symbol to be added into symbol table
66797              * @param meaning meaning of symbol to filter by before adding to symbol table
66798              */
66799             function copySymbol(symbol, meaning) {
66800                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
66801                     var id = symbol.escapedName;
66802                     // We will copy all symbol regardless of its reserved name because
66803                     // symbolsToArray will check whether the key is a reserved name and
66804                     // it will not copy symbol with reserved name to the array
66805                     if (!symbols.has(id)) {
66806                         symbols.set(id, symbol);
66807                     }
66808                 }
66809             }
66810             function copySymbols(source, meaning) {
66811                 if (meaning) {
66812                     source.forEach(function (symbol) {
66813                         copySymbol(symbol, meaning);
66814                     });
66815                 }
66816             }
66817         }
66818         function isTypeDeclarationName(name) {
66819             return name.kind === 75 /* Identifier */ &&
66820                 isTypeDeclaration(name.parent) &&
66821                 name.parent.name === name;
66822         }
66823         function isTypeDeclaration(node) {
66824             switch (node.kind) {
66825                 case 155 /* TypeParameter */:
66826                 case 245 /* ClassDeclaration */:
66827                 case 246 /* InterfaceDeclaration */:
66828                 case 247 /* TypeAliasDeclaration */:
66829                 case 248 /* EnumDeclaration */:
66830                     return true;
66831                 case 255 /* ImportClause */:
66832                     return node.isTypeOnly;
66833                 case 258 /* ImportSpecifier */:
66834                 case 263 /* ExportSpecifier */:
66835                     return node.parent.parent.isTypeOnly;
66836                 default:
66837                     return false;
66838             }
66839         }
66840         // True if the given identifier is part of a type reference
66841         function isTypeReferenceIdentifier(node) {
66842             while (node.parent.kind === 153 /* QualifiedName */) {
66843                 node = node.parent;
66844             }
66845             return node.parent.kind === 169 /* TypeReference */;
66846         }
66847         function isHeritageClauseElementIdentifier(node) {
66848             while (node.parent.kind === 194 /* PropertyAccessExpression */) {
66849                 node = node.parent;
66850             }
66851             return node.parent.kind === 216 /* ExpressionWithTypeArguments */;
66852         }
66853         function forEachEnclosingClass(node, callback) {
66854             var result;
66855             while (true) {
66856                 node = ts.getContainingClass(node);
66857                 if (!node)
66858                     break;
66859                 if (result = callback(node))
66860                     break;
66861             }
66862             return result;
66863         }
66864         function isNodeUsedDuringClassInitialization(node) {
66865             return !!ts.findAncestor(node, function (element) {
66866                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
66867                     return true;
66868                 }
66869                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
66870                     return "quit";
66871                 }
66872                 return false;
66873             });
66874         }
66875         function isNodeWithinClass(node, classDeclaration) {
66876             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
66877         }
66878         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
66879             while (nodeOnRightSide.parent.kind === 153 /* QualifiedName */) {
66880                 nodeOnRightSide = nodeOnRightSide.parent;
66881             }
66882             if (nodeOnRightSide.parent.kind === 253 /* ImportEqualsDeclaration */) {
66883                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66884             }
66885             if (nodeOnRightSide.parent.kind === 259 /* ExportAssignment */) {
66886                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
66887             }
66888             return undefined;
66889         }
66890         function isInRightSideOfImportOrExportAssignment(node) {
66891             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
66892         }
66893         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
66894             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
66895             switch (specialPropertyAssignmentKind) {
66896                 case 1 /* ExportsProperty */:
66897                 case 3 /* PrototypeProperty */:
66898                     return getSymbolOfNode(entityName.parent);
66899                 case 4 /* ThisProperty */:
66900                 case 2 /* ModuleExports */:
66901                 case 5 /* Property */:
66902                     return getSymbolOfNode(entityName.parent.parent);
66903             }
66904         }
66905         function isImportTypeQualifierPart(node) {
66906             var parent = node.parent;
66907             while (ts.isQualifiedName(parent)) {
66908                 node = parent;
66909                 parent = parent.parent;
66910             }
66911             if (parent && parent.kind === 188 /* ImportType */ && parent.qualifier === node) {
66912                 return parent;
66913             }
66914             return undefined;
66915         }
66916         function getSymbolOfNameOrPropertyAccessExpression(name) {
66917             if (ts.isDeclarationName(name)) {
66918                 return getSymbolOfNode(name.parent);
66919             }
66920             if (ts.isInJSFile(name) &&
66921                 name.parent.kind === 194 /* PropertyAccessExpression */ &&
66922                 name.parent === name.parent.parent.left) {
66923                 // Check if this is a special property assignment
66924                 if (!ts.isPrivateIdentifier(name)) {
66925                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
66926                     if (specialPropertyAssignmentSymbol) {
66927                         return specialPropertyAssignmentSymbol;
66928                     }
66929                 }
66930             }
66931             if (name.parent.kind === 259 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
66932                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
66933                 var success = resolveEntityName(name, 
66934                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
66935                 if (success && success !== unknownSymbol) {
66936                     return success;
66937                 }
66938             }
66939             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
66940                 // Since we already checked for ExportAssignment, this really could only be an Import
66941                 var importEqualsDeclaration = ts.getAncestor(name, 253 /* ImportEqualsDeclaration */);
66942                 ts.Debug.assert(importEqualsDeclaration !== undefined);
66943                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
66944             }
66945             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
66946                 var possibleImportNode = isImportTypeQualifierPart(name);
66947                 if (possibleImportNode) {
66948                     getTypeFromTypeNode(possibleImportNode);
66949                     var sym = getNodeLinks(name).resolvedSymbol;
66950                     return sym === unknownSymbol ? undefined : sym;
66951                 }
66952             }
66953             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
66954                 name = name.parent;
66955             }
66956             if (isHeritageClauseElementIdentifier(name)) {
66957                 var meaning = 0 /* None */;
66958                 // In an interface or class, we're definitely interested in a type.
66959                 if (name.parent.kind === 216 /* ExpressionWithTypeArguments */) {
66960                     meaning = 788968 /* Type */;
66961                     // In a class 'extends' clause we are also looking for a value.
66962                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
66963                         meaning |= 111551 /* Value */;
66964                     }
66965                 }
66966                 else {
66967                     meaning = 1920 /* Namespace */;
66968                 }
66969                 meaning |= 2097152 /* Alias */;
66970                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
66971                 if (entityNameSymbol) {
66972                     return entityNameSymbol;
66973                 }
66974             }
66975             if (name.parent.kind === 317 /* JSDocParameterTag */) {
66976                 return ts.getParameterSymbolFromJSDoc(name.parent);
66977             }
66978             if (name.parent.kind === 155 /* TypeParameter */ && name.parent.parent.kind === 321 /* JSDocTemplateTag */) {
66979                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
66980                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
66981                 return typeParameter && typeParameter.symbol;
66982             }
66983             if (ts.isExpressionNode(name)) {
66984                 if (ts.nodeIsMissing(name)) {
66985                     // Missing entity name.
66986                     return undefined;
66987                 }
66988                 if (name.kind === 75 /* Identifier */) {
66989                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
66990                         var symbol = getIntrinsicTagSymbol(name.parent);
66991                         return symbol === unknownSymbol ? undefined : symbol;
66992                     }
66993                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
66994                 }
66995                 else if (name.kind === 194 /* PropertyAccessExpression */ || name.kind === 153 /* QualifiedName */) {
66996                     var links = getNodeLinks(name);
66997                     if (links.resolvedSymbol) {
66998                         return links.resolvedSymbol;
66999                     }
67000                     if (name.kind === 194 /* PropertyAccessExpression */) {
67001                         checkPropertyAccessExpression(name);
67002                     }
67003                     else {
67004                         checkQualifiedName(name);
67005                     }
67006                     return links.resolvedSymbol;
67007                 }
67008             }
67009             else if (isTypeReferenceIdentifier(name)) {
67010                 var meaning = name.parent.kind === 169 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
67011                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
67012             }
67013             if (name.parent.kind === 168 /* TypePredicate */) {
67014                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
67015             }
67016             // Do we want to return undefined here?
67017             return undefined;
67018         }
67019         function getSymbolAtLocation(node, ignoreErrors) {
67020             if (node.kind === 290 /* SourceFile */) {
67021                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
67022             }
67023             var parent = node.parent;
67024             var grandParent = parent.parent;
67025             if (node.flags & 16777216 /* InWithStatement */) {
67026                 // We cannot answer semantic questions within a with block, do not proceed any further
67027                 return undefined;
67028             }
67029             if (isDeclarationNameOrImportPropertyName(node)) {
67030                 // This is a declaration, call getSymbolOfNode
67031                 var parentSymbol = getSymbolOfNode(parent);
67032                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
67033                     ? getImmediateAliasedSymbol(parentSymbol)
67034                     : parentSymbol;
67035             }
67036             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
67037                 return getSymbolOfNode(parent.parent);
67038             }
67039             if (node.kind === 75 /* Identifier */) {
67040                 if (isInRightSideOfImportOrExportAssignment(node)) {
67041                     return getSymbolOfNameOrPropertyAccessExpression(node);
67042                 }
67043                 else if (parent.kind === 191 /* BindingElement */ &&
67044                     grandParent.kind === 189 /* ObjectBindingPattern */ &&
67045                     node === parent.propertyName) {
67046                     var typeOfPattern = getTypeOfNode(grandParent);
67047                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
67048                     if (propertyDeclaration) {
67049                         return propertyDeclaration;
67050                     }
67051                 }
67052             }
67053             switch (node.kind) {
67054                 case 75 /* Identifier */:
67055                 case 76 /* PrivateIdentifier */:
67056                 case 194 /* PropertyAccessExpression */:
67057                 case 153 /* QualifiedName */:
67058                     return getSymbolOfNameOrPropertyAccessExpression(node);
67059                 case 104 /* ThisKeyword */:
67060                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
67061                     if (ts.isFunctionLike(container)) {
67062                         var sig = getSignatureFromDeclaration(container);
67063                         if (sig.thisParameter) {
67064                             return sig.thisParameter;
67065                         }
67066                     }
67067                     if (ts.isInExpressionContext(node)) {
67068                         return checkExpression(node).symbol;
67069                     }
67070                 // falls through
67071                 case 183 /* ThisType */:
67072                     return getTypeFromThisTypeNode(node).symbol;
67073                 case 102 /* SuperKeyword */:
67074                     return checkExpression(node).symbol;
67075                 case 129 /* ConstructorKeyword */:
67076                     // constructor keyword for an overload, should take us to the definition if it exist
67077                     var constructorDeclaration = node.parent;
67078                     if (constructorDeclaration && constructorDeclaration.kind === 162 /* Constructor */) {
67079                         return constructorDeclaration.parent.symbol;
67080                     }
67081                     return undefined;
67082                 case 10 /* StringLiteral */:
67083                 case 14 /* NoSubstitutionTemplateLiteral */:
67084                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
67085                     // 2). External module name in an import declaration
67086                     // 3). Dynamic import call or require in javascript
67087                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
67088                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
67089                         ((node.parent.kind === 254 /* ImportDeclaration */ || node.parent.kind === 260 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
67090                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
67091                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
67092                         return resolveExternalModuleName(node, node, ignoreErrors);
67093                     }
67094                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
67095                         return getSymbolOfNode(parent);
67096                     }
67097                 // falls through
67098                 case 8 /* NumericLiteral */:
67099                     // index access
67100                     var objectType = ts.isElementAccessExpression(parent)
67101                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
67102                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
67103                             ? getTypeFromTypeNode(grandParent.objectType)
67104                             : undefined;
67105                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
67106                 case 84 /* DefaultKeyword */:
67107                 case 94 /* FunctionKeyword */:
67108                 case 38 /* EqualsGreaterThanToken */:
67109                 case 80 /* ClassKeyword */:
67110                     return getSymbolOfNode(node.parent);
67111                 case 188 /* ImportType */:
67112                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
67113                 case 89 /* ExportKeyword */:
67114                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
67115                 default:
67116                     return undefined;
67117             }
67118         }
67119         function getShorthandAssignmentValueSymbol(location) {
67120             if (location && location.kind === 282 /* ShorthandPropertyAssignment */) {
67121                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
67122             }
67123             return undefined;
67124         }
67125         /** Returns the target of an export specifier without following aliases */
67126         function getExportSpecifierLocalTargetSymbol(node) {
67127             return node.parent.parent.moduleSpecifier ?
67128                 getExternalModuleMember(node.parent.parent, node) :
67129                 resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
67130         }
67131         function getTypeOfNode(node) {
67132             if (node.flags & 16777216 /* InWithStatement */) {
67133                 // We cannot answer semantic questions within a with block, do not proceed any further
67134                 return errorType;
67135             }
67136             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
67137             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
67138             if (ts.isPartOfTypeNode(node)) {
67139                 var typeFromTypeNode = getTypeFromTypeNode(node);
67140                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
67141             }
67142             if (ts.isExpressionNode(node)) {
67143                 return getRegularTypeOfExpression(node);
67144             }
67145             if (classType && !classDecl.isImplements) {
67146                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
67147                 // extends clause of a class. We handle that case here.
67148                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
67149                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
67150             }
67151             if (isTypeDeclaration(node)) {
67152                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67153                 var symbol = getSymbolOfNode(node);
67154                 return getDeclaredTypeOfSymbol(symbol);
67155             }
67156             if (isTypeDeclarationName(node)) {
67157                 var symbol = getSymbolAtLocation(node);
67158                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
67159             }
67160             if (ts.isDeclaration(node)) {
67161                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
67162                 var symbol = getSymbolOfNode(node);
67163                 return getTypeOfSymbol(symbol);
67164             }
67165             if (isDeclarationNameOrImportPropertyName(node)) {
67166                 var symbol = getSymbolAtLocation(node);
67167                 if (symbol) {
67168                     return getTypeOfSymbol(symbol);
67169                 }
67170                 return errorType;
67171             }
67172             if (ts.isBindingPattern(node)) {
67173                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
67174             }
67175             if (isInRightSideOfImportOrExportAssignment(node)) {
67176                 var symbol = getSymbolAtLocation(node);
67177                 if (symbol) {
67178                     var declaredType = getDeclaredTypeOfSymbol(symbol);
67179                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
67180                 }
67181             }
67182             return errorType;
67183         }
67184         // Gets the type of object literal or array literal of destructuring assignment.
67185         // { a } from
67186         //     for ( { a } of elems) {
67187         //     }
67188         // [ a ] from
67189         //     [a] = [ some array ...]
67190         function getTypeOfAssignmentPattern(expr) {
67191             ts.Debug.assert(expr.kind === 193 /* ObjectLiteralExpression */ || expr.kind === 192 /* ArrayLiteralExpression */);
67192             // If this is from "for of"
67193             //     for ( { a } of elems) {
67194             //     }
67195             if (expr.parent.kind === 232 /* ForOfStatement */) {
67196                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
67197                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67198             }
67199             // If this is from "for" initializer
67200             //     for ({a } = elems[0];.....) { }
67201             if (expr.parent.kind === 209 /* BinaryExpression */) {
67202                 var iteratedType = getTypeOfExpression(expr.parent.right);
67203                 return checkDestructuringAssignment(expr, iteratedType || errorType);
67204             }
67205             // If this is from nested object binding pattern
67206             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
67207             if (expr.parent.kind === 281 /* PropertyAssignment */) {
67208                 var node_4 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
67209                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_4) || errorType;
67210                 var propertyIndex = ts.indexOfNode(node_4.properties, expr.parent);
67211                 return checkObjectLiteralDestructuringPropertyAssignment(node_4, typeOfParentObjectLiteral, propertyIndex);
67212             }
67213             // Array literal assignment - array destructuring pattern
67214             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
67215             //    [{ property1: p1, property2 }] = elems;
67216             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
67217             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
67218             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
67219         }
67220         // Gets the property symbol corresponding to the property in destructuring assignment
67221         // 'property1' from
67222         //     for ( { property1: a } of elems) {
67223         //     }
67224         // 'property1' at location 'a' from:
67225         //     [a] = [ property1, property2 ]
67226         function getPropertySymbolOfDestructuringAssignment(location) {
67227             // Get the type of the object or array literal and then look for property of given name in the type
67228             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
67229             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
67230         }
67231         function getRegularTypeOfExpression(expr) {
67232             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
67233                 expr = expr.parent;
67234             }
67235             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
67236         }
67237         /**
67238          * Gets either the static or instance type of a class element, based on
67239          * whether the element is declared as "static".
67240          */
67241         function getParentTypeOfClassElement(node) {
67242             var classSymbol = getSymbolOfNode(node.parent);
67243             return ts.hasModifier(node, 32 /* Static */)
67244                 ? getTypeOfSymbol(classSymbol)
67245                 : getDeclaredTypeOfSymbol(classSymbol);
67246         }
67247         function getClassElementPropertyKeyType(element) {
67248             var name = element.name;
67249             switch (name.kind) {
67250                 case 75 /* Identifier */:
67251                     return getLiteralType(ts.idText(name));
67252                 case 8 /* NumericLiteral */:
67253                 case 10 /* StringLiteral */:
67254                     return getLiteralType(name.text);
67255                 case 154 /* ComputedPropertyName */:
67256                     var nameType = checkComputedPropertyName(name);
67257                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
67258                 default:
67259                     return ts.Debug.fail("Unsupported property name.");
67260             }
67261         }
67262         // Return the list of properties of the given type, augmented with properties from Function
67263         // if the type has call or construct signatures
67264         function getAugmentedPropertiesOfType(type) {
67265             type = getApparentType(type);
67266             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
67267             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
67268                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
67269                     undefined;
67270             if (functionType) {
67271                 ts.forEach(getPropertiesOfType(functionType), function (p) {
67272                     if (!propsByName.has(p.escapedName)) {
67273                         propsByName.set(p.escapedName, p);
67274                     }
67275                 });
67276             }
67277             return getNamedMembers(propsByName);
67278         }
67279         function typeHasCallOrConstructSignatures(type) {
67280             return ts.typeHasCallOrConstructSignatures(type, checker);
67281         }
67282         function getRootSymbols(symbol) {
67283             var roots = getImmediateRootSymbols(symbol);
67284             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
67285         }
67286         function getImmediateRootSymbols(symbol) {
67287             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
67288                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
67289             }
67290             else if (symbol.flags & 33554432 /* Transient */) {
67291                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
67292                 return leftSpread ? [leftSpread, rightSpread]
67293                     : syntheticOrigin ? [syntheticOrigin]
67294                         : ts.singleElementArray(tryGetAliasTarget(symbol));
67295             }
67296             return undefined;
67297         }
67298         function tryGetAliasTarget(symbol) {
67299             var target;
67300             var next = symbol;
67301             while (next = getSymbolLinks(next).target) {
67302                 target = next;
67303             }
67304             return target;
67305         }
67306         // Emitter support
67307         function isArgumentsLocalBinding(nodeIn) {
67308             if (!ts.isGeneratedIdentifier(nodeIn)) {
67309                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67310                 if (node) {
67311                     var isPropertyName_1 = node.parent.kind === 194 /* PropertyAccessExpression */ && node.parent.name === node;
67312                     return !isPropertyName_1 && getReferencedValueSymbol(node) === argumentsSymbol;
67313                 }
67314             }
67315             return false;
67316         }
67317         function moduleExportsSomeValue(moduleReferenceExpression) {
67318             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
67319             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
67320                 // If the module is not found or is shorthand, assume that it may export a value.
67321                 return true;
67322             }
67323             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
67324             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
67325             // otherwise it will return moduleSymbol itself
67326             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
67327             var symbolLinks = getSymbolLinks(moduleSymbol);
67328             if (symbolLinks.exportsSomeValue === undefined) {
67329                 // for export assignments - check if resolved symbol for RHS is itself a value
67330                 // otherwise - check if at least one export is value
67331                 symbolLinks.exportsSomeValue = hasExportAssignment
67332                     ? !!(moduleSymbol.flags & 111551 /* Value */)
67333                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
67334             }
67335             return symbolLinks.exportsSomeValue;
67336             function isValue(s) {
67337                 s = resolveSymbol(s);
67338                 return s && !!(s.flags & 111551 /* Value */);
67339             }
67340         }
67341         function isNameOfModuleOrEnumDeclaration(node) {
67342             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
67343         }
67344         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
67345         // node of the exported entity's container. Otherwise, return undefined.
67346         function getReferencedExportContainer(nodeIn, prefixLocals) {
67347             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67348             if (node) {
67349                 // When resolving the export container for the name of a module or enum
67350                 // declaration, we need to start resolution at the declaration's container.
67351                 // Otherwise, we could incorrectly resolve the export container as the
67352                 // declaration if it contains an exported member with the same name.
67353                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
67354                 if (symbol) {
67355                     if (symbol.flags & 1048576 /* ExportValue */) {
67356                         // If we reference an exported entity within the same module declaration, then whether
67357                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
67358                         // kinds that we do NOT prefix.
67359                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
67360                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
67361                             return undefined;
67362                         }
67363                         symbol = exportSymbol;
67364                     }
67365                     var parentSymbol_1 = getParentOfSymbol(symbol);
67366                     if (parentSymbol_1) {
67367                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 290 /* SourceFile */) {
67368                             var symbolFile = parentSymbol_1.valueDeclaration;
67369                             var referenceFile = ts.getSourceFileOfNode(node);
67370                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
67371                             var symbolIsUmdExport = symbolFile !== referenceFile;
67372                             return symbolIsUmdExport ? undefined : symbolFile;
67373                         }
67374                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
67375                     }
67376                 }
67377             }
67378         }
67379         // When resolved as an expression identifier, if the given node references an import, return the declaration of
67380         // that import. Otherwise, return undefined.
67381         function getReferencedImportDeclaration(nodeIn) {
67382             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67383             if (node) {
67384                 var symbol = getReferencedValueSymbol(node);
67385                 // We should only get the declaration of an alias if there isn't a local value
67386                 // declaration for the symbol
67387                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
67388                     return getDeclarationOfAliasSymbol(symbol);
67389                 }
67390             }
67391             return undefined;
67392         }
67393         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
67394             return ts.isBindingElement(symbol.valueDeclaration)
67395                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 280 /* CatchClause */;
67396         }
67397         function isSymbolOfDeclarationWithCollidingName(symbol) {
67398             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
67399                 var links = getSymbolLinks(symbol);
67400                 if (links.isDeclarationWithCollidingName === undefined) {
67401                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
67402                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
67403                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
67404                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
67405                             // redeclaration - always should be renamed
67406                             links.isDeclarationWithCollidingName = true;
67407                         }
67408                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
67409                             // binding is captured in the function
67410                             // should be renamed if:
67411                             // - binding is not top level - top level bindings never collide with anything
67412                             // AND
67413                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
67414                             //     let a, b
67415                             //     { let x = 1; a = () => x; }
67416                             //     { let x = 100; b = () => x; }
67417                             //     console.log(a()); // should print '1'
67418                             //     console.log(b()); // should print '100'
67419                             //     OR
67420                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
67421                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
67422                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
67423                             //       they will not collide with anything
67424                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
67425                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
67426                             var inLoopBodyBlock = container.kind === 223 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
67427                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
67428                         }
67429                         else {
67430                             links.isDeclarationWithCollidingName = false;
67431                         }
67432                     }
67433                 }
67434                 return links.isDeclarationWithCollidingName;
67435             }
67436             return false;
67437         }
67438         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
67439         // a name that either hides an existing name or might hide it when compiled downlevel,
67440         // return the declaration of that entity. Otherwise, return undefined.
67441         function getReferencedDeclarationWithCollidingName(nodeIn) {
67442             if (!ts.isGeneratedIdentifier(nodeIn)) {
67443                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
67444                 if (node) {
67445                     var symbol = getReferencedValueSymbol(node);
67446                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
67447                         return symbol.valueDeclaration;
67448                     }
67449                 }
67450             }
67451             return undefined;
67452         }
67453         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
67454         // existing name or might hide a name when compiled downlevel
67455         function isDeclarationWithCollidingName(nodeIn) {
67456             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67457             if (node) {
67458                 var symbol = getSymbolOfNode(node);
67459                 if (symbol) {
67460                     return isSymbolOfDeclarationWithCollidingName(symbol);
67461                 }
67462             }
67463             return false;
67464         }
67465         function isValueAliasDeclaration(node) {
67466             switch (node.kind) {
67467                 case 253 /* ImportEqualsDeclaration */:
67468                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
67469                 case 255 /* ImportClause */:
67470                 case 256 /* NamespaceImport */:
67471                 case 258 /* ImportSpecifier */:
67472                 case 263 /* ExportSpecifier */:
67473                     var symbol = getSymbolOfNode(node) || unknownSymbol;
67474                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
67475                 case 260 /* ExportDeclaration */:
67476                     var exportClause = node.exportClause;
67477                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
67478                         ts.some(exportClause.elements, isValueAliasDeclaration));
67479                 case 259 /* ExportAssignment */:
67480                     return node.expression && node.expression.kind === 75 /* Identifier */ ?
67481                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
67482                         true;
67483             }
67484             return false;
67485         }
67486         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
67487             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
67488             if (node === undefined || node.parent.kind !== 290 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
67489                 // parent is not source file or it is not reference to internal module
67490                 return false;
67491             }
67492             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
67493             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
67494         }
67495         function isAliasResolvedToValue(symbol) {
67496             var target = resolveAlias(symbol);
67497             if (target === unknownSymbol) {
67498                 return true;
67499             }
67500             // const enums and modules that contain only const enums are not considered values from the emit perspective
67501             // unless 'preserveConstEnums' option is set to true
67502             return !!(target.flags & 111551 /* Value */) &&
67503                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
67504         }
67505         function isConstEnumOrConstEnumOnlyModule(s) {
67506             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
67507         }
67508         function isReferencedAliasDeclaration(node, checkChildren) {
67509             if (isAliasSymbolDeclaration(node)) {
67510                 var symbol = getSymbolOfNode(node);
67511                 if (symbol && getSymbolLinks(symbol).referenced) {
67512                     return true;
67513                 }
67514                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
67515                 if (target && ts.getModifierFlags(node) & 1 /* Export */ &&
67516                     target.flags & 111551 /* Value */ &&
67517                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
67518                     // An `export import ... =` of a value symbol is always considered referenced
67519                     return true;
67520                 }
67521             }
67522             if (checkChildren) {
67523                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
67524             }
67525             return false;
67526         }
67527         function isImplementationOfOverload(node) {
67528             if (ts.nodeIsPresent(node.body)) {
67529                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
67530                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
67531                 var symbol = getSymbolOfNode(node);
67532                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
67533                 // If this function body corresponds to function with multiple signature, it is implementation of overload
67534                 // e.g.: function foo(a: string): string;
67535                 //       function foo(a: number): number;
67536                 //       function foo(a: any) { // This is implementation of the overloads
67537                 //           return a;
67538                 //       }
67539                 return signaturesOfSymbol.length > 1 ||
67540                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
67541                     // e.g.: function foo(a: string): string;
67542                     //       function foo(a: any) { // This is implementation of the overloads
67543                     //           return a;
67544                     //       }
67545                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
67546             }
67547             return false;
67548         }
67549         function isRequiredInitializedParameter(parameter) {
67550             return !!strictNullChecks &&
67551                 !isOptionalParameter(parameter) &&
67552                 !ts.isJSDocParameterTag(parameter) &&
67553                 !!parameter.initializer &&
67554                 !ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67555         }
67556         function isOptionalUninitializedParameterProperty(parameter) {
67557             return strictNullChecks &&
67558                 isOptionalParameter(parameter) &&
67559                 !parameter.initializer &&
67560                 ts.hasModifier(parameter, 92 /* ParameterPropertyModifier */);
67561         }
67562         function isExpandoFunctionDeclaration(node) {
67563             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67564             if (!declaration) {
67565                 return false;
67566             }
67567             var symbol = getSymbolOfNode(declaration);
67568             if (!symbol || !(symbol.flags & 16 /* Function */)) {
67569                 return false;
67570             }
67571             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
67572         }
67573         function getPropertiesOfContainerFunction(node) {
67574             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
67575             if (!declaration) {
67576                 return ts.emptyArray;
67577             }
67578             var symbol = getSymbolOfNode(declaration);
67579             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
67580         }
67581         function getNodeCheckFlags(node) {
67582             return getNodeLinks(node).flags || 0;
67583         }
67584         function getEnumMemberValue(node) {
67585             computeEnumMemberValues(node.parent);
67586             return getNodeLinks(node).enumMemberValue;
67587         }
67588         function canHaveConstantValue(node) {
67589             switch (node.kind) {
67590                 case 284 /* EnumMember */:
67591                 case 194 /* PropertyAccessExpression */:
67592                 case 195 /* ElementAccessExpression */:
67593                     return true;
67594             }
67595             return false;
67596         }
67597         function getConstantValue(node) {
67598             if (node.kind === 284 /* EnumMember */) {
67599                 return getEnumMemberValue(node);
67600             }
67601             var symbol = getNodeLinks(node).resolvedSymbol;
67602             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
67603                 // inline property\index accesses only for const enums
67604                 var member = symbol.valueDeclaration;
67605                 if (ts.isEnumConst(member.parent)) {
67606                     return getEnumMemberValue(member);
67607                 }
67608             }
67609             return undefined;
67610         }
67611         function isFunctionType(type) {
67612             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
67613         }
67614         function getTypeReferenceSerializationKind(typeNameIn, location) {
67615             // ensure both `typeName` and `location` are parse tree nodes.
67616             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
67617             if (!typeName)
67618                 return ts.TypeReferenceSerializationKind.Unknown;
67619             if (location) {
67620                 location = ts.getParseTreeNode(location);
67621                 if (!location)
67622                     return ts.TypeReferenceSerializationKind.Unknown;
67623             }
67624             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
67625             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67626             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
67627             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
67628             if (valueSymbol && valueSymbol === typeSymbol) {
67629                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
67630                 if (globalPromiseSymbol && valueSymbol === globalPromiseSymbol) {
67631                     return ts.TypeReferenceSerializationKind.Promise;
67632                 }
67633                 var constructorType = getTypeOfSymbol(valueSymbol);
67634                 if (constructorType && isConstructorType(constructorType)) {
67635                     return ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
67636                 }
67637             }
67638             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
67639             if (!typeSymbol) {
67640                 return ts.TypeReferenceSerializationKind.Unknown;
67641             }
67642             var type = getDeclaredTypeOfSymbol(typeSymbol);
67643             if (type === errorType) {
67644                 return ts.TypeReferenceSerializationKind.Unknown;
67645             }
67646             else if (type.flags & 3 /* AnyOrUnknown */) {
67647                 return ts.TypeReferenceSerializationKind.ObjectType;
67648             }
67649             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
67650                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
67651             }
67652             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
67653                 return ts.TypeReferenceSerializationKind.BooleanType;
67654             }
67655             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
67656                 return ts.TypeReferenceSerializationKind.NumberLikeType;
67657             }
67658             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
67659                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
67660             }
67661             else if (isTypeAssignableToKind(type, 132 /* StringLike */)) {
67662                 return ts.TypeReferenceSerializationKind.StringLikeType;
67663             }
67664             else if (isTupleType(type)) {
67665                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67666             }
67667             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
67668                 return ts.TypeReferenceSerializationKind.ESSymbolType;
67669             }
67670             else if (isFunctionType(type)) {
67671                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
67672             }
67673             else if (isArrayType(type)) {
67674                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
67675             }
67676             else {
67677                 return ts.TypeReferenceSerializationKind.ObjectType;
67678             }
67679         }
67680         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
67681             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
67682             if (!declaration) {
67683                 return ts.createToken(125 /* AnyKeyword */);
67684             }
67685             // Get type of the symbol if this is the valid symbol otherwise get type at location
67686             var symbol = getSymbolOfNode(declaration);
67687             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
67688                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
67689                 : errorType;
67690             if (type.flags & 8192 /* UniqueESSymbol */ &&
67691                 type.symbol === symbol) {
67692                 flags |= 1048576 /* AllowUniqueESSymbolType */;
67693             }
67694             if (addUndefined) {
67695                 type = getOptionalType(type);
67696             }
67697             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67698         }
67699         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
67700             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
67701             if (!signatureDeclaration) {
67702                 return ts.createToken(125 /* AnyKeyword */);
67703             }
67704             var signature = getSignatureFromDeclaration(signatureDeclaration);
67705             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67706         }
67707         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
67708             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
67709             if (!expr) {
67710                 return ts.createToken(125 /* AnyKeyword */);
67711             }
67712             var type = getWidenedType(getRegularTypeOfExpression(expr));
67713             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
67714         }
67715         function hasGlobalName(name) {
67716             return globals.has(ts.escapeLeadingUnderscores(name));
67717         }
67718         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
67719             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
67720             if (resolvedSymbol) {
67721                 return resolvedSymbol;
67722             }
67723             var location = reference;
67724             if (startInDeclarationContainer) {
67725                 // When resolving the name of a declaration as a value, we need to start resolution
67726                 // at a point outside of the declaration.
67727                 var parent = reference.parent;
67728                 if (ts.isDeclaration(parent) && reference === parent.name) {
67729                     location = getDeclarationContainer(parent);
67730                 }
67731             }
67732             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
67733         }
67734         function getReferencedValueDeclaration(referenceIn) {
67735             if (!ts.isGeneratedIdentifier(referenceIn)) {
67736                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
67737                 if (reference) {
67738                     var symbol = getReferencedValueSymbol(reference);
67739                     if (symbol) {
67740                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
67741                     }
67742                 }
67743             }
67744             return undefined;
67745         }
67746         function isLiteralConstDeclaration(node) {
67747             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
67748                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
67749             }
67750             return false;
67751         }
67752         function literalTypeToNode(type, enclosing, tracker) {
67753             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
67754                 : type === trueType ? ts.createTrue() : type === falseType && ts.createFalse();
67755             return enumResult || ts.createLiteral(type.value);
67756         }
67757         function createLiteralConstValue(node, tracker) {
67758             var type = getTypeOfSymbol(getSymbolOfNode(node));
67759             return literalTypeToNode(type, node, tracker);
67760         }
67761         function getJsxFactoryEntity(location) {
67762             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
67763         }
67764         function createResolver() {
67765             // this variable and functions that use it are deliberately moved here from the outer scope
67766             // to avoid scope pollution
67767             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
67768             var fileToDirective;
67769             if (resolvedTypeReferenceDirectives) {
67770                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
67771                 fileToDirective = ts.createMap();
67772                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
67773                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
67774                         return;
67775                     }
67776                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
67777                     if (file) {
67778                         // Add the transitive closure of path references loaded by this file (as long as they are not)
67779                         // part of an existing type reference.
67780                         addReferencedFilesToTypeDirective(file, key);
67781                     }
67782                 });
67783             }
67784             return {
67785                 getReferencedExportContainer: getReferencedExportContainer,
67786                 getReferencedImportDeclaration: getReferencedImportDeclaration,
67787                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
67788                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
67789                 isValueAliasDeclaration: function (node) {
67790                     node = ts.getParseTreeNode(node);
67791                     // Synthesized nodes are always treated like values.
67792                     return node ? isValueAliasDeclaration(node) : true;
67793                 },
67794                 hasGlobalName: hasGlobalName,
67795                 isReferencedAliasDeclaration: function (node, checkChildren) {
67796                     node = ts.getParseTreeNode(node);
67797                     // Synthesized nodes are always treated as referenced.
67798                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
67799                 },
67800                 getNodeCheckFlags: function (node) {
67801                     node = ts.getParseTreeNode(node);
67802                     return node ? getNodeCheckFlags(node) : 0;
67803                 },
67804                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
67805                 isDeclarationVisible: isDeclarationVisible,
67806                 isImplementationOfOverload: isImplementationOfOverload,
67807                 isRequiredInitializedParameter: isRequiredInitializedParameter,
67808                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
67809                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
67810                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
67811                 createTypeOfDeclaration: createTypeOfDeclaration,
67812                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
67813                 createTypeOfExpression: createTypeOfExpression,
67814                 createLiteralConstValue: createLiteralConstValue,
67815                 isSymbolAccessible: isSymbolAccessible,
67816                 isEntityNameVisible: isEntityNameVisible,
67817                 getConstantValue: function (nodeIn) {
67818                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
67819                     return node ? getConstantValue(node) : undefined;
67820                 },
67821                 collectLinkedAliases: collectLinkedAliases,
67822                 getReferencedValueDeclaration: getReferencedValueDeclaration,
67823                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
67824                 isOptionalParameter: isOptionalParameter,
67825                 moduleExportsSomeValue: moduleExportsSomeValue,
67826                 isArgumentsLocalBinding: isArgumentsLocalBinding,
67827                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
67828                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
67829                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
67830                 isLiteralConstDeclaration: isLiteralConstDeclaration,
67831                 isLateBound: function (nodeIn) {
67832                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
67833                     var symbol = node && getSymbolOfNode(node);
67834                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
67835                 },
67836                 getJsxFactoryEntity: getJsxFactoryEntity,
67837                 getAllAccessorDeclarations: function (accessor) {
67838                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
67839                     var otherKind = accessor.kind === 164 /* SetAccessor */ ? 163 /* GetAccessor */ : 164 /* SetAccessor */;
67840                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
67841                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
67842                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
67843                     var setAccessor = accessor.kind === 164 /* SetAccessor */ ? accessor : otherAccessor;
67844                     var getAccessor = accessor.kind === 163 /* GetAccessor */ ? accessor : otherAccessor;
67845                     return {
67846                         firstAccessor: firstAccessor,
67847                         secondAccessor: secondAccessor,
67848                         setAccessor: setAccessor,
67849                         getAccessor: getAccessor
67850                     };
67851                 },
67852                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
67853                 isBindingCapturedByNode: function (node, decl) {
67854                     var parseNode = ts.getParseTreeNode(node);
67855                     var parseDecl = ts.getParseTreeNode(decl);
67856                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
67857                 },
67858                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
67859                     var n = ts.getParseTreeNode(node);
67860                     ts.Debug.assert(n && n.kind === 290 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
67861                     var sym = getSymbolOfNode(node);
67862                     if (!sym) {
67863                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
67864                     }
67865                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
67866                 },
67867                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
67868             };
67869             function isImportRequiredByAugmentation(node) {
67870                 var file = ts.getSourceFileOfNode(node);
67871                 if (!file.symbol)
67872                     return false;
67873                 var importTarget = getExternalModuleFileFromDeclaration(node);
67874                 if (!importTarget)
67875                     return false;
67876                 if (importTarget === file)
67877                     return false;
67878                 var exports = getExportsOfModule(file.symbol);
67879                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
67880                     var s = _a[_i];
67881                     if (s.mergeId) {
67882                         var merged = getMergedSymbol(s);
67883                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
67884                             var d = _c[_b];
67885                             var declFile = ts.getSourceFileOfNode(d);
67886                             if (declFile === importTarget) {
67887                                 return true;
67888                             }
67889                         }
67890                     }
67891                 }
67892                 return false;
67893             }
67894             function isInHeritageClause(node) {
67895                 return node.parent && node.parent.kind === 216 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 279 /* HeritageClause */;
67896             }
67897             // defined here to avoid outer scope pollution
67898             function getTypeReferenceDirectivesForEntityName(node) {
67899                 // program does not have any files with type reference directives - bail out
67900                 if (!fileToDirective) {
67901                     return undefined;
67902                 }
67903                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
67904                 // qualified names can only be used as types\namespaces
67905                 // identifiers are treated as values only if they appear in type queries
67906                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
67907                 if ((node.kind === 75 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 194 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
67908                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
67909                 }
67910                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
67911                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
67912             }
67913             // defined here to avoid outer scope pollution
67914             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
67915                 // program does not have any files with type reference directives - bail out
67916                 if (!fileToDirective) {
67917                     return undefined;
67918                 }
67919                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
67920                     return undefined;
67921                 }
67922                 // check what declarations in the symbol can contribute to the target meaning
67923                 var typeReferenceDirectives;
67924                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67925                     var decl = _a[_i];
67926                     // check meaning of the local symbol to see if declaration needs to be analyzed further
67927                     if (decl.symbol && decl.symbol.flags & meaning) {
67928                         var file = ts.getSourceFileOfNode(decl);
67929                         var typeReferenceDirective = fileToDirective.get(file.path);
67930                         if (typeReferenceDirective) {
67931                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
67932                         }
67933                         else {
67934                             // found at least one entry that does not originate from type reference directive
67935                             return undefined;
67936                         }
67937                     }
67938                 }
67939                 return typeReferenceDirectives;
67940             }
67941             function isSymbolFromTypeDeclarationFile(symbol) {
67942                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
67943                 if (!symbol.declarations) {
67944                     return false;
67945                 }
67946                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
67947                 // external modules cannot define or contribute to type declaration files
67948                 var current = symbol;
67949                 while (true) {
67950                     var parent = getParentOfSymbol(current);
67951                     if (parent) {
67952                         current = parent;
67953                     }
67954                     else {
67955                         break;
67956                     }
67957                 }
67958                 if (current.valueDeclaration && current.valueDeclaration.kind === 290 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
67959                     return false;
67960                 }
67961                 // check that at least one declaration of top level symbol originates from type declaration file
67962                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
67963                     var decl = _a[_i];
67964                     var file = ts.getSourceFileOfNode(decl);
67965                     if (fileToDirective.has(file.path)) {
67966                         return true;
67967                     }
67968                 }
67969                 return false;
67970             }
67971             function addReferencedFilesToTypeDirective(file, key) {
67972                 if (fileToDirective.has(file.path))
67973                     return;
67974                 fileToDirective.set(file.path, key);
67975                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
67976                     var fileName = _a[_i].fileName;
67977                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.originalFileName);
67978                     var referencedFile = host.getSourceFile(resolvedFile);
67979                     if (referencedFile) {
67980                         addReferencedFilesToTypeDirective(referencedFile, key);
67981                     }
67982                 }
67983             }
67984         }
67985         function getExternalModuleFileFromDeclaration(declaration) {
67986             var specifier = declaration.kind === 249 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
67987             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
67988             if (!moduleSymbol) {
67989                 return undefined;
67990             }
67991             return ts.getDeclarationOfKind(moduleSymbol, 290 /* SourceFile */);
67992         }
67993         function initializeTypeChecker() {
67994             // Bind all source files and propagate errors
67995             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
67996                 var file = _a[_i];
67997                 ts.bindSourceFile(file, compilerOptions);
67998             }
67999             amalgamatedDuplicates = ts.createMap();
68000             // Initialize global symbol table
68001             var augmentations;
68002             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
68003                 var file = _c[_b];
68004                 if (file.redirectInfo) {
68005                     continue;
68006                 }
68007                 if (!ts.isExternalOrCommonJsModule(file)) {
68008                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
68009                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
68010                     var fileGlobalThisSymbol = file.locals.get("globalThis");
68011                     if (fileGlobalThisSymbol) {
68012                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
68013                             var declaration = _e[_d];
68014                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
68015                         }
68016                     }
68017                     mergeSymbolTable(globals, file.locals);
68018                 }
68019                 if (file.jsGlobalAugmentations) {
68020                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
68021                 }
68022                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
68023                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
68024                 }
68025                 if (file.moduleAugmentations.length) {
68026                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
68027                 }
68028                 if (file.symbol && file.symbol.globalExports) {
68029                     // Merge in UMD exports with first-in-wins semantics (see #9771)
68030                     var source = file.symbol.globalExports;
68031                     source.forEach(function (sourceSymbol, id) {
68032                         if (!globals.has(id)) {
68033                             globals.set(id, sourceSymbol);
68034                         }
68035                     });
68036                 }
68037             }
68038             // We do global augmentations separately from module augmentations (and before creating global types) because they
68039             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
68040             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
68041             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
68042             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
68043             //       did module augmentations prior to finalizing the global types.
68044             if (augmentations) {
68045                 // merge _global_ module augmentations.
68046                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68047                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
68048                     var list = augmentations_1[_f];
68049                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
68050                         var augmentation = list_1[_g];
68051                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
68052                             continue;
68053                         mergeModuleAugmentation(augmentation);
68054                     }
68055                 }
68056             }
68057             // Setup global builtins
68058             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
68059             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
68060             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
68061             getSymbolLinks(unknownSymbol).type = errorType;
68062             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
68063             // Initialize special types
68064             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
68065             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
68066             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
68067             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68068             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
68069             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
68070             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
68071             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
68072             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
68073             anyArrayType = createArrayType(anyType);
68074             autoArrayType = createArrayType(autoType);
68075             if (autoArrayType === emptyObjectType) {
68076                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
68077                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
68078             }
68079             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
68080             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
68081             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
68082             if (augmentations) {
68083                 // merge _nonglobal_ module augmentations.
68084                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
68085                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
68086                     var list = augmentations_2[_h];
68087                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
68088                         var augmentation = list_2[_j];
68089                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
68090                             continue;
68091                         mergeModuleAugmentation(augmentation);
68092                     }
68093                 }
68094             }
68095             amalgamatedDuplicates.forEach(function (_a) {
68096                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
68097                 // If not many things conflict, issue individual errors
68098                 if (conflictingSymbols.size < 8) {
68099                     conflictingSymbols.forEach(function (_a, symbolName) {
68100                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
68101                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
68102                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
68103                             var node = firstFileLocations_1[_i];
68104                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
68105                         }
68106                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
68107                             var node = secondFileLocations_1[_b];
68108                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
68109                         }
68110                     });
68111                 }
68112                 else {
68113                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
68114                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
68115                     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)));
68116                     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)));
68117                 }
68118             });
68119             amalgamatedDuplicates = undefined;
68120         }
68121         function checkExternalEmitHelpers(location, helpers) {
68122             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
68123                 var sourceFile = ts.getSourceFileOfNode(location);
68124                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
68125                     var helpersModule = resolveHelpersModule(sourceFile, location);
68126                     if (helpersModule !== unknownSymbol) {
68127                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
68128                         for (var helper = 1 /* FirstEmitHelper */; helper <= 1048576 /* LastEmitHelper */; helper <<= 1) {
68129                             if (uncheckedHelpers & helper) {
68130                                 var name = getHelperName(helper);
68131                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
68132                                 if (!symbol) {
68133                                     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);
68134                                 }
68135                             }
68136                         }
68137                     }
68138                     requestedExternalEmitHelpers |= helpers;
68139                 }
68140             }
68141         }
68142         function getHelperName(helper) {
68143             switch (helper) {
68144                 case 1 /* Extends */: return "__extends";
68145                 case 2 /* Assign */: return "__assign";
68146                 case 4 /* Rest */: return "__rest";
68147                 case 8 /* Decorate */: return "__decorate";
68148                 case 16 /* Metadata */: return "__metadata";
68149                 case 32 /* Param */: return "__param";
68150                 case 64 /* Awaiter */: return "__awaiter";
68151                 case 128 /* Generator */: return "__generator";
68152                 case 256 /* Values */: return "__values";
68153                 case 512 /* Read */: return "__read";
68154                 case 1024 /* Spread */: return "__spread";
68155                 case 2048 /* SpreadArrays */: return "__spreadArrays";
68156                 case 4096 /* Await */: return "__await";
68157                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
68158                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
68159                 case 32768 /* AsyncValues */: return "__asyncValues";
68160                 case 65536 /* ExportStar */: return "__exportStar";
68161                 case 131072 /* MakeTemplateObject */: return "__makeTemplateObject";
68162                 case 262144 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
68163                 case 524288 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
68164                 case 1048576 /* CreateBinding */: return "__createBinding";
68165                 default: return ts.Debug.fail("Unrecognized helper");
68166             }
68167         }
68168         function resolveHelpersModule(node, errorNode) {
68169             if (!externalHelpersModule) {
68170                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
68171             }
68172             return externalHelpersModule;
68173         }
68174         // GRAMMAR CHECKING
68175         function checkGrammarDecoratorsAndModifiers(node) {
68176             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
68177         }
68178         function checkGrammarDecorators(node) {
68179             if (!node.decorators) {
68180                 return false;
68181             }
68182             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
68183                 if (node.kind === 161 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
68184                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
68185                 }
68186                 else {
68187                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
68188                 }
68189             }
68190             else if (node.kind === 163 /* GetAccessor */ || node.kind === 164 /* SetAccessor */) {
68191                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
68192                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
68193                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
68194                 }
68195             }
68196             return false;
68197         }
68198         function checkGrammarModifiers(node) {
68199             var quickResult = reportObviousModifierErrors(node);
68200             if (quickResult !== undefined) {
68201                 return quickResult;
68202             }
68203             var lastStatic, lastDeclare, lastAsync, lastReadonly;
68204             var flags = 0 /* None */;
68205             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
68206                 var modifier = _a[_i];
68207                 if (modifier.kind !== 138 /* ReadonlyKeyword */) {
68208                     if (node.kind === 158 /* PropertySignature */ || node.kind === 160 /* MethodSignature */) {
68209                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
68210                     }
68211                     if (node.kind === 167 /* IndexSignature */) {
68212                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
68213                     }
68214                 }
68215                 switch (modifier.kind) {
68216                     case 81 /* ConstKeyword */:
68217                         if (node.kind !== 248 /* EnumDeclaration */) {
68218                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(81 /* ConstKeyword */));
68219                         }
68220                         break;
68221                     case 119 /* PublicKeyword */:
68222                     case 118 /* ProtectedKeyword */:
68223                     case 117 /* PrivateKeyword */:
68224                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
68225                         if (flags & 28 /* AccessibilityModifier */) {
68226                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
68227                         }
68228                         else if (flags & 32 /* Static */) {
68229                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
68230                         }
68231                         else if (flags & 64 /* Readonly */) {
68232                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
68233                         }
68234                         else if (flags & 256 /* Async */) {
68235                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
68236                         }
68237                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68238                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
68239                         }
68240                         else if (flags & 128 /* Abstract */) {
68241                             if (modifier.kind === 117 /* PrivateKeyword */) {
68242                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
68243                             }
68244                             else {
68245                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
68246                             }
68247                         }
68248                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68249                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
68250                         }
68251                         flags |= ts.modifierToFlag(modifier.kind);
68252                         break;
68253                     case 120 /* StaticKeyword */:
68254                         if (flags & 32 /* Static */) {
68255                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
68256                         }
68257                         else if (flags & 64 /* Readonly */) {
68258                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
68259                         }
68260                         else if (flags & 256 /* Async */) {
68261                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
68262                         }
68263                         else if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68264                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
68265                         }
68266                         else if (node.kind === 156 /* Parameter */) {
68267                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
68268                         }
68269                         else if (flags & 128 /* Abstract */) {
68270                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68271                         }
68272                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68273                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
68274                         }
68275                         flags |= 32 /* Static */;
68276                         lastStatic = modifier;
68277                         break;
68278                     case 138 /* ReadonlyKeyword */:
68279                         if (flags & 64 /* Readonly */) {
68280                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
68281                         }
68282                         else if (node.kind !== 159 /* PropertyDeclaration */ && node.kind !== 158 /* PropertySignature */ && node.kind !== 167 /* IndexSignature */ && node.kind !== 156 /* Parameter */) {
68283                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
68284                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
68285                         }
68286                         flags |= 64 /* Readonly */;
68287                         lastReadonly = modifier;
68288                         break;
68289                     case 89 /* ExportKeyword */:
68290                         if (flags & 1 /* Export */) {
68291                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
68292                         }
68293                         else if (flags & 2 /* Ambient */) {
68294                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
68295                         }
68296                         else if (flags & 128 /* Abstract */) {
68297                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
68298                         }
68299                         else if (flags & 256 /* Async */) {
68300                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
68301                         }
68302                         else if (ts.isClassLike(node.parent)) {
68303                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "export");
68304                         }
68305                         else if (node.kind === 156 /* Parameter */) {
68306                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
68307                         }
68308                         flags |= 1 /* Export */;
68309                         break;
68310                     case 84 /* DefaultKeyword */:
68311                         var container = node.parent.kind === 290 /* SourceFile */ ? node.parent : node.parent.parent;
68312                         if (container.kind === 249 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
68313                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
68314                         }
68315                         flags |= 512 /* Default */;
68316                         break;
68317                     case 130 /* DeclareKeyword */:
68318                         if (flags & 2 /* Ambient */) {
68319                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
68320                         }
68321                         else if (flags & 256 /* Async */) {
68322                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68323                         }
68324                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
68325                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_class_element, "declare");
68326                         }
68327                         else if (node.kind === 156 /* Parameter */) {
68328                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
68329                         }
68330                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 250 /* ModuleBlock */) {
68331                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
68332                         }
68333                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
68334                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
68335                         }
68336                         flags |= 2 /* Ambient */;
68337                         lastDeclare = modifier;
68338                         break;
68339                     case 122 /* AbstractKeyword */:
68340                         if (flags & 128 /* Abstract */) {
68341                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
68342                         }
68343                         if (node.kind !== 245 /* ClassDeclaration */) {
68344                             if (node.kind !== 161 /* MethodDeclaration */ &&
68345                                 node.kind !== 159 /* PropertyDeclaration */ &&
68346                                 node.kind !== 163 /* GetAccessor */ &&
68347                                 node.kind !== 164 /* SetAccessor */) {
68348                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
68349                             }
68350                             if (!(node.parent.kind === 245 /* ClassDeclaration */ && ts.hasModifier(node.parent, 128 /* Abstract */))) {
68351                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
68352                             }
68353                             if (flags & 32 /* Static */) {
68354                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
68355                             }
68356                             if (flags & 8 /* Private */) {
68357                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
68358                             }
68359                         }
68360                         if (ts.isNamedDeclaration(node) && node.name.kind === 76 /* PrivateIdentifier */) {
68361                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
68362                         }
68363                         flags |= 128 /* Abstract */;
68364                         break;
68365                     case 126 /* AsyncKeyword */:
68366                         if (flags & 256 /* Async */) {
68367                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
68368                         }
68369                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
68370                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
68371                         }
68372                         else if (node.kind === 156 /* Parameter */) {
68373                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
68374                         }
68375                         flags |= 256 /* Async */;
68376                         lastAsync = modifier;
68377                         break;
68378                 }
68379             }
68380             if (node.kind === 162 /* Constructor */) {
68381                 if (flags & 32 /* Static */) {
68382                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
68383                 }
68384                 if (flags & 128 /* Abstract */) {
68385                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
68386                 }
68387                 else if (flags & 256 /* Async */) {
68388                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
68389                 }
68390                 else if (flags & 64 /* Readonly */) {
68391                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
68392                 }
68393                 return false;
68394             }
68395             else if ((node.kind === 254 /* ImportDeclaration */ || node.kind === 253 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
68396                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
68397             }
68398             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
68399                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
68400             }
68401             else if (node.kind === 156 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
68402                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
68403             }
68404             if (flags & 256 /* Async */) {
68405                 return checkGrammarAsyncModifier(node, lastAsync);
68406             }
68407             return false;
68408         }
68409         /**
68410          * true | false: Early return this value from checkGrammarModifiers.
68411          * undefined: Need to do full checking on the modifiers.
68412          */
68413         function reportObviousModifierErrors(node) {
68414             return !node.modifiers
68415                 ? false
68416                 : shouldReportBadModifier(node)
68417                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
68418                     : undefined;
68419         }
68420         function shouldReportBadModifier(node) {
68421             switch (node.kind) {
68422                 case 163 /* GetAccessor */:
68423                 case 164 /* SetAccessor */:
68424                 case 162 /* Constructor */:
68425                 case 159 /* PropertyDeclaration */:
68426                 case 158 /* PropertySignature */:
68427                 case 161 /* MethodDeclaration */:
68428                 case 160 /* MethodSignature */:
68429                 case 167 /* IndexSignature */:
68430                 case 249 /* ModuleDeclaration */:
68431                 case 254 /* ImportDeclaration */:
68432                 case 253 /* ImportEqualsDeclaration */:
68433                 case 260 /* ExportDeclaration */:
68434                 case 259 /* ExportAssignment */:
68435                 case 201 /* FunctionExpression */:
68436                 case 202 /* ArrowFunction */:
68437                 case 156 /* Parameter */:
68438                     return false;
68439                 default:
68440                     if (node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
68441                         return false;
68442                     }
68443                     switch (node.kind) {
68444                         case 244 /* FunctionDeclaration */:
68445                             return nodeHasAnyModifiersExcept(node, 126 /* AsyncKeyword */);
68446                         case 245 /* ClassDeclaration */:
68447                             return nodeHasAnyModifiersExcept(node, 122 /* AbstractKeyword */);
68448                         case 246 /* InterfaceDeclaration */:
68449                         case 225 /* VariableStatement */:
68450                         case 247 /* TypeAliasDeclaration */:
68451                             return true;
68452                         case 248 /* EnumDeclaration */:
68453                             return nodeHasAnyModifiersExcept(node, 81 /* ConstKeyword */);
68454                         default:
68455                             ts.Debug.fail();
68456                             return false;
68457                     }
68458             }
68459         }
68460         function nodeHasAnyModifiersExcept(node, allowedModifier) {
68461             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
68462         }
68463         function checkGrammarAsyncModifier(node, asyncModifier) {
68464             switch (node.kind) {
68465                 case 161 /* MethodDeclaration */:
68466                 case 244 /* FunctionDeclaration */:
68467                 case 201 /* FunctionExpression */:
68468                 case 202 /* ArrowFunction */:
68469                     return false;
68470             }
68471             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
68472         }
68473         function checkGrammarForDisallowedTrailingComma(list, diag) {
68474             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
68475             if (list && list.hasTrailingComma) {
68476                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
68477             }
68478             return false;
68479         }
68480         function checkGrammarTypeParameterList(typeParameters, file) {
68481             if (typeParameters && typeParameters.length === 0) {
68482                 var start = typeParameters.pos - "<".length;
68483                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
68484                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
68485             }
68486             return false;
68487         }
68488         function checkGrammarParameterList(parameters) {
68489             var seenOptionalParameter = false;
68490             var parameterCount = parameters.length;
68491             for (var i = 0; i < parameterCount; i++) {
68492                 var parameter = parameters[i];
68493                 if (parameter.dotDotDotToken) {
68494                     if (i !== (parameterCount - 1)) {
68495                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
68496                     }
68497                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
68498                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
68499                     }
68500                     if (parameter.questionToken) {
68501                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
68502                     }
68503                     if (parameter.initializer) {
68504                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
68505                     }
68506                 }
68507                 else if (parameter.questionToken) {
68508                     seenOptionalParameter = true;
68509                     if (parameter.initializer) {
68510                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
68511                     }
68512                 }
68513                 else if (seenOptionalParameter && !parameter.initializer) {
68514                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
68515                 }
68516             }
68517         }
68518         function getNonSimpleParameters(parameters) {
68519             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
68520         }
68521         function checkGrammarForUseStrictSimpleParameterList(node) {
68522             if (languageVersion >= 3 /* ES2016 */) {
68523                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
68524                 if (useStrictDirective_1) {
68525                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
68526                     if (ts.length(nonSimpleParameters)) {
68527                         ts.forEach(nonSimpleParameters, function (parameter) {
68528                             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));
68529                         });
68530                         var diagnostics_1 = nonSimpleParameters.map(function (parameter, index) { return (index === 0 ? ts.createDiagnosticForNode(parameter, ts.Diagnostics.Non_simple_parameter_declared_here) : ts.createDiagnosticForNode(parameter, ts.Diagnostics.and_here)); });
68531                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_1));
68532                         return true;
68533                     }
68534                 }
68535             }
68536             return false;
68537         }
68538         function checkGrammarFunctionLikeDeclaration(node) {
68539             // Prevent cascading error by short-circuit
68540             var file = ts.getSourceFileOfNode(node);
68541             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) ||
68542                 checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) ||
68543                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
68544         }
68545         function checkGrammarClassLikeDeclaration(node) {
68546             var file = ts.getSourceFileOfNode(node);
68547             return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
68548         }
68549         function checkGrammarArrowFunction(node, file) {
68550             if (!ts.isArrowFunction(node)) {
68551                 return false;
68552             }
68553             var equalsGreaterThanToken = node.equalsGreaterThanToken;
68554             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
68555             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
68556             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
68557         }
68558         function checkGrammarIndexSignatureParameters(node) {
68559             var parameter = node.parameters[0];
68560             if (node.parameters.length !== 1) {
68561                 if (parameter) {
68562                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68563                 }
68564                 else {
68565                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
68566                 }
68567             }
68568             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
68569             if (parameter.dotDotDotToken) {
68570                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
68571             }
68572             if (ts.hasModifiers(parameter)) {
68573                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
68574             }
68575             if (parameter.questionToken) {
68576                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
68577             }
68578             if (parameter.initializer) {
68579                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
68580             }
68581             if (!parameter.type) {
68582                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
68583             }
68584             if (parameter.type.kind !== 143 /* StringKeyword */ && parameter.type.kind !== 140 /* NumberKeyword */) {
68585                 var type = getTypeFromTypeNode(parameter.type);
68586                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
68587                     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));
68588                 }
68589                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
68590                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
68591                 }
68592                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
68593             }
68594             if (!node.type) {
68595                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
68596             }
68597             return false;
68598         }
68599         function checkGrammarIndexSignature(node) {
68600             // Prevent cascading error by short-circuit
68601             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
68602         }
68603         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
68604             if (typeArguments && typeArguments.length === 0) {
68605                 var sourceFile = ts.getSourceFileOfNode(node);
68606                 var start = typeArguments.pos - "<".length;
68607                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
68608                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
68609             }
68610             return false;
68611         }
68612         function checkGrammarTypeArguments(node, typeArguments) {
68613             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
68614                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
68615         }
68616         function checkGrammarTaggedTemplateChain(node) {
68617             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
68618                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
68619             }
68620             return false;
68621         }
68622         function checkGrammarForOmittedArgument(args) {
68623             if (args) {
68624                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
68625                     var arg = args_4[_i];
68626                     if (arg.kind === 215 /* OmittedExpression */) {
68627                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
68628                     }
68629                 }
68630             }
68631             return false;
68632         }
68633         function checkGrammarArguments(args) {
68634             return checkGrammarForOmittedArgument(args);
68635         }
68636         function checkGrammarHeritageClause(node) {
68637             var types = node.types;
68638             if (checkGrammarForDisallowedTrailingComma(types)) {
68639                 return true;
68640             }
68641             if (types && types.length === 0) {
68642                 var listType = ts.tokenToString(node.token);
68643                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
68644             }
68645             return ts.some(types, checkGrammarExpressionWithTypeArguments);
68646         }
68647         function checkGrammarExpressionWithTypeArguments(node) {
68648             return checkGrammarTypeArguments(node, node.typeArguments);
68649         }
68650         function checkGrammarClassDeclarationHeritageClauses(node) {
68651             var seenExtendsClause = false;
68652             var seenImplementsClause = false;
68653             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
68654                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68655                     var heritageClause = _a[_i];
68656                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68657                         if (seenExtendsClause) {
68658                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68659                         }
68660                         if (seenImplementsClause) {
68661                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
68662                         }
68663                         if (heritageClause.types.length > 1) {
68664                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
68665                         }
68666                         seenExtendsClause = true;
68667                     }
68668                     else {
68669                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68670                         if (seenImplementsClause) {
68671                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
68672                         }
68673                         seenImplementsClause = true;
68674                     }
68675                     // Grammar checking heritageClause inside class declaration
68676                     checkGrammarHeritageClause(heritageClause);
68677                 }
68678             }
68679         }
68680         function checkGrammarInterfaceDeclaration(node) {
68681             var seenExtendsClause = false;
68682             if (node.heritageClauses) {
68683                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
68684                     var heritageClause = _a[_i];
68685                     if (heritageClause.token === 90 /* ExtendsKeyword */) {
68686                         if (seenExtendsClause) {
68687                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
68688                         }
68689                         seenExtendsClause = true;
68690                     }
68691                     else {
68692                         ts.Debug.assert(heritageClause.token === 113 /* ImplementsKeyword */);
68693                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
68694                     }
68695                     // Grammar checking heritageClause inside class declaration
68696                     checkGrammarHeritageClause(heritageClause);
68697                 }
68698             }
68699             return false;
68700         }
68701         function checkGrammarComputedPropertyName(node) {
68702             // If node is not a computedPropertyName, just skip the grammar checking
68703             if (node.kind !== 154 /* ComputedPropertyName */) {
68704                 return false;
68705             }
68706             var computedPropertyName = node;
68707             if (computedPropertyName.expression.kind === 209 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
68708                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
68709             }
68710             return false;
68711         }
68712         function checkGrammarForGenerator(node) {
68713             if (node.asteriskToken) {
68714                 ts.Debug.assert(node.kind === 244 /* FunctionDeclaration */ ||
68715                     node.kind === 201 /* FunctionExpression */ ||
68716                     node.kind === 161 /* MethodDeclaration */);
68717                 if (node.flags & 8388608 /* Ambient */) {
68718                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
68719                 }
68720                 if (!node.body) {
68721                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
68722                 }
68723             }
68724         }
68725         function checkGrammarForInvalidQuestionMark(questionToken, message) {
68726             return !!questionToken && grammarErrorOnNode(questionToken, message);
68727         }
68728         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
68729             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
68730         }
68731         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
68732             var seen = ts.createUnderscoreEscapedMap();
68733             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
68734                 var prop = _a[_i];
68735                 if (prop.kind === 283 /* SpreadAssignment */) {
68736                     if (inDestructuring) {
68737                         // a rest property cannot be destructured any further
68738                         var expression = ts.skipParentheses(prop.expression);
68739                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
68740                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
68741                         }
68742                     }
68743                     continue;
68744                 }
68745                 var name = prop.name;
68746                 if (name.kind === 154 /* ComputedPropertyName */) {
68747                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
68748                     checkGrammarComputedPropertyName(name);
68749                 }
68750                 if (prop.kind === 282 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
68751                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
68752                     // outside of destructuring it is a syntax error
68753                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment);
68754                 }
68755                 if (name.kind === 76 /* PrivateIdentifier */) {
68756                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
68757                 }
68758                 // Modifiers are never allowed on properties except for 'async' on a method declaration
68759                 if (prop.modifiers) {
68760                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
68761                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
68762                         var mod = _c[_b];
68763                         if (mod.kind !== 126 /* AsyncKeyword */ || prop.kind !== 161 /* MethodDeclaration */) {
68764                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
68765                         }
68766                     }
68767                 }
68768                 // ECMA-262 11.1.5 Object Initializer
68769                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
68770                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
68771                 // IsDataDescriptor(propId.descriptor) is true.
68772                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
68773                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
68774                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
68775                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
68776                 var currentKind = void 0;
68777                 switch (prop.kind) {
68778                     case 282 /* ShorthandPropertyAssignment */:
68779                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
68780                     // falls through
68781                     case 281 /* PropertyAssignment */:
68782                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
68783                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
68784                         if (name.kind === 8 /* NumericLiteral */) {
68785                             checkGrammarNumericLiteral(name);
68786                         }
68787                         currentKind = 4 /* PropertyAssignment */;
68788                         break;
68789                     case 161 /* MethodDeclaration */:
68790                         currentKind = 8 /* Method */;
68791                         break;
68792                     case 163 /* GetAccessor */:
68793                         currentKind = 1 /* GetAccessor */;
68794                         break;
68795                     case 164 /* SetAccessor */:
68796                         currentKind = 2 /* SetAccessor */;
68797                         break;
68798                     default:
68799                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
68800                 }
68801                 if (!inDestructuring) {
68802                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
68803                     if (effectiveName === undefined) {
68804                         continue;
68805                     }
68806                     var existingKind = seen.get(effectiveName);
68807                     if (!existingKind) {
68808                         seen.set(effectiveName, currentKind);
68809                     }
68810                     else {
68811                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
68812                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
68813                         }
68814                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
68815                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
68816                                 seen.set(effectiveName, currentKind | existingKind);
68817                             }
68818                             else {
68819                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
68820                             }
68821                         }
68822                         else {
68823                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
68824                         }
68825                     }
68826                 }
68827             }
68828         }
68829         function checkGrammarJsxElement(node) {
68830             checkGrammarTypeArguments(node, node.typeArguments);
68831             var seen = ts.createUnderscoreEscapedMap();
68832             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
68833                 var attr = _a[_i];
68834                 if (attr.kind === 275 /* JsxSpreadAttribute */) {
68835                     continue;
68836                 }
68837                 var name = attr.name, initializer = attr.initializer;
68838                 if (!seen.get(name.escapedText)) {
68839                     seen.set(name.escapedText, true);
68840                 }
68841                 else {
68842                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
68843                 }
68844                 if (initializer && initializer.kind === 276 /* JsxExpression */ && !initializer.expression) {
68845                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
68846                 }
68847             }
68848         }
68849         function checkGrammarJsxExpression(node) {
68850             if (node.expression && ts.isCommaSequence(node.expression)) {
68851                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
68852             }
68853         }
68854         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
68855             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
68856                 return true;
68857             }
68858             if (forInOrOfStatement.kind === 232 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
68859                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
68860                     // use of 'for-await-of' in non-async function
68861                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
68862                     if (!hasParseDiagnostics(sourceFile)) {
68863                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
68864                         var func = ts.getContainingFunction(forInOrOfStatement);
68865                         if (func && func.kind !== 162 /* Constructor */) {
68866                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
68867                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
68868                             ts.addRelatedInfo(diagnostic, relatedInfo);
68869                         }
68870                         diagnostics.add(diagnostic);
68871                         return true;
68872                     }
68873                     return false;
68874                 }
68875             }
68876             if (forInOrOfStatement.initializer.kind === 243 /* VariableDeclarationList */) {
68877                 var variableList = forInOrOfStatement.initializer;
68878                 if (!checkGrammarVariableDeclarationList(variableList)) {
68879                     var declarations = variableList.declarations;
68880                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
68881                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
68882                     // For example:
68883                     //      var let = 10;
68884                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
68885                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
68886                     // We will then want to skip on grammar checking on variableList declaration
68887                     if (!declarations.length) {
68888                         return false;
68889                     }
68890                     if (declarations.length > 1) {
68891                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68892                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
68893                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
68894                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
68895                     }
68896                     var firstDeclaration = declarations[0];
68897                     if (firstDeclaration.initializer) {
68898                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68899                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
68900                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
68901                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
68902                     }
68903                     if (firstDeclaration.type) {
68904                         var diagnostic = forInOrOfStatement.kind === 231 /* ForInStatement */
68905                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
68906                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
68907                         return grammarErrorOnNode(firstDeclaration, diagnostic);
68908                     }
68909                 }
68910             }
68911             return false;
68912         }
68913         function checkGrammarAccessor(accessor) {
68914             if (!(accessor.flags & 8388608 /* Ambient */)) {
68915                 if (languageVersion < 1 /* ES5 */) {
68916                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
68917                 }
68918                 if (accessor.body === undefined && !ts.hasModifier(accessor, 128 /* Abstract */)) {
68919                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
68920                 }
68921             }
68922             if (accessor.body && ts.hasModifier(accessor, 128 /* Abstract */)) {
68923                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
68924             }
68925             if (accessor.typeParameters) {
68926                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
68927             }
68928             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
68929                 return grammarErrorOnNode(accessor.name, accessor.kind === 163 /* GetAccessor */ ?
68930                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
68931                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
68932             }
68933             if (accessor.kind === 164 /* SetAccessor */) {
68934                 if (accessor.type) {
68935                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
68936                 }
68937                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
68938                 if (parameter.dotDotDotToken) {
68939                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
68940                 }
68941                 if (parameter.questionToken) {
68942                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
68943                 }
68944                 if (parameter.initializer) {
68945                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
68946                 }
68947             }
68948             return false;
68949         }
68950         /** Does the accessor have the right number of parameters?
68951          * A get accessor has no parameters or a single `this` parameter.
68952          * A set accessor has one parameter or a `this` parameter and one more parameter.
68953          */
68954         function doesAccessorHaveCorrectParameterCount(accessor) {
68955             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 0 : 1);
68956         }
68957         function getAccessorThisParameter(accessor) {
68958             if (accessor.parameters.length === (accessor.kind === 163 /* GetAccessor */ ? 1 : 2)) {
68959                 return ts.getThisParameter(accessor);
68960             }
68961         }
68962         function checkGrammarTypeOperatorNode(node) {
68963             if (node.operator === 147 /* UniqueKeyword */) {
68964                 if (node.type.kind !== 144 /* SymbolKeyword */) {
68965                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(144 /* SymbolKeyword */));
68966                 }
68967                 var parent = ts.walkUpParenthesizedTypes(node.parent);
68968                 switch (parent.kind) {
68969                     case 242 /* VariableDeclaration */:
68970                         var decl = parent;
68971                         if (decl.name.kind !== 75 /* Identifier */) {
68972                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
68973                         }
68974                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
68975                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
68976                         }
68977                         if (!(decl.parent.flags & 2 /* Const */)) {
68978                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
68979                         }
68980                         break;
68981                     case 159 /* PropertyDeclaration */:
68982                         if (!ts.hasModifier(parent, 32 /* Static */) ||
68983                             !ts.hasModifier(parent, 64 /* Readonly */)) {
68984                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
68985                         }
68986                         break;
68987                     case 158 /* PropertySignature */:
68988                         if (!ts.hasModifier(parent, 64 /* Readonly */)) {
68989                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
68990                         }
68991                         break;
68992                     default:
68993                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
68994                 }
68995             }
68996             else if (node.operator === 138 /* ReadonlyKeyword */) {
68997                 if (node.type.kind !== 174 /* ArrayType */ && node.type.kind !== 175 /* TupleType */) {
68998                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(144 /* SymbolKeyword */));
68999                 }
69000             }
69001         }
69002         function checkGrammarForInvalidDynamicName(node, message) {
69003             if (isNonBindableDynamicName(node)) {
69004                 return grammarErrorOnNode(node, message);
69005             }
69006         }
69007         function checkGrammarMethod(node) {
69008             if (checkGrammarFunctionLikeDeclaration(node)) {
69009                 return true;
69010             }
69011             if (node.kind === 161 /* MethodDeclaration */) {
69012                 if (node.parent.kind === 193 /* ObjectLiteralExpression */) {
69013                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
69014                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 126 /* AsyncKeyword */)) {
69015                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
69016                     }
69017                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
69018                         return true;
69019                     }
69020                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
69021                         return true;
69022                     }
69023                     else if (node.body === undefined) {
69024                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
69025                     }
69026                 }
69027                 if (checkGrammarForGenerator(node)) {
69028                     return true;
69029                 }
69030             }
69031             if (ts.isClassLike(node.parent)) {
69032                 // Technically, computed properties in ambient contexts is disallowed
69033                 // for property declarations and accessors too, not just methods.
69034                 // However, property declarations disallow computed names in general,
69035                 // and accessors are not allowed in ambient contexts in general,
69036                 // so this error only really matters for methods.
69037                 if (node.flags & 8388608 /* Ambient */) {
69038                     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);
69039                 }
69040                 else if (node.kind === 161 /* MethodDeclaration */ && !node.body) {
69041                     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);
69042                 }
69043             }
69044             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69045                 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);
69046             }
69047             else if (node.parent.kind === 173 /* TypeLiteral */) {
69048                 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);
69049             }
69050         }
69051         function checkGrammarBreakOrContinueStatement(node) {
69052             var current = node;
69053             while (current) {
69054                 if (ts.isFunctionLike(current)) {
69055                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
69056                 }
69057                 switch (current.kind) {
69058                     case 238 /* LabeledStatement */:
69059                         if (node.label && current.label.escapedText === node.label.escapedText) {
69060                             // found matching label - verify that label usage is correct
69061                             // continue can only target labels that are on iteration statements
69062                             var isMisplacedContinueLabel = node.kind === 233 /* ContinueStatement */
69063                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
69064                             if (isMisplacedContinueLabel) {
69065                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
69066                             }
69067                             return false;
69068                         }
69069                         break;
69070                     case 237 /* SwitchStatement */:
69071                         if (node.kind === 234 /* BreakStatement */ && !node.label) {
69072                             // unlabeled break within switch statement - ok
69073                             return false;
69074                         }
69075                         break;
69076                     default:
69077                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
69078                             // unlabeled break or continue within iteration statement - ok
69079                             return false;
69080                         }
69081                         break;
69082                 }
69083                 current = current.parent;
69084             }
69085             if (node.label) {
69086                 var message = node.kind === 234 /* BreakStatement */
69087                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
69088                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
69089                 return grammarErrorOnNode(node, message);
69090             }
69091             else {
69092                 var message = node.kind === 234 /* BreakStatement */
69093                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
69094                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
69095                 return grammarErrorOnNode(node, message);
69096             }
69097         }
69098         function checkGrammarBindingElement(node) {
69099             if (node.dotDotDotToken) {
69100                 var elements = node.parent.elements;
69101                 if (node !== ts.last(elements)) {
69102                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
69103                 }
69104                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
69105                 if (node.propertyName) {
69106                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
69107                 }
69108                 if (node.initializer) {
69109                     // Error on equals token which immediately precedes the initializer
69110                     return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
69111                 }
69112             }
69113         }
69114         function isStringOrNumberLiteralExpression(expr) {
69115             return ts.isStringOrNumericLiteralLike(expr) ||
69116                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69117                     expr.operand.kind === 8 /* NumericLiteral */;
69118         }
69119         function isBigIntLiteralExpression(expr) {
69120             return expr.kind === 9 /* BigIntLiteral */ ||
69121                 expr.kind === 207 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
69122                     expr.operand.kind === 9 /* BigIntLiteral */;
69123         }
69124         function isSimpleLiteralEnumReference(expr) {
69125             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
69126                 ts.isEntityNameExpression(expr.expression)) {
69127                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
69128             }
69129         }
69130         function checkAmbientInitializer(node) {
69131             var initializer = node.initializer;
69132             if (initializer) {
69133                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
69134                     isSimpleLiteralEnumReference(initializer) ||
69135                     initializer.kind === 106 /* TrueKeyword */ || initializer.kind === 91 /* FalseKeyword */ ||
69136                     isBigIntLiteralExpression(initializer));
69137                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
69138                 if (isConstOrReadonly && !node.type) {
69139                     if (isInvalidInitializer) {
69140                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
69141                     }
69142                 }
69143                 else {
69144                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69145                 }
69146                 if (!isConstOrReadonly || isInvalidInitializer) {
69147                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
69148                 }
69149             }
69150         }
69151         function checkGrammarVariableDeclaration(node) {
69152             if (node.parent.parent.kind !== 231 /* ForInStatement */ && node.parent.parent.kind !== 232 /* ForOfStatement */) {
69153                 if (node.flags & 8388608 /* Ambient */) {
69154                     checkAmbientInitializer(node);
69155                 }
69156                 else if (!node.initializer) {
69157                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
69158                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
69159                     }
69160                     if (ts.isVarConst(node)) {
69161                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
69162                     }
69163                 }
69164             }
69165             if (node.exclamationToken && (node.parent.parent.kind !== 225 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
69166                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.Definite_assignment_assertions_can_only_be_used_along_with_a_type_annotation);
69167             }
69168             var moduleKind = ts.getEmitModuleKind(compilerOptions);
69169             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System && !compilerOptions.noEmit &&
69170                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasModifier(node.parent.parent, 1 /* Export */)) {
69171                 checkESModuleMarker(node.name);
69172             }
69173             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
69174             // 1. LexicalDeclaration : LetOrConst BindingList ;
69175             // It is a Syntax Error if the BoundNames of BindingList contains "let".
69176             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
69177             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
69178             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
69179             // and its Identifier is eval or arguments
69180             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
69181         }
69182         function checkESModuleMarker(name) {
69183             if (name.kind === 75 /* Identifier */) {
69184                 if (ts.idText(name) === "__esModule") {
69185                     return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
69186                 }
69187             }
69188             else {
69189                 var elements = name.elements;
69190                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
69191                     var element = elements_1[_i];
69192                     if (!ts.isOmittedExpression(element)) {
69193                         return checkESModuleMarker(element.name);
69194                     }
69195                 }
69196             }
69197             return false;
69198         }
69199         function checkGrammarNameInLetOrConstDeclarations(name) {
69200             if (name.kind === 75 /* Identifier */) {
69201                 if (name.originalKeywordKind === 115 /* LetKeyword */) {
69202                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
69203                 }
69204             }
69205             else {
69206                 var elements = name.elements;
69207                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
69208                     var element = elements_2[_i];
69209                     if (!ts.isOmittedExpression(element)) {
69210                         checkGrammarNameInLetOrConstDeclarations(element.name);
69211                     }
69212                 }
69213             }
69214             return false;
69215         }
69216         function checkGrammarVariableDeclarationList(declarationList) {
69217             var declarations = declarationList.declarations;
69218             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
69219                 return true;
69220             }
69221             if (!declarationList.declarations.length) {
69222                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
69223             }
69224             return false;
69225         }
69226         function allowLetAndConstDeclarations(parent) {
69227             switch (parent.kind) {
69228                 case 227 /* IfStatement */:
69229                 case 228 /* DoStatement */:
69230                 case 229 /* WhileStatement */:
69231                 case 236 /* WithStatement */:
69232                 case 230 /* ForStatement */:
69233                 case 231 /* ForInStatement */:
69234                 case 232 /* ForOfStatement */:
69235                     return false;
69236                 case 238 /* LabeledStatement */:
69237                     return allowLetAndConstDeclarations(parent.parent);
69238             }
69239             return true;
69240         }
69241         function checkGrammarForDisallowedLetOrConstStatement(node) {
69242             if (!allowLetAndConstDeclarations(node.parent)) {
69243                 if (ts.isLet(node.declarationList)) {
69244                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
69245                 }
69246                 else if (ts.isVarConst(node.declarationList)) {
69247                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
69248                 }
69249             }
69250         }
69251         function checkGrammarMetaProperty(node) {
69252             var escapedText = node.name.escapedText;
69253             switch (node.keywordToken) {
69254                 case 99 /* NewKeyword */:
69255                     if (escapedText !== "target") {
69256                         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");
69257                     }
69258                     break;
69259                 case 96 /* ImportKeyword */:
69260                     if (escapedText !== "meta") {
69261                         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");
69262                     }
69263                     break;
69264             }
69265         }
69266         function hasParseDiagnostics(sourceFile) {
69267             return sourceFile.parseDiagnostics.length > 0;
69268         }
69269         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
69270             var sourceFile = ts.getSourceFileOfNode(node);
69271             if (!hasParseDiagnostics(sourceFile)) {
69272                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69273                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
69274                 return true;
69275             }
69276             return false;
69277         }
69278         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
69279             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
69280             if (!hasParseDiagnostics(sourceFile)) {
69281                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
69282                 return true;
69283             }
69284             return false;
69285         }
69286         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
69287             var sourceFile = ts.getSourceFileOfNode(node);
69288             if (!hasParseDiagnostics(sourceFile)) {
69289                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
69290                 return true;
69291             }
69292             return false;
69293         }
69294         function checkGrammarConstructorTypeParameters(node) {
69295             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
69296             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
69297             if (range) {
69298                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
69299                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
69300             }
69301         }
69302         function checkGrammarConstructorTypeAnnotation(node) {
69303             var type = ts.getEffectiveReturnTypeNode(node);
69304             if (type) {
69305                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
69306             }
69307         }
69308         function checkGrammarProperty(node) {
69309             if (ts.isClassLike(node.parent)) {
69310                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
69311                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
69312                 }
69313                 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)) {
69314                     return true;
69315                 }
69316                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
69317                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
69318                 }
69319             }
69320             else if (node.parent.kind === 246 /* InterfaceDeclaration */) {
69321                 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)) {
69322                     return true;
69323                 }
69324                 if (node.initializer) {
69325                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
69326                 }
69327             }
69328             else if (node.parent.kind === 173 /* TypeLiteral */) {
69329                 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)) {
69330                     return true;
69331                 }
69332                 if (node.initializer) {
69333                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
69334                 }
69335             }
69336             if (node.flags & 8388608 /* Ambient */) {
69337                 checkAmbientInitializer(node);
69338             }
69339             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
69340                 node.flags & 8388608 /* Ambient */ || ts.hasModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
69341                 return grammarErrorOnNode(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
69342             }
69343         }
69344         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
69345             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
69346             // interfaces and imports categories:
69347             //
69348             //  DeclarationElement:
69349             //     ExportAssignment
69350             //     export_opt   InterfaceDeclaration
69351             //     export_opt   TypeAliasDeclaration
69352             //     export_opt   ImportDeclaration
69353             //     export_opt   ExternalImportDeclaration
69354             //     export_opt   AmbientDeclaration
69355             //
69356             // TODO: The spec needs to be amended to reflect this grammar.
69357             if (node.kind === 246 /* InterfaceDeclaration */ ||
69358                 node.kind === 247 /* TypeAliasDeclaration */ ||
69359                 node.kind === 254 /* ImportDeclaration */ ||
69360                 node.kind === 253 /* ImportEqualsDeclaration */ ||
69361                 node.kind === 260 /* ExportDeclaration */ ||
69362                 node.kind === 259 /* ExportAssignment */ ||
69363                 node.kind === 252 /* NamespaceExportDeclaration */ ||
69364                 ts.hasModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
69365                 return false;
69366             }
69367             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
69368         }
69369         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
69370             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
69371                 var decl = _a[_i];
69372                 if (ts.isDeclaration(decl) || decl.kind === 225 /* VariableStatement */) {
69373                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
69374                         return true;
69375                     }
69376                 }
69377             }
69378             return false;
69379         }
69380         function checkGrammarSourceFile(node) {
69381             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
69382         }
69383         function checkGrammarStatementInAmbientContext(node) {
69384             if (node.flags & 8388608 /* Ambient */) {
69385                 // Find containing block which is either Block, ModuleBlock, SourceFile
69386                 var links = getNodeLinks(node);
69387                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
69388                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
69389                 }
69390                 // We are either parented by another statement, or some sort of block.
69391                 // If we're in a block, we only want to really report an error once
69392                 // to prevent noisiness.  So use a bit on the block to indicate if
69393                 // this has already been reported, and don't report if it has.
69394                 //
69395                 if (node.parent.kind === 223 /* Block */ || node.parent.kind === 250 /* ModuleBlock */ || node.parent.kind === 290 /* SourceFile */) {
69396                     var links_2 = getNodeLinks(node.parent);
69397                     // Check if the containing block ever report this error
69398                     if (!links_2.hasReportedStatementInAmbientContext) {
69399                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
69400                     }
69401                 }
69402                 else {
69403                     // We must be parented by a statement.  If so, there's no need
69404                     // to report the error as our parent will have already done it.
69405                     // Debug.assert(isStatement(node.parent));
69406                 }
69407             }
69408             return false;
69409         }
69410         function checkGrammarNumericLiteral(node) {
69411             // Grammar checking
69412             if (node.numericLiteralFlags & 32 /* Octal */) {
69413                 var diagnosticMessage = void 0;
69414                 if (languageVersion >= 1 /* ES5 */) {
69415                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
69416                 }
69417                 else if (ts.isChildOfNodeWithKind(node, 187 /* LiteralType */)) {
69418                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
69419                 }
69420                 else if (ts.isChildOfNodeWithKind(node, 284 /* EnumMember */)) {
69421                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
69422                 }
69423                 if (diagnosticMessage) {
69424                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
69425                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
69426                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
69427                 }
69428             }
69429             // Realism (size) checking
69430             checkNumericLiteralValueSize(node);
69431             return false;
69432         }
69433         function checkNumericLiteralValueSize(node) {
69434             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
69435             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
69436             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
69437             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
69438                 return;
69439             }
69440             // We can't rely on the runtime to accurately store and compare extremely large numeric values
69441             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
69442             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
69443             // it's likely addition operations on it will fail too
69444             var apparentValue = +ts.getTextOfNode(node);
69445             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
69446                 return;
69447             }
69448             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));
69449         }
69450         function checkGrammarBigIntLiteral(node) {
69451             var literalType = ts.isLiteralTypeNode(node.parent) ||
69452                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
69453             if (!literalType) {
69454                 if (languageVersion < 7 /* ES2020 */) {
69455                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
69456                         return true;
69457                     }
69458                 }
69459             }
69460             return false;
69461         }
69462         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
69463             var sourceFile = ts.getSourceFileOfNode(node);
69464             if (!hasParseDiagnostics(sourceFile)) {
69465                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
69466                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
69467                 return true;
69468             }
69469             return false;
69470         }
69471         function getAmbientModules() {
69472             if (!ambientModulesCache) {
69473                 ambientModulesCache = [];
69474                 globals.forEach(function (global, sym) {
69475                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
69476                     if (ambientModuleSymbolRegex.test(sym)) {
69477                         ambientModulesCache.push(global);
69478                     }
69479                 });
69480             }
69481             return ambientModulesCache;
69482         }
69483         function checkGrammarImportClause(node) {
69484             if (node.isTypeOnly && node.name && node.namedBindings) {
69485                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
69486             }
69487             return false;
69488         }
69489         function checkGrammarImportCallExpression(node) {
69490             if (moduleKind === ts.ModuleKind.ES2015) {
69491                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
69492             }
69493             if (node.typeArguments) {
69494                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
69495             }
69496             var nodeArguments = node.arguments;
69497             if (nodeArguments.length !== 1) {
69498                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
69499             }
69500             checkGrammarForDisallowedTrailingComma(nodeArguments);
69501             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
69502             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
69503             if (ts.isSpreadElement(nodeArguments[0])) {
69504                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
69505             }
69506             return false;
69507         }
69508         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
69509             var sourceObjectFlags = ts.getObjectFlags(source);
69510             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
69511                 return ts.find(unionTarget.types, function (target) {
69512                     if (target.flags & 524288 /* Object */) {
69513                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
69514                         if (overlapObjFlags & 4 /* Reference */) {
69515                             return source.target === target.target;
69516                         }
69517                         if (overlapObjFlags & 16 /* Anonymous */) {
69518                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
69519                         }
69520                     }
69521                     return false;
69522                 });
69523             }
69524         }
69525         function findBestTypeForObjectLiteral(source, unionTarget) {
69526             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
69527                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
69528             }
69529         }
69530         function findBestTypeForInvokable(source, unionTarget) {
69531             var signatureKind = 0 /* Call */;
69532             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
69533                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
69534             if (hasSignatures) {
69535                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
69536             }
69537         }
69538         function findMostOverlappyType(source, unionTarget) {
69539             var bestMatch;
69540             var matchingCount = 0;
69541             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
69542                 var target = _a[_i];
69543                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
69544                 if (overlap.flags & 4194304 /* Index */) {
69545                     // perfect overlap of keys
69546                     bestMatch = target;
69547                     matchingCount = Infinity;
69548                 }
69549                 else if (overlap.flags & 1048576 /* Union */) {
69550                     // We only want to account for literal types otherwise.
69551                     // If we have a union of index types, it seems likely that we
69552                     // needed to elaborate between two generic mapped types anyway.
69553                     var len = ts.length(ts.filter(overlap.types, isUnitType));
69554                     if (len >= matchingCount) {
69555                         bestMatch = target;
69556                         matchingCount = len;
69557                     }
69558                 }
69559                 else if (isUnitType(overlap) && 1 >= matchingCount) {
69560                     bestMatch = target;
69561                     matchingCount = 1;
69562                 }
69563             }
69564             return bestMatch;
69565         }
69566         function filterPrimitivesIfContainsNonPrimitive(type) {
69567             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
69568                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
69569                 if (!(result.flags & 131072 /* Never */)) {
69570                     return result;
69571                 }
69572             }
69573             return type;
69574         }
69575         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
69576         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
69577             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
69578                 var sourceProperties = getPropertiesOfType(source);
69579                 if (sourceProperties) {
69580                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
69581                     if (sourcePropertiesFiltered) {
69582                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
69583                     }
69584                 }
69585             }
69586             return undefined;
69587         }
69588     }
69589     ts.createTypeChecker = createTypeChecker;
69590     function isNotAccessor(declaration) {
69591         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
69592         return !ts.isAccessor(declaration);
69593     }
69594     function isNotOverload(declaration) {
69595         return (declaration.kind !== 244 /* FunctionDeclaration */ && declaration.kind !== 161 /* MethodDeclaration */) ||
69596             !!declaration.body;
69597     }
69598     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
69599     function isDeclarationNameOrImportPropertyName(name) {
69600         switch (name.parent.kind) {
69601             case 258 /* ImportSpecifier */:
69602             case 263 /* ExportSpecifier */:
69603                 return ts.isIdentifier(name);
69604             default:
69605                 return ts.isDeclarationName(name);
69606         }
69607     }
69608     function isSomeImportDeclaration(decl) {
69609         switch (decl.kind) {
69610             case 255 /* ImportClause */: // For default import
69611             case 253 /* ImportEqualsDeclaration */:
69612             case 256 /* NamespaceImport */:
69613             case 258 /* ImportSpecifier */: // For rename import `x as y`
69614                 return true;
69615             case 75 /* Identifier */:
69616                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
69617                 return decl.parent.kind === 258 /* ImportSpecifier */;
69618             default:
69619                 return false;
69620         }
69621     }
69622     var JsxNames;
69623     (function (JsxNames) {
69624         JsxNames.JSX = "JSX";
69625         JsxNames.IntrinsicElements = "IntrinsicElements";
69626         JsxNames.ElementClass = "ElementClass";
69627         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
69628         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
69629         JsxNames.Element = "Element";
69630         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
69631         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
69632         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
69633     })(JsxNames || (JsxNames = {}));
69634     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
69635         switch (typeKind) {
69636             case 0 /* Yield */: return "yieldType";
69637             case 1 /* Return */: return "returnType";
69638             case 2 /* Next */: return "nextType";
69639         }
69640     }
69641     function signatureHasRestParameter(s) {
69642         return !!(s.flags & 1 /* HasRestParameter */);
69643     }
69644     ts.signatureHasRestParameter = signatureHasRestParameter;
69645     function signatureHasLiteralTypes(s) {
69646         return !!(s.flags & 2 /* HasLiteralTypes */);
69647     }
69648     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
69649 })(ts || (ts = {}));
69650 var ts;
69651 (function (ts) {
69652     function createSynthesizedNode(kind) {
69653         var node = ts.createNode(kind, -1, -1);
69654         node.flags |= 8 /* Synthesized */;
69655         return node;
69656     }
69657     /* @internal */
69658     function updateNode(updated, original) {
69659         if (updated !== original) {
69660             setOriginalNode(updated, original);
69661             setTextRange(updated, original);
69662             ts.aggregateTransformFlags(updated);
69663         }
69664         return updated;
69665     }
69666     ts.updateNode = updateNode;
69667     /**
69668      * Make `elements` into a `NodeArray<T>`. If `elements` is `undefined`, returns an empty `NodeArray<T>`.
69669      */
69670     function createNodeArray(elements, hasTrailingComma) {
69671         if (!elements || elements === ts.emptyArray) {
69672             elements = [];
69673         }
69674         else if (ts.isNodeArray(elements)) {
69675             return elements;
69676         }
69677         var array = elements;
69678         array.pos = -1;
69679         array.end = -1;
69680         array.hasTrailingComma = hasTrailingComma;
69681         return array;
69682     }
69683     ts.createNodeArray = createNodeArray;
69684     /**
69685      * Creates a shallow, memberwise clone of a node with no source map location.
69686      */
69687     /* @internal */
69688     function getSynthesizedClone(node) {
69689         // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
69690         // the original node. We also need to exclude specific properties and only include own-
69691         // properties (to skip members already defined on the shared prototype).
69692         if (node === undefined) {
69693             return node;
69694         }
69695         var clone = createSynthesizedNode(node.kind);
69696         clone.flags |= node.flags;
69697         setOriginalNode(clone, node);
69698         for (var key in node) {
69699             if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
69700                 continue;
69701             }
69702             clone[key] = node[key];
69703         }
69704         return clone;
69705     }
69706     ts.getSynthesizedClone = getSynthesizedClone;
69707     function createLiteral(value, isSingleQuote) {
69708         if (typeof value === "number") {
69709             return createNumericLiteral(value + "");
69710         }
69711         // eslint-disable-next-line no-in-operator
69712         if (typeof value === "object" && "base10Value" in value) { // PseudoBigInt
69713             return createBigIntLiteral(ts.pseudoBigIntToString(value) + "n");
69714         }
69715         if (typeof value === "boolean") {
69716             return value ? createTrue() : createFalse();
69717         }
69718         if (ts.isString(value)) {
69719             var res = createStringLiteral(value);
69720             if (isSingleQuote)
69721                 res.singleQuote = true;
69722             return res;
69723         }
69724         return createLiteralFromNode(value);
69725     }
69726     ts.createLiteral = createLiteral;
69727     function createNumericLiteral(value, numericLiteralFlags) {
69728         if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
69729         var node = createSynthesizedNode(8 /* NumericLiteral */);
69730         node.text = value;
69731         node.numericLiteralFlags = numericLiteralFlags;
69732         return node;
69733     }
69734     ts.createNumericLiteral = createNumericLiteral;
69735     function createBigIntLiteral(value) {
69736         var node = createSynthesizedNode(9 /* BigIntLiteral */);
69737         node.text = value;
69738         return node;
69739     }
69740     ts.createBigIntLiteral = createBigIntLiteral;
69741     function createStringLiteral(text) {
69742         var node = createSynthesizedNode(10 /* StringLiteral */);
69743         node.text = text;
69744         return node;
69745     }
69746     ts.createStringLiteral = createStringLiteral;
69747     function createRegularExpressionLiteral(text) {
69748         var node = createSynthesizedNode(13 /* RegularExpressionLiteral */);
69749         node.text = text;
69750         return node;
69751     }
69752     ts.createRegularExpressionLiteral = createRegularExpressionLiteral;
69753     function createLiteralFromNode(sourceNode) {
69754         var node = createStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode));
69755         node.textSourceNode = sourceNode;
69756         return node;
69757     }
69758     function createIdentifier(text, typeArguments) {
69759         var node = createSynthesizedNode(75 /* Identifier */);
69760         node.escapedText = ts.escapeLeadingUnderscores(text);
69761         node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */;
69762         node.autoGenerateFlags = 0 /* None */;
69763         node.autoGenerateId = 0;
69764         if (typeArguments) {
69765             node.typeArguments = createNodeArray(typeArguments);
69766         }
69767         return node;
69768     }
69769     ts.createIdentifier = createIdentifier;
69770     function updateIdentifier(node, typeArguments) {
69771         return node.typeArguments !== typeArguments
69772             ? updateNode(createIdentifier(ts.idText(node), typeArguments), node)
69773             : node;
69774     }
69775     ts.updateIdentifier = updateIdentifier;
69776     var nextAutoGenerateId = 0;
69777     function createTempVariable(recordTempVariable, reservedInNestedScopes) {
69778         var name = createIdentifier("");
69779         name.autoGenerateFlags = 1 /* Auto */;
69780         name.autoGenerateId = nextAutoGenerateId;
69781         nextAutoGenerateId++;
69782         if (recordTempVariable) {
69783             recordTempVariable(name);
69784         }
69785         if (reservedInNestedScopes) {
69786             name.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
69787         }
69788         return name;
69789     }
69790     ts.createTempVariable = createTempVariable;
69791     /** Create a unique temporary variable for use in a loop. */
69792     function createLoopVariable() {
69793         var name = createIdentifier("");
69794         name.autoGenerateFlags = 2 /* Loop */;
69795         name.autoGenerateId = nextAutoGenerateId;
69796         nextAutoGenerateId++;
69797         return name;
69798     }
69799     ts.createLoopVariable = createLoopVariable;
69800     /** Create a unique name based on the supplied text. */
69801     function createUniqueName(text) {
69802         var name = createIdentifier(text);
69803         name.autoGenerateFlags = 3 /* Unique */;
69804         name.autoGenerateId = nextAutoGenerateId;
69805         nextAutoGenerateId++;
69806         return name;
69807     }
69808     ts.createUniqueName = createUniqueName;
69809     function createOptimisticUniqueName(text) {
69810         var name = createIdentifier(text);
69811         name.autoGenerateFlags = 3 /* Unique */ | 16 /* Optimistic */;
69812         name.autoGenerateId = nextAutoGenerateId;
69813         nextAutoGenerateId++;
69814         return name;
69815     }
69816     ts.createOptimisticUniqueName = createOptimisticUniqueName;
69817     /** Create a unique name based on the supplied text. This does not consider names injected by the transformer. */
69818     function createFileLevelUniqueName(text) {
69819         var name = createOptimisticUniqueName(text);
69820         name.autoGenerateFlags |= 32 /* FileLevel */;
69821         return name;
69822     }
69823     ts.createFileLevelUniqueName = createFileLevelUniqueName;
69824     function getGeneratedNameForNode(node, flags) {
69825         var name = createIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "");
69826         name.autoGenerateFlags = 4 /* Node */ | flags;
69827         name.autoGenerateId = nextAutoGenerateId;
69828         name.original = node;
69829         nextAutoGenerateId++;
69830         return name;
69831     }
69832     ts.getGeneratedNameForNode = getGeneratedNameForNode;
69833     // Private Identifiers
69834     function createPrivateIdentifier(text) {
69835         if (text[0] !== "#") {
69836             ts.Debug.fail("First character of private identifier must be #: " + text);
69837         }
69838         var node = createSynthesizedNode(76 /* PrivateIdentifier */);
69839         node.escapedText = ts.escapeLeadingUnderscores(text);
69840         return node;
69841     }
69842     ts.createPrivateIdentifier = createPrivateIdentifier;
69843     // Punctuation
69844     function createToken(token) {
69845         return createSynthesizedNode(token);
69846     }
69847     ts.createToken = createToken;
69848     // Reserved words
69849     function createSuper() {
69850         return createSynthesizedNode(102 /* SuperKeyword */);
69851     }
69852     ts.createSuper = createSuper;
69853     function createThis() {
69854         return createSynthesizedNode(104 /* ThisKeyword */);
69855     }
69856     ts.createThis = createThis;
69857     function createNull() {
69858         return createSynthesizedNode(100 /* NullKeyword */);
69859     }
69860     ts.createNull = createNull;
69861     function createTrue() {
69862         return createSynthesizedNode(106 /* TrueKeyword */);
69863     }
69864     ts.createTrue = createTrue;
69865     function createFalse() {
69866         return createSynthesizedNode(91 /* FalseKeyword */);
69867     }
69868     ts.createFalse = createFalse;
69869     // Modifiers
69870     function createModifier(kind) {
69871         return createToken(kind);
69872     }
69873     ts.createModifier = createModifier;
69874     function createModifiersFromModifierFlags(flags) {
69875         var result = [];
69876         if (flags & 1 /* Export */) {
69877             result.push(createModifier(89 /* ExportKeyword */));
69878         }
69879         if (flags & 2 /* Ambient */) {
69880             result.push(createModifier(130 /* DeclareKeyword */));
69881         }
69882         if (flags & 512 /* Default */) {
69883             result.push(createModifier(84 /* DefaultKeyword */));
69884         }
69885         if (flags & 2048 /* Const */) {
69886             result.push(createModifier(81 /* ConstKeyword */));
69887         }
69888         if (flags & 4 /* Public */) {
69889             result.push(createModifier(119 /* PublicKeyword */));
69890         }
69891         if (flags & 8 /* Private */) {
69892             result.push(createModifier(117 /* PrivateKeyword */));
69893         }
69894         if (flags & 16 /* Protected */) {
69895             result.push(createModifier(118 /* ProtectedKeyword */));
69896         }
69897         if (flags & 128 /* Abstract */) {
69898             result.push(createModifier(122 /* AbstractKeyword */));
69899         }
69900         if (flags & 32 /* Static */) {
69901             result.push(createModifier(120 /* StaticKeyword */));
69902         }
69903         if (flags & 64 /* Readonly */) {
69904             result.push(createModifier(138 /* ReadonlyKeyword */));
69905         }
69906         if (flags & 256 /* Async */) {
69907             result.push(createModifier(126 /* AsyncKeyword */));
69908         }
69909         return result;
69910     }
69911     ts.createModifiersFromModifierFlags = createModifiersFromModifierFlags;
69912     // Names
69913     function createQualifiedName(left, right) {
69914         var node = createSynthesizedNode(153 /* QualifiedName */);
69915         node.left = left;
69916         node.right = asName(right);
69917         return node;
69918     }
69919     ts.createQualifiedName = createQualifiedName;
69920     function updateQualifiedName(node, left, right) {
69921         return node.left !== left
69922             || node.right !== right
69923             ? updateNode(createQualifiedName(left, right), node)
69924             : node;
69925     }
69926     ts.updateQualifiedName = updateQualifiedName;
69927     function parenthesizeForComputedName(expression) {
69928         return ts.isCommaSequence(expression)
69929             ? createParen(expression)
69930             : expression;
69931     }
69932     function createComputedPropertyName(expression) {
69933         var node = createSynthesizedNode(154 /* ComputedPropertyName */);
69934         node.expression = parenthesizeForComputedName(expression);
69935         return node;
69936     }
69937     ts.createComputedPropertyName = createComputedPropertyName;
69938     function updateComputedPropertyName(node, expression) {
69939         return node.expression !== expression
69940             ? updateNode(createComputedPropertyName(expression), node)
69941             : node;
69942     }
69943     ts.updateComputedPropertyName = updateComputedPropertyName;
69944     // Signature elements
69945     function createTypeParameterDeclaration(name, constraint, defaultType) {
69946         var node = createSynthesizedNode(155 /* TypeParameter */);
69947         node.name = asName(name);
69948         node.constraint = constraint;
69949         node.default = defaultType;
69950         return node;
69951     }
69952     ts.createTypeParameterDeclaration = createTypeParameterDeclaration;
69953     function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
69954         return node.name !== name
69955             || node.constraint !== constraint
69956             || node.default !== defaultType
69957             ? updateNode(createTypeParameterDeclaration(name, constraint, defaultType), node)
69958             : node;
69959     }
69960     ts.updateTypeParameterDeclaration = updateTypeParameterDeclaration;
69961     function createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69962         var node = createSynthesizedNode(156 /* Parameter */);
69963         node.decorators = asNodeArray(decorators);
69964         node.modifiers = asNodeArray(modifiers);
69965         node.dotDotDotToken = dotDotDotToken;
69966         node.name = asName(name);
69967         node.questionToken = questionToken;
69968         node.type = type;
69969         node.initializer = initializer ? ts.parenthesizeExpressionForList(initializer) : undefined;
69970         return node;
69971     }
69972     ts.createParameter = createParameter;
69973     function updateParameter(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
69974         return node.decorators !== decorators
69975             || node.modifiers !== modifiers
69976             || node.dotDotDotToken !== dotDotDotToken
69977             || node.name !== name
69978             || node.questionToken !== questionToken
69979             || node.type !== type
69980             || node.initializer !== initializer
69981             ? updateNode(createParameter(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
69982             : node;
69983     }
69984     ts.updateParameter = updateParameter;
69985     function createDecorator(expression) {
69986         var node = createSynthesizedNode(157 /* Decorator */);
69987         node.expression = ts.parenthesizeForAccess(expression);
69988         return node;
69989     }
69990     ts.createDecorator = createDecorator;
69991     function updateDecorator(node, expression) {
69992         return node.expression !== expression
69993             ? updateNode(createDecorator(expression), node)
69994             : node;
69995     }
69996     ts.updateDecorator = updateDecorator;
69997     // Type Elements
69998     function createPropertySignature(modifiers, name, questionToken, type, initializer) {
69999         var node = createSynthesizedNode(158 /* PropertySignature */);
70000         node.modifiers = asNodeArray(modifiers);
70001         node.name = asName(name);
70002         node.questionToken = questionToken;
70003         node.type = type;
70004         node.initializer = initializer;
70005         return node;
70006     }
70007     ts.createPropertySignature = createPropertySignature;
70008     function updatePropertySignature(node, modifiers, name, questionToken, type, initializer) {
70009         return node.modifiers !== modifiers
70010             || node.name !== name
70011             || node.questionToken !== questionToken
70012             || node.type !== type
70013             || node.initializer !== initializer
70014             ? updateNode(createPropertySignature(modifiers, name, questionToken, type, initializer), node)
70015             : node;
70016     }
70017     ts.updatePropertySignature = updatePropertySignature;
70018     function createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70019         var node = createSynthesizedNode(159 /* PropertyDeclaration */);
70020         node.decorators = asNodeArray(decorators);
70021         node.modifiers = asNodeArray(modifiers);
70022         node.name = asName(name);
70023         node.questionToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined;
70024         node.exclamationToken = questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined;
70025         node.type = type;
70026         node.initializer = initializer;
70027         return node;
70028     }
70029     ts.createProperty = createProperty;
70030     function updateProperty(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
70031         return node.decorators !== decorators
70032             || node.modifiers !== modifiers
70033             || node.name !== name
70034             || node.questionToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 57 /* QuestionToken */ ? questionOrExclamationToken : undefined)
70035             || node.exclamationToken !== (questionOrExclamationToken !== undefined && questionOrExclamationToken.kind === 53 /* ExclamationToken */ ? questionOrExclamationToken : undefined)
70036             || node.type !== type
70037             || node.initializer !== initializer
70038             ? updateNode(createProperty(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
70039             : node;
70040     }
70041     ts.updateProperty = updateProperty;
70042     function createMethodSignature(typeParameters, parameters, type, name, questionToken) {
70043         var node = createSignatureDeclaration(160 /* MethodSignature */, typeParameters, parameters, type);
70044         node.name = asName(name);
70045         node.questionToken = questionToken;
70046         return node;
70047     }
70048     ts.createMethodSignature = createMethodSignature;
70049     function updateMethodSignature(node, typeParameters, parameters, type, name, questionToken) {
70050         return node.typeParameters !== typeParameters
70051             || node.parameters !== parameters
70052             || node.type !== type
70053             || node.name !== name
70054             || node.questionToken !== questionToken
70055             ? updateNode(createMethodSignature(typeParameters, parameters, type, name, questionToken), node)
70056             : node;
70057     }
70058     ts.updateMethodSignature = updateMethodSignature;
70059     function createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70060         var node = createSynthesizedNode(161 /* MethodDeclaration */);
70061         node.decorators = asNodeArray(decorators);
70062         node.modifiers = asNodeArray(modifiers);
70063         node.asteriskToken = asteriskToken;
70064         node.name = asName(name);
70065         node.questionToken = questionToken;
70066         node.typeParameters = asNodeArray(typeParameters);
70067         node.parameters = createNodeArray(parameters);
70068         node.type = type;
70069         node.body = body;
70070         return node;
70071     }
70072     ts.createMethod = createMethod;
70073     function createMethodCall(object, methodName, argumentsList) {
70074         return createCall(createPropertyAccess(object, asName(methodName)), 
70075         /*typeArguments*/ undefined, argumentsList);
70076     }
70077     function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
70078         return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
70079     }
70080     /* @internal */
70081     function createObjectDefinePropertyCall(target, propertyName, attributes) {
70082         return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
70083     }
70084     ts.createObjectDefinePropertyCall = createObjectDefinePropertyCall;
70085     function tryAddPropertyAssignment(properties, propertyName, expression) {
70086         if (expression) {
70087             properties.push(createPropertyAssignment(propertyName, expression));
70088             return true;
70089         }
70090         return false;
70091     }
70092     /* @internal */
70093     function createPropertyDescriptor(attributes, singleLine) {
70094         var properties = [];
70095         tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
70096         tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
70097         var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
70098         isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
70099         var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
70100         isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
70101         ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
70102         return createObjectLiteral(properties, !singleLine);
70103     }
70104     ts.createPropertyDescriptor = createPropertyDescriptor;
70105     function updateMethod(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
70106         return node.decorators !== decorators
70107             || node.modifiers !== modifiers
70108             || node.asteriskToken !== asteriskToken
70109             || node.name !== name
70110             || node.questionToken !== questionToken
70111             || node.typeParameters !== typeParameters
70112             || node.parameters !== parameters
70113             || node.type !== type
70114             || node.body !== body
70115             ? updateNode(createMethod(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
70116             : node;
70117     }
70118     ts.updateMethod = updateMethod;
70119     function createConstructor(decorators, modifiers, parameters, body) {
70120         var node = createSynthesizedNode(162 /* Constructor */);
70121         node.decorators = asNodeArray(decorators);
70122         node.modifiers = asNodeArray(modifiers);
70123         node.typeParameters = undefined;
70124         node.parameters = createNodeArray(parameters);
70125         node.type = undefined;
70126         node.body = body;
70127         return node;
70128     }
70129     ts.createConstructor = createConstructor;
70130     function updateConstructor(node, decorators, modifiers, parameters, body) {
70131         return node.decorators !== decorators
70132             || node.modifiers !== modifiers
70133             || node.parameters !== parameters
70134             || node.body !== body
70135             ? updateNode(createConstructor(decorators, modifiers, parameters, body), node)
70136             : node;
70137     }
70138     ts.updateConstructor = updateConstructor;
70139     function createGetAccessor(decorators, modifiers, name, parameters, type, body) {
70140         var node = createSynthesizedNode(163 /* GetAccessor */);
70141         node.decorators = asNodeArray(decorators);
70142         node.modifiers = asNodeArray(modifiers);
70143         node.name = asName(name);
70144         node.typeParameters = undefined;
70145         node.parameters = createNodeArray(parameters);
70146         node.type = type;
70147         node.body = body;
70148         return node;
70149     }
70150     ts.createGetAccessor = createGetAccessor;
70151     function updateGetAccessor(node, decorators, modifiers, name, parameters, type, body) {
70152         return node.decorators !== decorators
70153             || node.modifiers !== modifiers
70154             || node.name !== name
70155             || node.parameters !== parameters
70156             || node.type !== type
70157             || node.body !== body
70158             ? updateNode(createGetAccessor(decorators, modifiers, name, parameters, type, body), node)
70159             : node;
70160     }
70161     ts.updateGetAccessor = updateGetAccessor;
70162     function createSetAccessor(decorators, modifiers, name, parameters, body) {
70163         var node = createSynthesizedNode(164 /* SetAccessor */);
70164         node.decorators = asNodeArray(decorators);
70165         node.modifiers = asNodeArray(modifiers);
70166         node.name = asName(name);
70167         node.typeParameters = undefined;
70168         node.parameters = createNodeArray(parameters);
70169         node.body = body;
70170         return node;
70171     }
70172     ts.createSetAccessor = createSetAccessor;
70173     function updateSetAccessor(node, decorators, modifiers, name, parameters, body) {
70174         return node.decorators !== decorators
70175             || node.modifiers !== modifiers
70176             || node.name !== name
70177             || node.parameters !== parameters
70178             || node.body !== body
70179             ? updateNode(createSetAccessor(decorators, modifiers, name, parameters, body), node)
70180             : node;
70181     }
70182     ts.updateSetAccessor = updateSetAccessor;
70183     function createCallSignature(typeParameters, parameters, type) {
70184         return createSignatureDeclaration(165 /* CallSignature */, typeParameters, parameters, type);
70185     }
70186     ts.createCallSignature = createCallSignature;
70187     function updateCallSignature(node, typeParameters, parameters, type) {
70188         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70189     }
70190     ts.updateCallSignature = updateCallSignature;
70191     function createConstructSignature(typeParameters, parameters, type) {
70192         return createSignatureDeclaration(166 /* ConstructSignature */, typeParameters, parameters, type);
70193     }
70194     ts.createConstructSignature = createConstructSignature;
70195     function updateConstructSignature(node, typeParameters, parameters, type) {
70196         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70197     }
70198     ts.updateConstructSignature = updateConstructSignature;
70199     function createIndexSignature(decorators, modifiers, parameters, type) {
70200         var node = createSynthesizedNode(167 /* IndexSignature */);
70201         node.decorators = asNodeArray(decorators);
70202         node.modifiers = asNodeArray(modifiers);
70203         node.parameters = createNodeArray(parameters);
70204         node.type = type;
70205         return node;
70206     }
70207     ts.createIndexSignature = createIndexSignature;
70208     function updateIndexSignature(node, decorators, modifiers, parameters, type) {
70209         return node.parameters !== parameters
70210             || node.type !== type
70211             || node.decorators !== decorators
70212             || node.modifiers !== modifiers
70213             ? updateNode(createIndexSignature(decorators, modifiers, parameters, type), node)
70214             : node;
70215     }
70216     ts.updateIndexSignature = updateIndexSignature;
70217     /* @internal */
70218     function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) {
70219         var node = createSynthesizedNode(kind);
70220         node.typeParameters = asNodeArray(typeParameters);
70221         node.parameters = asNodeArray(parameters);
70222         node.type = type;
70223         node.typeArguments = asNodeArray(typeArguments);
70224         return node;
70225     }
70226     ts.createSignatureDeclaration = createSignatureDeclaration;
70227     function updateSignatureDeclaration(node, typeParameters, parameters, type) {
70228         return node.typeParameters !== typeParameters
70229             || node.parameters !== parameters
70230             || node.type !== type
70231             ? updateNode(createSignatureDeclaration(node.kind, typeParameters, parameters, type), node)
70232             : node;
70233     }
70234     // Types
70235     function createKeywordTypeNode(kind) {
70236         return createSynthesizedNode(kind);
70237     }
70238     ts.createKeywordTypeNode = createKeywordTypeNode;
70239     function createTypePredicateNode(parameterName, type) {
70240         return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
70241     }
70242     ts.createTypePredicateNode = createTypePredicateNode;
70243     function createTypePredicateNodeWithModifier(assertsModifier, parameterName, type) {
70244         var node = createSynthesizedNode(168 /* TypePredicate */);
70245         node.assertsModifier = assertsModifier;
70246         node.parameterName = asName(parameterName);
70247         node.type = type;
70248         return node;
70249     }
70250     ts.createTypePredicateNodeWithModifier = createTypePredicateNodeWithModifier;
70251     function updateTypePredicateNode(node, parameterName, type) {
70252         return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
70253     }
70254     ts.updateTypePredicateNode = updateTypePredicateNode;
70255     function updateTypePredicateNodeWithModifier(node, assertsModifier, parameterName, type) {
70256         return node.assertsModifier !== assertsModifier
70257             || node.parameterName !== parameterName
70258             || node.type !== type
70259             ? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
70260             : node;
70261     }
70262     ts.updateTypePredicateNodeWithModifier = updateTypePredicateNodeWithModifier;
70263     function createTypeReferenceNode(typeName, typeArguments) {
70264         var node = createSynthesizedNode(169 /* TypeReference */);
70265         node.typeName = asName(typeName);
70266         node.typeArguments = typeArguments && ts.parenthesizeTypeParameters(typeArguments);
70267         return node;
70268     }
70269     ts.createTypeReferenceNode = createTypeReferenceNode;
70270     function updateTypeReferenceNode(node, typeName, typeArguments) {
70271         return node.typeName !== typeName
70272             || node.typeArguments !== typeArguments
70273             ? updateNode(createTypeReferenceNode(typeName, typeArguments), node)
70274             : node;
70275     }
70276     ts.updateTypeReferenceNode = updateTypeReferenceNode;
70277     function createFunctionTypeNode(typeParameters, parameters, type) {
70278         return createSignatureDeclaration(170 /* FunctionType */, typeParameters, parameters, type);
70279     }
70280     ts.createFunctionTypeNode = createFunctionTypeNode;
70281     function updateFunctionTypeNode(node, typeParameters, parameters, type) {
70282         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70283     }
70284     ts.updateFunctionTypeNode = updateFunctionTypeNode;
70285     function createConstructorTypeNode(typeParameters, parameters, type) {
70286         return createSignatureDeclaration(171 /* ConstructorType */, typeParameters, parameters, type);
70287     }
70288     ts.createConstructorTypeNode = createConstructorTypeNode;
70289     function updateConstructorTypeNode(node, typeParameters, parameters, type) {
70290         return updateSignatureDeclaration(node, typeParameters, parameters, type);
70291     }
70292     ts.updateConstructorTypeNode = updateConstructorTypeNode;
70293     function createTypeQueryNode(exprName) {
70294         var node = createSynthesizedNode(172 /* TypeQuery */);
70295         node.exprName = exprName;
70296         return node;
70297     }
70298     ts.createTypeQueryNode = createTypeQueryNode;
70299     function updateTypeQueryNode(node, exprName) {
70300         return node.exprName !== exprName
70301             ? updateNode(createTypeQueryNode(exprName), node)
70302             : node;
70303     }
70304     ts.updateTypeQueryNode = updateTypeQueryNode;
70305     function createTypeLiteralNode(members) {
70306         var node = createSynthesizedNode(173 /* TypeLiteral */);
70307         node.members = createNodeArray(members);
70308         return node;
70309     }
70310     ts.createTypeLiteralNode = createTypeLiteralNode;
70311     function updateTypeLiteralNode(node, members) {
70312         return node.members !== members
70313             ? updateNode(createTypeLiteralNode(members), node)
70314             : node;
70315     }
70316     ts.updateTypeLiteralNode = updateTypeLiteralNode;
70317     function createArrayTypeNode(elementType) {
70318         var node = createSynthesizedNode(174 /* ArrayType */);
70319         node.elementType = ts.parenthesizeArrayTypeMember(elementType);
70320         return node;
70321     }
70322     ts.createArrayTypeNode = createArrayTypeNode;
70323     function updateArrayTypeNode(node, elementType) {
70324         return node.elementType !== elementType
70325             ? updateNode(createArrayTypeNode(elementType), node)
70326             : node;
70327     }
70328     ts.updateArrayTypeNode = updateArrayTypeNode;
70329     function createTupleTypeNode(elementTypes) {
70330         var node = createSynthesizedNode(175 /* TupleType */);
70331         node.elementTypes = createNodeArray(elementTypes);
70332         return node;
70333     }
70334     ts.createTupleTypeNode = createTupleTypeNode;
70335     function updateTupleTypeNode(node, elementTypes) {
70336         return node.elementTypes !== elementTypes
70337             ? updateNode(createTupleTypeNode(elementTypes), node)
70338             : node;
70339     }
70340     ts.updateTupleTypeNode = updateTupleTypeNode;
70341     function createOptionalTypeNode(type) {
70342         var node = createSynthesizedNode(176 /* OptionalType */);
70343         node.type = ts.parenthesizeArrayTypeMember(type);
70344         return node;
70345     }
70346     ts.createOptionalTypeNode = createOptionalTypeNode;
70347     function updateOptionalTypeNode(node, type) {
70348         return node.type !== type
70349             ? updateNode(createOptionalTypeNode(type), node)
70350             : node;
70351     }
70352     ts.updateOptionalTypeNode = updateOptionalTypeNode;
70353     function createRestTypeNode(type) {
70354         var node = createSynthesizedNode(177 /* RestType */);
70355         node.type = type;
70356         return node;
70357     }
70358     ts.createRestTypeNode = createRestTypeNode;
70359     function updateRestTypeNode(node, type) {
70360         return node.type !== type
70361             ? updateNode(createRestTypeNode(type), node)
70362             : node;
70363     }
70364     ts.updateRestTypeNode = updateRestTypeNode;
70365     function createUnionTypeNode(types) {
70366         return createUnionOrIntersectionTypeNode(178 /* UnionType */, types);
70367     }
70368     ts.createUnionTypeNode = createUnionTypeNode;
70369     function updateUnionTypeNode(node, types) {
70370         return updateUnionOrIntersectionTypeNode(node, types);
70371     }
70372     ts.updateUnionTypeNode = updateUnionTypeNode;
70373     function createIntersectionTypeNode(types) {
70374         return createUnionOrIntersectionTypeNode(179 /* IntersectionType */, types);
70375     }
70376     ts.createIntersectionTypeNode = createIntersectionTypeNode;
70377     function updateIntersectionTypeNode(node, types) {
70378         return updateUnionOrIntersectionTypeNode(node, types);
70379     }
70380     ts.updateIntersectionTypeNode = updateIntersectionTypeNode;
70381     function createUnionOrIntersectionTypeNode(kind, types) {
70382         var node = createSynthesizedNode(kind);
70383         node.types = ts.parenthesizeElementTypeMembers(types);
70384         return node;
70385     }
70386     ts.createUnionOrIntersectionTypeNode = createUnionOrIntersectionTypeNode;
70387     function updateUnionOrIntersectionTypeNode(node, types) {
70388         return node.types !== types
70389             ? updateNode(createUnionOrIntersectionTypeNode(node.kind, types), node)
70390             : node;
70391     }
70392     function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
70393         var node = createSynthesizedNode(180 /* ConditionalType */);
70394         node.checkType = ts.parenthesizeConditionalTypeMember(checkType);
70395         node.extendsType = ts.parenthesizeConditionalTypeMember(extendsType);
70396         node.trueType = trueType;
70397         node.falseType = falseType;
70398         return node;
70399     }
70400     ts.createConditionalTypeNode = createConditionalTypeNode;
70401     function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
70402         return node.checkType !== checkType
70403             || node.extendsType !== extendsType
70404             || node.trueType !== trueType
70405             || node.falseType !== falseType
70406             ? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
70407             : node;
70408     }
70409     ts.updateConditionalTypeNode = updateConditionalTypeNode;
70410     function createInferTypeNode(typeParameter) {
70411         var node = createSynthesizedNode(181 /* InferType */);
70412         node.typeParameter = typeParameter;
70413         return node;
70414     }
70415     ts.createInferTypeNode = createInferTypeNode;
70416     function updateInferTypeNode(node, typeParameter) {
70417         return node.typeParameter !== typeParameter
70418             ? updateNode(createInferTypeNode(typeParameter), node)
70419             : node;
70420     }
70421     ts.updateInferTypeNode = updateInferTypeNode;
70422     function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
70423         var node = createSynthesizedNode(188 /* ImportType */);
70424         node.argument = argument;
70425         node.qualifier = qualifier;
70426         node.typeArguments = ts.parenthesizeTypeParameters(typeArguments);
70427         node.isTypeOf = isTypeOf;
70428         return node;
70429     }
70430     ts.createImportTypeNode = createImportTypeNode;
70431     function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
70432         return node.argument !== argument
70433             || node.qualifier !== qualifier
70434             || node.typeArguments !== typeArguments
70435             || node.isTypeOf !== isTypeOf
70436             ? updateNode(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
70437             : node;
70438     }
70439     ts.updateImportTypeNode = updateImportTypeNode;
70440     function createParenthesizedType(type) {
70441         var node = createSynthesizedNode(182 /* ParenthesizedType */);
70442         node.type = type;
70443         return node;
70444     }
70445     ts.createParenthesizedType = createParenthesizedType;
70446     function updateParenthesizedType(node, type) {
70447         return node.type !== type
70448             ? updateNode(createParenthesizedType(type), node)
70449             : node;
70450     }
70451     ts.updateParenthesizedType = updateParenthesizedType;
70452     function createThisTypeNode() {
70453         return createSynthesizedNode(183 /* ThisType */);
70454     }
70455     ts.createThisTypeNode = createThisTypeNode;
70456     function createTypeOperatorNode(operatorOrType, type) {
70457         var node = createSynthesizedNode(184 /* TypeOperator */);
70458         node.operator = typeof operatorOrType === "number" ? operatorOrType : 134 /* KeyOfKeyword */;
70459         node.type = ts.parenthesizeElementTypeMember(typeof operatorOrType === "number" ? type : operatorOrType);
70460         return node;
70461     }
70462     ts.createTypeOperatorNode = createTypeOperatorNode;
70463     function updateTypeOperatorNode(node, type) {
70464         return node.type !== type ? updateNode(createTypeOperatorNode(node.operator, type), node) : node;
70465     }
70466     ts.updateTypeOperatorNode = updateTypeOperatorNode;
70467     function createIndexedAccessTypeNode(objectType, indexType) {
70468         var node = createSynthesizedNode(185 /* IndexedAccessType */);
70469         node.objectType = ts.parenthesizeElementTypeMember(objectType);
70470         node.indexType = indexType;
70471         return node;
70472     }
70473     ts.createIndexedAccessTypeNode = createIndexedAccessTypeNode;
70474     function updateIndexedAccessTypeNode(node, objectType, indexType) {
70475         return node.objectType !== objectType
70476             || node.indexType !== indexType
70477             ? updateNode(createIndexedAccessTypeNode(objectType, indexType), node)
70478             : node;
70479     }
70480     ts.updateIndexedAccessTypeNode = updateIndexedAccessTypeNode;
70481     function createMappedTypeNode(readonlyToken, typeParameter, questionToken, type) {
70482         var node = createSynthesizedNode(186 /* MappedType */);
70483         node.readonlyToken = readonlyToken;
70484         node.typeParameter = typeParameter;
70485         node.questionToken = questionToken;
70486         node.type = type;
70487         return node;
70488     }
70489     ts.createMappedTypeNode = createMappedTypeNode;
70490     function updateMappedTypeNode(node, readonlyToken, typeParameter, questionToken, type) {
70491         return node.readonlyToken !== readonlyToken
70492             || node.typeParameter !== typeParameter
70493             || node.questionToken !== questionToken
70494             || node.type !== type
70495             ? updateNode(createMappedTypeNode(readonlyToken, typeParameter, questionToken, type), node)
70496             : node;
70497     }
70498     ts.updateMappedTypeNode = updateMappedTypeNode;
70499     function createLiteralTypeNode(literal) {
70500         var node = createSynthesizedNode(187 /* LiteralType */);
70501         node.literal = literal;
70502         return node;
70503     }
70504     ts.createLiteralTypeNode = createLiteralTypeNode;
70505     function updateLiteralTypeNode(node, literal) {
70506         return node.literal !== literal
70507             ? updateNode(createLiteralTypeNode(literal), node)
70508             : node;
70509     }
70510     ts.updateLiteralTypeNode = updateLiteralTypeNode;
70511     // Binding Patterns
70512     function createObjectBindingPattern(elements) {
70513         var node = createSynthesizedNode(189 /* ObjectBindingPattern */);
70514         node.elements = createNodeArray(elements);
70515         return node;
70516     }
70517     ts.createObjectBindingPattern = createObjectBindingPattern;
70518     function updateObjectBindingPattern(node, elements) {
70519         return node.elements !== elements
70520             ? updateNode(createObjectBindingPattern(elements), node)
70521             : node;
70522     }
70523     ts.updateObjectBindingPattern = updateObjectBindingPattern;
70524     function createArrayBindingPattern(elements) {
70525         var node = createSynthesizedNode(190 /* ArrayBindingPattern */);
70526         node.elements = createNodeArray(elements);
70527         return node;
70528     }
70529     ts.createArrayBindingPattern = createArrayBindingPattern;
70530     function updateArrayBindingPattern(node, elements) {
70531         return node.elements !== elements
70532             ? updateNode(createArrayBindingPattern(elements), node)
70533             : node;
70534     }
70535     ts.updateArrayBindingPattern = updateArrayBindingPattern;
70536     function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
70537         var node = createSynthesizedNode(191 /* BindingElement */);
70538         node.dotDotDotToken = dotDotDotToken;
70539         node.propertyName = asName(propertyName);
70540         node.name = asName(name);
70541         node.initializer = initializer;
70542         return node;
70543     }
70544     ts.createBindingElement = createBindingElement;
70545     function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
70546         return node.propertyName !== propertyName
70547             || node.dotDotDotToken !== dotDotDotToken
70548             || node.name !== name
70549             || node.initializer !== initializer
70550             ? updateNode(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
70551             : node;
70552     }
70553     ts.updateBindingElement = updateBindingElement;
70554     // Expression
70555     function createArrayLiteral(elements, multiLine) {
70556         var node = createSynthesizedNode(192 /* ArrayLiteralExpression */);
70557         node.elements = ts.parenthesizeListElements(createNodeArray(elements));
70558         if (multiLine)
70559             node.multiLine = true;
70560         return node;
70561     }
70562     ts.createArrayLiteral = createArrayLiteral;
70563     function updateArrayLiteral(node, elements) {
70564         return node.elements !== elements
70565             ? updateNode(createArrayLiteral(elements, node.multiLine), node)
70566             : node;
70567     }
70568     ts.updateArrayLiteral = updateArrayLiteral;
70569     function createObjectLiteral(properties, multiLine) {
70570         var node = createSynthesizedNode(193 /* ObjectLiteralExpression */);
70571         node.properties = createNodeArray(properties);
70572         if (multiLine)
70573             node.multiLine = true;
70574         return node;
70575     }
70576     ts.createObjectLiteral = createObjectLiteral;
70577     function updateObjectLiteral(node, properties) {
70578         return node.properties !== properties
70579             ? updateNode(createObjectLiteral(properties, node.multiLine), node)
70580             : node;
70581     }
70582     ts.updateObjectLiteral = updateObjectLiteral;
70583     function createPropertyAccess(expression, name) {
70584         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70585         node.expression = ts.parenthesizeForAccess(expression);
70586         node.name = asName(name);
70587         setEmitFlags(node, 131072 /* NoIndentation */);
70588         return node;
70589     }
70590     ts.createPropertyAccess = createPropertyAccess;
70591     function updatePropertyAccess(node, expression, name) {
70592         if (ts.isPropertyAccessChain(node)) {
70593             return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
70594         }
70595         // Because we are updating existed propertyAccess we want to inherit its emitFlags
70596         // instead of using the default from createPropertyAccess
70597         return node.expression !== expression
70598             || node.name !== name
70599             ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node)
70600             : node;
70601     }
70602     ts.updatePropertyAccess = updatePropertyAccess;
70603     function createPropertyAccessChain(expression, questionDotToken, name) {
70604         var node = createSynthesizedNode(194 /* PropertyAccessExpression */);
70605         node.flags |= 32 /* OptionalChain */;
70606         node.expression = ts.parenthesizeForAccess(expression);
70607         node.questionDotToken = questionDotToken;
70608         node.name = asName(name);
70609         setEmitFlags(node, 131072 /* NoIndentation */);
70610         return node;
70611     }
70612     ts.createPropertyAccessChain = createPropertyAccessChain;
70613     function updatePropertyAccessChain(node, expression, questionDotToken, name) {
70614         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
70615         // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
70616         // instead of using the default from createPropertyAccess
70617         return node.expression !== expression
70618             || node.questionDotToken !== questionDotToken
70619             || node.name !== name
70620             ? updateNode(setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), ts.getEmitFlags(node)), node)
70621             : node;
70622     }
70623     ts.updatePropertyAccessChain = updatePropertyAccessChain;
70624     function createElementAccess(expression, index) {
70625         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70626         node.expression = ts.parenthesizeForAccess(expression);
70627         node.argumentExpression = asExpression(index);
70628         return node;
70629     }
70630     ts.createElementAccess = createElementAccess;
70631     function updateElementAccess(node, expression, argumentExpression) {
70632         if (ts.isOptionalChain(node)) {
70633             return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
70634         }
70635         return node.expression !== expression
70636             || node.argumentExpression !== argumentExpression
70637             ? updateNode(createElementAccess(expression, argumentExpression), node)
70638             : node;
70639     }
70640     ts.updateElementAccess = updateElementAccess;
70641     function createElementAccessChain(expression, questionDotToken, index) {
70642         var node = createSynthesizedNode(195 /* ElementAccessExpression */);
70643         node.flags |= 32 /* OptionalChain */;
70644         node.expression = ts.parenthesizeForAccess(expression);
70645         node.questionDotToken = questionDotToken;
70646         node.argumentExpression = asExpression(index);
70647         return node;
70648     }
70649     ts.createElementAccessChain = createElementAccessChain;
70650     function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
70651         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
70652         return node.expression !== expression
70653             || node.questionDotToken !== questionDotToken
70654             || node.argumentExpression !== argumentExpression
70655             ? updateNode(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
70656             : node;
70657     }
70658     ts.updateElementAccessChain = updateElementAccessChain;
70659     function createCall(expression, typeArguments, argumentsArray) {
70660         var node = createSynthesizedNode(196 /* CallExpression */);
70661         node.expression = ts.parenthesizeForAccess(expression);
70662         node.typeArguments = asNodeArray(typeArguments);
70663         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70664         return node;
70665     }
70666     ts.createCall = createCall;
70667     function updateCall(node, expression, typeArguments, argumentsArray) {
70668         if (ts.isOptionalChain(node)) {
70669             return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
70670         }
70671         return node.expression !== expression
70672             || node.typeArguments !== typeArguments
70673             || node.arguments !== argumentsArray
70674             ? updateNode(createCall(expression, typeArguments, argumentsArray), node)
70675             : node;
70676     }
70677     ts.updateCall = updateCall;
70678     function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
70679         var node = createSynthesizedNode(196 /* CallExpression */);
70680         node.flags |= 32 /* OptionalChain */;
70681         node.expression = ts.parenthesizeForAccess(expression);
70682         node.questionDotToken = questionDotToken;
70683         node.typeArguments = asNodeArray(typeArguments);
70684         node.arguments = ts.parenthesizeListElements(createNodeArray(argumentsArray));
70685         return node;
70686     }
70687     ts.createCallChain = createCallChain;
70688     function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
70689         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
70690         return node.expression !== expression
70691             || node.questionDotToken !== questionDotToken
70692             || node.typeArguments !== typeArguments
70693             || node.arguments !== argumentsArray
70694             ? updateNode(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
70695             : node;
70696     }
70697     ts.updateCallChain = updateCallChain;
70698     function createNew(expression, typeArguments, argumentsArray) {
70699         var node = createSynthesizedNode(197 /* NewExpression */);
70700         node.expression = ts.parenthesizeForNew(expression);
70701         node.typeArguments = asNodeArray(typeArguments);
70702         node.arguments = argumentsArray ? ts.parenthesizeListElements(createNodeArray(argumentsArray)) : undefined;
70703         return node;
70704     }
70705     ts.createNew = createNew;
70706     function updateNew(node, expression, typeArguments, argumentsArray) {
70707         return node.expression !== expression
70708             || node.typeArguments !== typeArguments
70709             || node.arguments !== argumentsArray
70710             ? updateNode(createNew(expression, typeArguments, argumentsArray), node)
70711             : node;
70712     }
70713     ts.updateNew = updateNew;
70714     function createTaggedTemplate(tag, typeArgumentsOrTemplate, template) {
70715         var node = createSynthesizedNode(198 /* TaggedTemplateExpression */);
70716         node.tag = ts.parenthesizeForAccess(tag);
70717         if (template) {
70718             node.typeArguments = asNodeArray(typeArgumentsOrTemplate);
70719             node.template = template;
70720         }
70721         else {
70722             node.typeArguments = undefined;
70723             node.template = typeArgumentsOrTemplate;
70724         }
70725         return node;
70726     }
70727     ts.createTaggedTemplate = createTaggedTemplate;
70728     function updateTaggedTemplate(node, tag, typeArgumentsOrTemplate, template) {
70729         return node.tag !== tag
70730             || (template
70731                 ? node.typeArguments !== typeArgumentsOrTemplate || node.template !== template
70732                 : node.typeArguments !== undefined || node.template !== typeArgumentsOrTemplate)
70733             ? updateNode(createTaggedTemplate(tag, typeArgumentsOrTemplate, template), node)
70734             : node;
70735     }
70736     ts.updateTaggedTemplate = updateTaggedTemplate;
70737     function createTypeAssertion(type, expression) {
70738         var node = createSynthesizedNode(199 /* TypeAssertionExpression */);
70739         node.type = type;
70740         node.expression = ts.parenthesizePrefixOperand(expression);
70741         return node;
70742     }
70743     ts.createTypeAssertion = createTypeAssertion;
70744     function updateTypeAssertion(node, type, expression) {
70745         return node.type !== type
70746             || node.expression !== expression
70747             ? updateNode(createTypeAssertion(type, expression), node)
70748             : node;
70749     }
70750     ts.updateTypeAssertion = updateTypeAssertion;
70751     function createParen(expression) {
70752         var node = createSynthesizedNode(200 /* ParenthesizedExpression */);
70753         node.expression = expression;
70754         return node;
70755     }
70756     ts.createParen = createParen;
70757     function updateParen(node, expression) {
70758         return node.expression !== expression
70759             ? updateNode(createParen(expression), node)
70760             : node;
70761     }
70762     ts.updateParen = updateParen;
70763     function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70764         var node = createSynthesizedNode(201 /* FunctionExpression */);
70765         node.modifiers = asNodeArray(modifiers);
70766         node.asteriskToken = asteriskToken;
70767         node.name = asName(name);
70768         node.typeParameters = asNodeArray(typeParameters);
70769         node.parameters = createNodeArray(parameters);
70770         node.type = type;
70771         node.body = body;
70772         return node;
70773     }
70774     ts.createFunctionExpression = createFunctionExpression;
70775     function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
70776         return node.name !== name
70777             || node.modifiers !== modifiers
70778             || node.asteriskToken !== asteriskToken
70779             || node.typeParameters !== typeParameters
70780             || node.parameters !== parameters
70781             || node.type !== type
70782             || node.body !== body
70783             ? updateNode(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
70784             : node;
70785     }
70786     ts.updateFunctionExpression = updateFunctionExpression;
70787     function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70788         var node = createSynthesizedNode(202 /* ArrowFunction */);
70789         node.modifiers = asNodeArray(modifiers);
70790         node.typeParameters = asNodeArray(typeParameters);
70791         node.parameters = createNodeArray(parameters);
70792         node.type = type;
70793         node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(38 /* EqualsGreaterThanToken */);
70794         node.body = ts.parenthesizeConciseBody(body);
70795         return node;
70796     }
70797     ts.createArrowFunction = createArrowFunction;
70798     function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
70799         return node.modifiers !== modifiers
70800             || node.typeParameters !== typeParameters
70801             || node.parameters !== parameters
70802             || node.type !== type
70803             || node.equalsGreaterThanToken !== equalsGreaterThanToken
70804             || node.body !== body
70805             ? updateNode(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
70806             : node;
70807     }
70808     ts.updateArrowFunction = updateArrowFunction;
70809     function createDelete(expression) {
70810         var node = createSynthesizedNode(203 /* DeleteExpression */);
70811         node.expression = ts.parenthesizePrefixOperand(expression);
70812         return node;
70813     }
70814     ts.createDelete = createDelete;
70815     function updateDelete(node, expression) {
70816         return node.expression !== expression
70817             ? updateNode(createDelete(expression), node)
70818             : node;
70819     }
70820     ts.updateDelete = updateDelete;
70821     function createTypeOf(expression) {
70822         var node = createSynthesizedNode(204 /* TypeOfExpression */);
70823         node.expression = ts.parenthesizePrefixOperand(expression);
70824         return node;
70825     }
70826     ts.createTypeOf = createTypeOf;
70827     function updateTypeOf(node, expression) {
70828         return node.expression !== expression
70829             ? updateNode(createTypeOf(expression), node)
70830             : node;
70831     }
70832     ts.updateTypeOf = updateTypeOf;
70833     function createVoid(expression) {
70834         var node = createSynthesizedNode(205 /* VoidExpression */);
70835         node.expression = ts.parenthesizePrefixOperand(expression);
70836         return node;
70837     }
70838     ts.createVoid = createVoid;
70839     function updateVoid(node, expression) {
70840         return node.expression !== expression
70841             ? updateNode(createVoid(expression), node)
70842             : node;
70843     }
70844     ts.updateVoid = updateVoid;
70845     function createAwait(expression) {
70846         var node = createSynthesizedNode(206 /* AwaitExpression */);
70847         node.expression = ts.parenthesizePrefixOperand(expression);
70848         return node;
70849     }
70850     ts.createAwait = createAwait;
70851     function updateAwait(node, expression) {
70852         return node.expression !== expression
70853             ? updateNode(createAwait(expression), node)
70854             : node;
70855     }
70856     ts.updateAwait = updateAwait;
70857     function createPrefix(operator, operand) {
70858         var node = createSynthesizedNode(207 /* PrefixUnaryExpression */);
70859         node.operator = operator;
70860         node.operand = ts.parenthesizePrefixOperand(operand);
70861         return node;
70862     }
70863     ts.createPrefix = createPrefix;
70864     function updatePrefix(node, operand) {
70865         return node.operand !== operand
70866             ? updateNode(createPrefix(node.operator, operand), node)
70867             : node;
70868     }
70869     ts.updatePrefix = updatePrefix;
70870     function createPostfix(operand, operator) {
70871         var node = createSynthesizedNode(208 /* PostfixUnaryExpression */);
70872         node.operand = ts.parenthesizePostfixOperand(operand);
70873         node.operator = operator;
70874         return node;
70875     }
70876     ts.createPostfix = createPostfix;
70877     function updatePostfix(node, operand) {
70878         return node.operand !== operand
70879             ? updateNode(createPostfix(operand, node.operator), node)
70880             : node;
70881     }
70882     ts.updatePostfix = updatePostfix;
70883     function createBinary(left, operator, right) {
70884         var node = createSynthesizedNode(209 /* BinaryExpression */);
70885         var operatorToken = asToken(operator);
70886         var operatorKind = operatorToken.kind;
70887         node.left = ts.parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined);
70888         node.operatorToken = operatorToken;
70889         node.right = ts.parenthesizeBinaryOperand(operatorKind, right, /*isLeftSideOfBinary*/ false, node.left);
70890         return node;
70891     }
70892     ts.createBinary = createBinary;
70893     function updateBinary(node, left, right, operator) {
70894         return node.left !== left
70895             || node.right !== right
70896             ? updateNode(createBinary(left, operator || node.operatorToken, right), node)
70897             : node;
70898     }
70899     ts.updateBinary = updateBinary;
70900     function createConditional(condition, questionTokenOrWhenTrue, whenTrueOrWhenFalse, colonToken, whenFalse) {
70901         var node = createSynthesizedNode(210 /* ConditionalExpression */);
70902         node.condition = ts.parenthesizeForConditionalHead(condition);
70903         node.questionToken = whenFalse ? questionTokenOrWhenTrue : createToken(57 /* QuestionToken */);
70904         node.whenTrue = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenTrueOrWhenFalse : questionTokenOrWhenTrue);
70905         node.colonToken = whenFalse ? colonToken : createToken(58 /* ColonToken */);
70906         node.whenFalse = ts.parenthesizeSubexpressionOfConditionalExpression(whenFalse ? whenFalse : whenTrueOrWhenFalse);
70907         return node;
70908     }
70909     ts.createConditional = createConditional;
70910     function updateConditional(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
70911         return node.condition !== condition
70912             || node.questionToken !== questionToken
70913             || node.whenTrue !== whenTrue
70914             || node.colonToken !== colonToken
70915             || node.whenFalse !== whenFalse
70916             ? updateNode(createConditional(condition, questionToken, whenTrue, colonToken, whenFalse), node)
70917             : node;
70918     }
70919     ts.updateConditional = updateConditional;
70920     function createTemplateExpression(head, templateSpans) {
70921         var node = createSynthesizedNode(211 /* TemplateExpression */);
70922         node.head = head;
70923         node.templateSpans = createNodeArray(templateSpans);
70924         return node;
70925     }
70926     ts.createTemplateExpression = createTemplateExpression;
70927     function updateTemplateExpression(node, head, templateSpans) {
70928         return node.head !== head
70929             || node.templateSpans !== templateSpans
70930             ? updateNode(createTemplateExpression(head, templateSpans), node)
70931             : node;
70932     }
70933     ts.updateTemplateExpression = updateTemplateExpression;
70934     var rawTextScanner;
70935     var invalidValueSentinel = {};
70936     function getCookedText(kind, rawText) {
70937         if (!rawTextScanner) {
70938             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
70939         }
70940         switch (kind) {
70941             case 14 /* NoSubstitutionTemplateLiteral */:
70942                 rawTextScanner.setText("`" + rawText + "`");
70943                 break;
70944             case 15 /* TemplateHead */:
70945                 rawTextScanner.setText("`" + rawText + "${");
70946                 break;
70947             case 16 /* TemplateMiddle */:
70948                 rawTextScanner.setText("}" + rawText + "${");
70949                 break;
70950             case 17 /* TemplateTail */:
70951                 rawTextScanner.setText("}" + rawText + "`");
70952                 break;
70953         }
70954         var token = rawTextScanner.scan();
70955         if (token === 23 /* CloseBracketToken */) {
70956             token = rawTextScanner.reScanTemplateToken(/* isTaggedTemplate */ false);
70957         }
70958         if (rawTextScanner.isUnterminated()) {
70959             rawTextScanner.setText(undefined);
70960             return invalidValueSentinel;
70961         }
70962         var tokenValue;
70963         switch (token) {
70964             case 14 /* NoSubstitutionTemplateLiteral */:
70965             case 15 /* TemplateHead */:
70966             case 16 /* TemplateMiddle */:
70967             case 17 /* TemplateTail */:
70968                 tokenValue = rawTextScanner.getTokenValue();
70969                 break;
70970         }
70971         if (rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
70972             rawTextScanner.setText(undefined);
70973             return invalidValueSentinel;
70974         }
70975         rawTextScanner.setText(undefined);
70976         return tokenValue;
70977     }
70978     function createTemplateLiteralLikeNode(kind, text, rawText) {
70979         var node = createSynthesizedNode(kind);
70980         node.text = text;
70981         if (rawText === undefined || text === rawText) {
70982             node.rawText = rawText;
70983         }
70984         else {
70985             var cooked = getCookedText(kind, rawText);
70986             if (typeof cooked === "object") {
70987                 return ts.Debug.fail("Invalid raw text");
70988             }
70989             ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
70990             node.rawText = rawText;
70991         }
70992         return node;
70993     }
70994     function createTemplateHead(text, rawText) {
70995         var node = createTemplateLiteralLikeNode(15 /* TemplateHead */, text, rawText);
70996         node.text = text;
70997         return node;
70998     }
70999     ts.createTemplateHead = createTemplateHead;
71000     function createTemplateMiddle(text, rawText) {
71001         var node = createTemplateLiteralLikeNode(16 /* TemplateMiddle */, text, rawText);
71002         node.text = text;
71003         return node;
71004     }
71005     ts.createTemplateMiddle = createTemplateMiddle;
71006     function createTemplateTail(text, rawText) {
71007         var node = createTemplateLiteralLikeNode(17 /* TemplateTail */, text, rawText);
71008         node.text = text;
71009         return node;
71010     }
71011     ts.createTemplateTail = createTemplateTail;
71012     function createNoSubstitutionTemplateLiteral(text, rawText) {
71013         var node = createTemplateLiteralLikeNode(14 /* NoSubstitutionTemplateLiteral */, text, rawText);
71014         return node;
71015     }
71016     ts.createNoSubstitutionTemplateLiteral = createNoSubstitutionTemplateLiteral;
71017     function createYield(asteriskTokenOrExpression, expression) {
71018         var asteriskToken = asteriskTokenOrExpression && asteriskTokenOrExpression.kind === 41 /* AsteriskToken */ ? asteriskTokenOrExpression : undefined;
71019         expression = asteriskTokenOrExpression && asteriskTokenOrExpression.kind !== 41 /* AsteriskToken */ ? asteriskTokenOrExpression : expression;
71020         var node = createSynthesizedNode(212 /* YieldExpression */);
71021         node.asteriskToken = asteriskToken;
71022         node.expression = expression && ts.parenthesizeExpressionForList(expression);
71023         return node;
71024     }
71025     ts.createYield = createYield;
71026     function updateYield(node, asteriskToken, expression) {
71027         return node.expression !== expression
71028             || node.asteriskToken !== asteriskToken
71029             ? updateNode(createYield(asteriskToken, expression), node)
71030             : node;
71031     }
71032     ts.updateYield = updateYield;
71033     function createSpread(expression) {
71034         var node = createSynthesizedNode(213 /* SpreadElement */);
71035         node.expression = ts.parenthesizeExpressionForList(expression);
71036         return node;
71037     }
71038     ts.createSpread = createSpread;
71039     function updateSpread(node, expression) {
71040         return node.expression !== expression
71041             ? updateNode(createSpread(expression), node)
71042             : node;
71043     }
71044     ts.updateSpread = updateSpread;
71045     function createClassExpression(modifiers, name, typeParameters, heritageClauses, members) {
71046         var node = createSynthesizedNode(214 /* ClassExpression */);
71047         node.decorators = undefined;
71048         node.modifiers = asNodeArray(modifiers);
71049         node.name = asName(name);
71050         node.typeParameters = asNodeArray(typeParameters);
71051         node.heritageClauses = asNodeArray(heritageClauses);
71052         node.members = createNodeArray(members);
71053         return node;
71054     }
71055     ts.createClassExpression = createClassExpression;
71056     function updateClassExpression(node, modifiers, name, typeParameters, heritageClauses, members) {
71057         return node.modifiers !== modifiers
71058             || node.name !== name
71059             || node.typeParameters !== typeParameters
71060             || node.heritageClauses !== heritageClauses
71061             || node.members !== members
71062             ? updateNode(createClassExpression(modifiers, name, typeParameters, heritageClauses, members), node)
71063             : node;
71064     }
71065     ts.updateClassExpression = updateClassExpression;
71066     function createOmittedExpression() {
71067         return createSynthesizedNode(215 /* OmittedExpression */);
71068     }
71069     ts.createOmittedExpression = createOmittedExpression;
71070     function createExpressionWithTypeArguments(typeArguments, expression) {
71071         var node = createSynthesizedNode(216 /* ExpressionWithTypeArguments */);
71072         node.expression = ts.parenthesizeForAccess(expression);
71073         node.typeArguments = asNodeArray(typeArguments);
71074         return node;
71075     }
71076     ts.createExpressionWithTypeArguments = createExpressionWithTypeArguments;
71077     function updateExpressionWithTypeArguments(node, typeArguments, expression) {
71078         return node.typeArguments !== typeArguments
71079             || node.expression !== expression
71080             ? updateNode(createExpressionWithTypeArguments(typeArguments, expression), node)
71081             : node;
71082     }
71083     ts.updateExpressionWithTypeArguments = updateExpressionWithTypeArguments;
71084     function createAsExpression(expression, type) {
71085         var node = createSynthesizedNode(217 /* AsExpression */);
71086         node.expression = expression;
71087         node.type = type;
71088         return node;
71089     }
71090     ts.createAsExpression = createAsExpression;
71091     function updateAsExpression(node, expression, type) {
71092         return node.expression !== expression
71093             || node.type !== type
71094             ? updateNode(createAsExpression(expression, type), node)
71095             : node;
71096     }
71097     ts.updateAsExpression = updateAsExpression;
71098     function createNonNullExpression(expression) {
71099         var node = createSynthesizedNode(218 /* NonNullExpression */);
71100         node.expression = ts.parenthesizeForAccess(expression);
71101         return node;
71102     }
71103     ts.createNonNullExpression = createNonNullExpression;
71104     function updateNonNullExpression(node, expression) {
71105         if (ts.isNonNullChain(node)) {
71106             return updateNonNullChain(node, expression);
71107         }
71108         return node.expression !== expression
71109             ? updateNode(createNonNullExpression(expression), node)
71110             : node;
71111     }
71112     ts.updateNonNullExpression = updateNonNullExpression;
71113     function createNonNullChain(expression) {
71114         var node = createSynthesizedNode(218 /* NonNullExpression */);
71115         node.flags |= 32 /* OptionalChain */;
71116         node.expression = ts.parenthesizeForAccess(expression);
71117         return node;
71118     }
71119     ts.createNonNullChain = createNonNullChain;
71120     function updateNonNullChain(node, expression) {
71121         ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
71122         return node.expression !== expression
71123             ? updateNode(createNonNullChain(expression), node)
71124             : node;
71125     }
71126     ts.updateNonNullChain = updateNonNullChain;
71127     function createMetaProperty(keywordToken, name) {
71128         var node = createSynthesizedNode(219 /* MetaProperty */);
71129         node.keywordToken = keywordToken;
71130         node.name = name;
71131         return node;
71132     }
71133     ts.createMetaProperty = createMetaProperty;
71134     function updateMetaProperty(node, name) {
71135         return node.name !== name
71136             ? updateNode(createMetaProperty(node.keywordToken, name), node)
71137             : node;
71138     }
71139     ts.updateMetaProperty = updateMetaProperty;
71140     // Misc
71141     function createTemplateSpan(expression, literal) {
71142         var node = createSynthesizedNode(221 /* TemplateSpan */);
71143         node.expression = expression;
71144         node.literal = literal;
71145         return node;
71146     }
71147     ts.createTemplateSpan = createTemplateSpan;
71148     function updateTemplateSpan(node, expression, literal) {
71149         return node.expression !== expression
71150             || node.literal !== literal
71151             ? updateNode(createTemplateSpan(expression, literal), node)
71152             : node;
71153     }
71154     ts.updateTemplateSpan = updateTemplateSpan;
71155     function createSemicolonClassElement() {
71156         return createSynthesizedNode(222 /* SemicolonClassElement */);
71157     }
71158     ts.createSemicolonClassElement = createSemicolonClassElement;
71159     // Element
71160     function createBlock(statements, multiLine) {
71161         var block = createSynthesizedNode(223 /* Block */);
71162         block.statements = createNodeArray(statements);
71163         if (multiLine)
71164             block.multiLine = multiLine;
71165         return block;
71166     }
71167     ts.createBlock = createBlock;
71168     function updateBlock(node, statements) {
71169         return node.statements !== statements
71170             ? updateNode(createBlock(statements, node.multiLine), node)
71171             : node;
71172     }
71173     ts.updateBlock = updateBlock;
71174     function createVariableStatement(modifiers, declarationList) {
71175         var node = createSynthesizedNode(225 /* VariableStatement */);
71176         node.decorators = undefined;
71177         node.modifiers = asNodeArray(modifiers);
71178         node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
71179         return node;
71180     }
71181     ts.createVariableStatement = createVariableStatement;
71182     function updateVariableStatement(node, modifiers, declarationList) {
71183         return node.modifiers !== modifiers
71184             || node.declarationList !== declarationList
71185             ? updateNode(createVariableStatement(modifiers, declarationList), node)
71186             : node;
71187     }
71188     ts.updateVariableStatement = updateVariableStatement;
71189     function createEmptyStatement() {
71190         return createSynthesizedNode(224 /* EmptyStatement */);
71191     }
71192     ts.createEmptyStatement = createEmptyStatement;
71193     function createExpressionStatement(expression) {
71194         var node = createSynthesizedNode(226 /* ExpressionStatement */);
71195         node.expression = ts.parenthesizeExpressionForExpressionStatement(expression);
71196         return node;
71197     }
71198     ts.createExpressionStatement = createExpressionStatement;
71199     function updateExpressionStatement(node, expression) {
71200         return node.expression !== expression
71201             ? updateNode(createExpressionStatement(expression), node)
71202             : node;
71203     }
71204     ts.updateExpressionStatement = updateExpressionStatement;
71205     /** @deprecated Use `createExpressionStatement` instead.  */
71206     ts.createStatement = createExpressionStatement;
71207     /** @deprecated Use `updateExpressionStatement` instead.  */
71208     ts.updateStatement = updateExpressionStatement;
71209     function createIf(expression, thenStatement, elseStatement) {
71210         var node = createSynthesizedNode(227 /* IfStatement */);
71211         node.expression = expression;
71212         node.thenStatement = asEmbeddedStatement(thenStatement);
71213         node.elseStatement = asEmbeddedStatement(elseStatement);
71214         return node;
71215     }
71216     ts.createIf = createIf;
71217     function updateIf(node, expression, thenStatement, elseStatement) {
71218         return node.expression !== expression
71219             || node.thenStatement !== thenStatement
71220             || node.elseStatement !== elseStatement
71221             ? updateNode(createIf(expression, thenStatement, elseStatement), node)
71222             : node;
71223     }
71224     ts.updateIf = updateIf;
71225     function createDo(statement, expression) {
71226         var node = createSynthesizedNode(228 /* DoStatement */);
71227         node.statement = asEmbeddedStatement(statement);
71228         node.expression = expression;
71229         return node;
71230     }
71231     ts.createDo = createDo;
71232     function updateDo(node, statement, expression) {
71233         return node.statement !== statement
71234             || node.expression !== expression
71235             ? updateNode(createDo(statement, expression), node)
71236             : node;
71237     }
71238     ts.updateDo = updateDo;
71239     function createWhile(expression, statement) {
71240         var node = createSynthesizedNode(229 /* WhileStatement */);
71241         node.expression = expression;
71242         node.statement = asEmbeddedStatement(statement);
71243         return node;
71244     }
71245     ts.createWhile = createWhile;
71246     function updateWhile(node, expression, statement) {
71247         return node.expression !== expression
71248             || node.statement !== statement
71249             ? updateNode(createWhile(expression, statement), node)
71250             : node;
71251     }
71252     ts.updateWhile = updateWhile;
71253     function createFor(initializer, condition, incrementor, statement) {
71254         var node = createSynthesizedNode(230 /* ForStatement */);
71255         node.initializer = initializer;
71256         node.condition = condition;
71257         node.incrementor = incrementor;
71258         node.statement = asEmbeddedStatement(statement);
71259         return node;
71260     }
71261     ts.createFor = createFor;
71262     function updateFor(node, initializer, condition, incrementor, statement) {
71263         return node.initializer !== initializer
71264             || node.condition !== condition
71265             || node.incrementor !== incrementor
71266             || node.statement !== statement
71267             ? updateNode(createFor(initializer, condition, incrementor, statement), node)
71268             : node;
71269     }
71270     ts.updateFor = updateFor;
71271     function createForIn(initializer, expression, statement) {
71272         var node = createSynthesizedNode(231 /* ForInStatement */);
71273         node.initializer = initializer;
71274         node.expression = expression;
71275         node.statement = asEmbeddedStatement(statement);
71276         return node;
71277     }
71278     ts.createForIn = createForIn;
71279     function updateForIn(node, initializer, expression, statement) {
71280         return node.initializer !== initializer
71281             || node.expression !== expression
71282             || node.statement !== statement
71283             ? updateNode(createForIn(initializer, expression, statement), node)
71284             : node;
71285     }
71286     ts.updateForIn = updateForIn;
71287     function createForOf(awaitModifier, initializer, expression, statement) {
71288         var node = createSynthesizedNode(232 /* ForOfStatement */);
71289         node.awaitModifier = awaitModifier;
71290         node.initializer = initializer;
71291         node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression;
71292         node.statement = asEmbeddedStatement(statement);
71293         return node;
71294     }
71295     ts.createForOf = createForOf;
71296     function updateForOf(node, awaitModifier, initializer, expression, statement) {
71297         return node.awaitModifier !== awaitModifier
71298             || node.initializer !== initializer
71299             || node.expression !== expression
71300             || node.statement !== statement
71301             ? updateNode(createForOf(awaitModifier, initializer, expression, statement), node)
71302             : node;
71303     }
71304     ts.updateForOf = updateForOf;
71305     function createContinue(label) {
71306         var node = createSynthesizedNode(233 /* ContinueStatement */);
71307         node.label = asName(label);
71308         return node;
71309     }
71310     ts.createContinue = createContinue;
71311     function updateContinue(node, label) {
71312         return node.label !== label
71313             ? updateNode(createContinue(label), node)
71314             : node;
71315     }
71316     ts.updateContinue = updateContinue;
71317     function createBreak(label) {
71318         var node = createSynthesizedNode(234 /* BreakStatement */);
71319         node.label = asName(label);
71320         return node;
71321     }
71322     ts.createBreak = createBreak;
71323     function updateBreak(node, label) {
71324         return node.label !== label
71325             ? updateNode(createBreak(label), node)
71326             : node;
71327     }
71328     ts.updateBreak = updateBreak;
71329     function createReturn(expression) {
71330         var node = createSynthesizedNode(235 /* ReturnStatement */);
71331         node.expression = expression;
71332         return node;
71333     }
71334     ts.createReturn = createReturn;
71335     function updateReturn(node, expression) {
71336         return node.expression !== expression
71337             ? updateNode(createReturn(expression), node)
71338             : node;
71339     }
71340     ts.updateReturn = updateReturn;
71341     function createWith(expression, statement) {
71342         var node = createSynthesizedNode(236 /* WithStatement */);
71343         node.expression = expression;
71344         node.statement = asEmbeddedStatement(statement);
71345         return node;
71346     }
71347     ts.createWith = createWith;
71348     function updateWith(node, expression, statement) {
71349         return node.expression !== expression
71350             || node.statement !== statement
71351             ? updateNode(createWith(expression, statement), node)
71352             : node;
71353     }
71354     ts.updateWith = updateWith;
71355     function createSwitch(expression, caseBlock) {
71356         var node = createSynthesizedNode(237 /* SwitchStatement */);
71357         node.expression = ts.parenthesizeExpressionForList(expression);
71358         node.caseBlock = caseBlock;
71359         return node;
71360     }
71361     ts.createSwitch = createSwitch;
71362     function updateSwitch(node, expression, caseBlock) {
71363         return node.expression !== expression
71364             || node.caseBlock !== caseBlock
71365             ? updateNode(createSwitch(expression, caseBlock), node)
71366             : node;
71367     }
71368     ts.updateSwitch = updateSwitch;
71369     function createLabel(label, statement) {
71370         var node = createSynthesizedNode(238 /* LabeledStatement */);
71371         node.label = asName(label);
71372         node.statement = asEmbeddedStatement(statement);
71373         return node;
71374     }
71375     ts.createLabel = createLabel;
71376     function updateLabel(node, label, statement) {
71377         return node.label !== label
71378             || node.statement !== statement
71379             ? updateNode(createLabel(label, statement), node)
71380             : node;
71381     }
71382     ts.updateLabel = updateLabel;
71383     function createThrow(expression) {
71384         var node = createSynthesizedNode(239 /* ThrowStatement */);
71385         node.expression = expression;
71386         return node;
71387     }
71388     ts.createThrow = createThrow;
71389     function updateThrow(node, expression) {
71390         return node.expression !== expression
71391             ? updateNode(createThrow(expression), node)
71392             : node;
71393     }
71394     ts.updateThrow = updateThrow;
71395     function createTry(tryBlock, catchClause, finallyBlock) {
71396         var node = createSynthesizedNode(240 /* TryStatement */);
71397         node.tryBlock = tryBlock;
71398         node.catchClause = catchClause;
71399         node.finallyBlock = finallyBlock;
71400         return node;
71401     }
71402     ts.createTry = createTry;
71403     function updateTry(node, tryBlock, catchClause, finallyBlock) {
71404         return node.tryBlock !== tryBlock
71405             || node.catchClause !== catchClause
71406             || node.finallyBlock !== finallyBlock
71407             ? updateNode(createTry(tryBlock, catchClause, finallyBlock), node)
71408             : node;
71409     }
71410     ts.updateTry = updateTry;
71411     function createDebuggerStatement() {
71412         return createSynthesizedNode(241 /* DebuggerStatement */);
71413     }
71414     ts.createDebuggerStatement = createDebuggerStatement;
71415     function createVariableDeclaration(name, type, initializer) {
71416         /* Internally, one should probably use createTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71417         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71418         node.name = asName(name);
71419         node.type = type;
71420         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71421         return node;
71422     }
71423     ts.createVariableDeclaration = createVariableDeclaration;
71424     function updateVariableDeclaration(node, name, type, initializer) {
71425         /* Internally, one should probably use updateTypeScriptVariableDeclaration instead and handle definite assignment assertions */
71426         return node.name !== name
71427             || node.type !== type
71428             || node.initializer !== initializer
71429             ? updateNode(createVariableDeclaration(name, type, initializer), node)
71430             : node;
71431     }
71432     ts.updateVariableDeclaration = updateVariableDeclaration;
71433     /* @internal */
71434     function createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer) {
71435         var node = createSynthesizedNode(242 /* VariableDeclaration */);
71436         node.name = asName(name);
71437         node.type = type;
71438         node.initializer = initializer !== undefined ? ts.parenthesizeExpressionForList(initializer) : undefined;
71439         node.exclamationToken = exclaimationToken;
71440         return node;
71441     }
71442     ts.createTypeScriptVariableDeclaration = createTypeScriptVariableDeclaration;
71443     /* @internal */
71444     function updateTypeScriptVariableDeclaration(node, name, exclaimationToken, type, initializer) {
71445         return node.name !== name
71446             || node.type !== type
71447             || node.initializer !== initializer
71448             || node.exclamationToken !== exclaimationToken
71449             ? updateNode(createTypeScriptVariableDeclaration(name, exclaimationToken, type, initializer), node)
71450             : node;
71451     }
71452     ts.updateTypeScriptVariableDeclaration = updateTypeScriptVariableDeclaration;
71453     function createVariableDeclarationList(declarations, flags) {
71454         if (flags === void 0) { flags = 0 /* None */; }
71455         var node = createSynthesizedNode(243 /* VariableDeclarationList */);
71456         node.flags |= flags & 3 /* BlockScoped */;
71457         node.declarations = createNodeArray(declarations);
71458         return node;
71459     }
71460     ts.createVariableDeclarationList = createVariableDeclarationList;
71461     function updateVariableDeclarationList(node, declarations) {
71462         return node.declarations !== declarations
71463             ? updateNode(createVariableDeclarationList(declarations, node.flags), node)
71464             : node;
71465     }
71466     ts.updateVariableDeclarationList = updateVariableDeclarationList;
71467     function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71468         var node = createSynthesizedNode(244 /* FunctionDeclaration */);
71469         node.decorators = asNodeArray(decorators);
71470         node.modifiers = asNodeArray(modifiers);
71471         node.asteriskToken = asteriskToken;
71472         node.name = asName(name);
71473         node.typeParameters = asNodeArray(typeParameters);
71474         node.parameters = createNodeArray(parameters);
71475         node.type = type;
71476         node.body = body;
71477         return node;
71478     }
71479     ts.createFunctionDeclaration = createFunctionDeclaration;
71480     function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
71481         return node.decorators !== decorators
71482             || node.modifiers !== modifiers
71483             || node.asteriskToken !== asteriskToken
71484             || node.name !== name
71485             || node.typeParameters !== typeParameters
71486             || node.parameters !== parameters
71487             || node.type !== type
71488             || node.body !== body
71489             ? updateNode(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
71490             : node;
71491     }
71492     ts.updateFunctionDeclaration = updateFunctionDeclaration;
71493     /* @internal */
71494     function updateFunctionLikeBody(declaration, body) {
71495         switch (declaration.kind) {
71496             case 244 /* FunctionDeclaration */:
71497                 return createFunctionDeclaration(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71498             case 161 /* MethodDeclaration */:
71499                 return createMethod(declaration.decorators, declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.questionToken, declaration.typeParameters, declaration.parameters, declaration.type, body);
71500             case 163 /* GetAccessor */:
71501                 return createGetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, declaration.type, body);
71502             case 164 /* SetAccessor */:
71503                 return createSetAccessor(declaration.decorators, declaration.modifiers, declaration.name, declaration.parameters, body);
71504             case 162 /* Constructor */:
71505                 return createConstructor(declaration.decorators, declaration.modifiers, declaration.parameters, body);
71506             case 201 /* FunctionExpression */:
71507                 return createFunctionExpression(declaration.modifiers, declaration.asteriskToken, declaration.name, declaration.typeParameters, declaration.parameters, declaration.type, body);
71508             case 202 /* ArrowFunction */:
71509                 return createArrowFunction(declaration.modifiers, declaration.typeParameters, declaration.parameters, declaration.type, declaration.equalsGreaterThanToken, body);
71510         }
71511     }
71512     ts.updateFunctionLikeBody = updateFunctionLikeBody;
71513     function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71514         var node = createSynthesizedNode(245 /* ClassDeclaration */);
71515         node.decorators = asNodeArray(decorators);
71516         node.modifiers = asNodeArray(modifiers);
71517         node.name = asName(name);
71518         node.typeParameters = asNodeArray(typeParameters);
71519         node.heritageClauses = asNodeArray(heritageClauses);
71520         node.members = createNodeArray(members);
71521         return node;
71522     }
71523     ts.createClassDeclaration = createClassDeclaration;
71524     function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71525         return node.decorators !== decorators
71526             || node.modifiers !== modifiers
71527             || node.name !== name
71528             || node.typeParameters !== typeParameters
71529             || node.heritageClauses !== heritageClauses
71530             || node.members !== members
71531             ? updateNode(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71532             : node;
71533     }
71534     ts.updateClassDeclaration = updateClassDeclaration;
71535     function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
71536         var node = createSynthesizedNode(246 /* InterfaceDeclaration */);
71537         node.decorators = asNodeArray(decorators);
71538         node.modifiers = asNodeArray(modifiers);
71539         node.name = asName(name);
71540         node.typeParameters = asNodeArray(typeParameters);
71541         node.heritageClauses = asNodeArray(heritageClauses);
71542         node.members = createNodeArray(members);
71543         return node;
71544     }
71545     ts.createInterfaceDeclaration = createInterfaceDeclaration;
71546     function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
71547         return node.decorators !== decorators
71548             || node.modifiers !== modifiers
71549             || node.name !== name
71550             || node.typeParameters !== typeParameters
71551             || node.heritageClauses !== heritageClauses
71552             || node.members !== members
71553             ? updateNode(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
71554             : node;
71555     }
71556     ts.updateInterfaceDeclaration = updateInterfaceDeclaration;
71557     function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
71558         var node = createSynthesizedNode(247 /* TypeAliasDeclaration */);
71559         node.decorators = asNodeArray(decorators);
71560         node.modifiers = asNodeArray(modifiers);
71561         node.name = asName(name);
71562         node.typeParameters = asNodeArray(typeParameters);
71563         node.type = type;
71564         return node;
71565     }
71566     ts.createTypeAliasDeclaration = createTypeAliasDeclaration;
71567     function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
71568         return node.decorators !== decorators
71569             || node.modifiers !== modifiers
71570             || node.name !== name
71571             || node.typeParameters !== typeParameters
71572             || node.type !== type
71573             ? updateNode(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
71574             : node;
71575     }
71576     ts.updateTypeAliasDeclaration = updateTypeAliasDeclaration;
71577     function createEnumDeclaration(decorators, modifiers, name, members) {
71578         var node = createSynthesizedNode(248 /* EnumDeclaration */);
71579         node.decorators = asNodeArray(decorators);
71580         node.modifiers = asNodeArray(modifiers);
71581         node.name = asName(name);
71582         node.members = createNodeArray(members);
71583         return node;
71584     }
71585     ts.createEnumDeclaration = createEnumDeclaration;
71586     function updateEnumDeclaration(node, decorators, modifiers, name, members) {
71587         return node.decorators !== decorators
71588             || node.modifiers !== modifiers
71589             || node.name !== name
71590             || node.members !== members
71591             ? updateNode(createEnumDeclaration(decorators, modifiers, name, members), node)
71592             : node;
71593     }
71594     ts.updateEnumDeclaration = updateEnumDeclaration;
71595     function createModuleDeclaration(decorators, modifiers, name, body, flags) {
71596         if (flags === void 0) { flags = 0 /* None */; }
71597         var node = createSynthesizedNode(249 /* ModuleDeclaration */);
71598         node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
71599         node.decorators = asNodeArray(decorators);
71600         node.modifiers = asNodeArray(modifiers);
71601         node.name = name;
71602         node.body = body;
71603         return node;
71604     }
71605     ts.createModuleDeclaration = createModuleDeclaration;
71606     function updateModuleDeclaration(node, decorators, modifiers, name, body) {
71607         return node.decorators !== decorators
71608             || node.modifiers !== modifiers
71609             || node.name !== name
71610             || node.body !== body
71611             ? updateNode(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
71612             : node;
71613     }
71614     ts.updateModuleDeclaration = updateModuleDeclaration;
71615     function createModuleBlock(statements) {
71616         var node = createSynthesizedNode(250 /* ModuleBlock */);
71617         node.statements = createNodeArray(statements);
71618         return node;
71619     }
71620     ts.createModuleBlock = createModuleBlock;
71621     function updateModuleBlock(node, statements) {
71622         return node.statements !== statements
71623             ? updateNode(createModuleBlock(statements), node)
71624             : node;
71625     }
71626     ts.updateModuleBlock = updateModuleBlock;
71627     function createCaseBlock(clauses) {
71628         var node = createSynthesizedNode(251 /* CaseBlock */);
71629         node.clauses = createNodeArray(clauses);
71630         return node;
71631     }
71632     ts.createCaseBlock = createCaseBlock;
71633     function updateCaseBlock(node, clauses) {
71634         return node.clauses !== clauses
71635             ? updateNode(createCaseBlock(clauses), node)
71636             : node;
71637     }
71638     ts.updateCaseBlock = updateCaseBlock;
71639     function createNamespaceExportDeclaration(name) {
71640         var node = createSynthesizedNode(252 /* NamespaceExportDeclaration */);
71641         node.name = asName(name);
71642         return node;
71643     }
71644     ts.createNamespaceExportDeclaration = createNamespaceExportDeclaration;
71645     function updateNamespaceExportDeclaration(node, name) {
71646         return node.name !== name
71647             ? updateNode(createNamespaceExportDeclaration(name), node)
71648             : node;
71649     }
71650     ts.updateNamespaceExportDeclaration = updateNamespaceExportDeclaration;
71651     function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
71652         var node = createSynthesizedNode(253 /* ImportEqualsDeclaration */);
71653         node.decorators = asNodeArray(decorators);
71654         node.modifiers = asNodeArray(modifiers);
71655         node.name = asName(name);
71656         node.moduleReference = moduleReference;
71657         return node;
71658     }
71659     ts.createImportEqualsDeclaration = createImportEqualsDeclaration;
71660     function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
71661         return node.decorators !== decorators
71662             || node.modifiers !== modifiers
71663             || node.name !== name
71664             || node.moduleReference !== moduleReference
71665             ? updateNode(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
71666             : node;
71667     }
71668     ts.updateImportEqualsDeclaration = updateImportEqualsDeclaration;
71669     function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
71670         var node = createSynthesizedNode(254 /* ImportDeclaration */);
71671         node.decorators = asNodeArray(decorators);
71672         node.modifiers = asNodeArray(modifiers);
71673         node.importClause = importClause;
71674         node.moduleSpecifier = moduleSpecifier;
71675         return node;
71676     }
71677     ts.createImportDeclaration = createImportDeclaration;
71678     function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
71679         return node.decorators !== decorators
71680             || node.modifiers !== modifiers
71681             || node.importClause !== importClause
71682             || node.moduleSpecifier !== moduleSpecifier
71683             ? updateNode(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
71684             : node;
71685     }
71686     ts.updateImportDeclaration = updateImportDeclaration;
71687     function createImportClause(name, namedBindings, isTypeOnly) {
71688         if (isTypeOnly === void 0) { isTypeOnly = false; }
71689         var node = createSynthesizedNode(255 /* ImportClause */);
71690         node.name = name;
71691         node.namedBindings = namedBindings;
71692         node.isTypeOnly = isTypeOnly;
71693         return node;
71694     }
71695     ts.createImportClause = createImportClause;
71696     function updateImportClause(node, name, namedBindings, isTypeOnly) {
71697         return node.name !== name
71698             || node.namedBindings !== namedBindings
71699             || node.isTypeOnly !== isTypeOnly
71700             ? updateNode(createImportClause(name, namedBindings, isTypeOnly), node)
71701             : node;
71702     }
71703     ts.updateImportClause = updateImportClause;
71704     function createNamespaceImport(name) {
71705         var node = createSynthesizedNode(256 /* NamespaceImport */);
71706         node.name = name;
71707         return node;
71708     }
71709     ts.createNamespaceImport = createNamespaceImport;
71710     function createNamespaceExport(name) {
71711         var node = createSynthesizedNode(262 /* NamespaceExport */);
71712         node.name = name;
71713         return node;
71714     }
71715     ts.createNamespaceExport = createNamespaceExport;
71716     function updateNamespaceImport(node, name) {
71717         return node.name !== name
71718             ? updateNode(createNamespaceImport(name), node)
71719             : node;
71720     }
71721     ts.updateNamespaceImport = updateNamespaceImport;
71722     function updateNamespaceExport(node, name) {
71723         return node.name !== name
71724             ? updateNode(createNamespaceExport(name), node)
71725             : node;
71726     }
71727     ts.updateNamespaceExport = updateNamespaceExport;
71728     function createNamedImports(elements) {
71729         var node = createSynthesizedNode(257 /* NamedImports */);
71730         node.elements = createNodeArray(elements);
71731         return node;
71732     }
71733     ts.createNamedImports = createNamedImports;
71734     function updateNamedImports(node, elements) {
71735         return node.elements !== elements
71736             ? updateNode(createNamedImports(elements), node)
71737             : node;
71738     }
71739     ts.updateNamedImports = updateNamedImports;
71740     function createImportSpecifier(propertyName, name) {
71741         var node = createSynthesizedNode(258 /* ImportSpecifier */);
71742         node.propertyName = propertyName;
71743         node.name = name;
71744         return node;
71745     }
71746     ts.createImportSpecifier = createImportSpecifier;
71747     function updateImportSpecifier(node, propertyName, name) {
71748         return node.propertyName !== propertyName
71749             || node.name !== name
71750             ? updateNode(createImportSpecifier(propertyName, name), node)
71751             : node;
71752     }
71753     ts.updateImportSpecifier = updateImportSpecifier;
71754     function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
71755         var node = createSynthesizedNode(259 /* ExportAssignment */);
71756         node.decorators = asNodeArray(decorators);
71757         node.modifiers = asNodeArray(modifiers);
71758         node.isExportEquals = isExportEquals;
71759         node.expression = isExportEquals ? ts.parenthesizeBinaryOperand(62 /* EqualsToken */, expression, /*isLeftSideOfBinary*/ false, /*leftOperand*/ undefined) : ts.parenthesizeDefaultExpression(expression);
71760         return node;
71761     }
71762     ts.createExportAssignment = createExportAssignment;
71763     function updateExportAssignment(node, decorators, modifiers, expression) {
71764         return node.decorators !== decorators
71765             || node.modifiers !== modifiers
71766             || node.expression !== expression
71767             ? updateNode(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
71768             : node;
71769     }
71770     ts.updateExportAssignment = updateExportAssignment;
71771     function createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71772         if (isTypeOnly === void 0) { isTypeOnly = false; }
71773         var node = createSynthesizedNode(260 /* ExportDeclaration */);
71774         node.decorators = asNodeArray(decorators);
71775         node.modifiers = asNodeArray(modifiers);
71776         node.isTypeOnly = isTypeOnly;
71777         node.exportClause = exportClause;
71778         node.moduleSpecifier = moduleSpecifier;
71779         return node;
71780     }
71781     ts.createExportDeclaration = createExportDeclaration;
71782     function updateExportDeclaration(node, decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly) {
71783         return node.decorators !== decorators
71784             || node.modifiers !== modifiers
71785             || node.isTypeOnly !== isTypeOnly
71786             || node.exportClause !== exportClause
71787             || node.moduleSpecifier !== moduleSpecifier
71788             ? updateNode(createExportDeclaration(decorators, modifiers, exportClause, moduleSpecifier, isTypeOnly), node)
71789             : node;
71790     }
71791     ts.updateExportDeclaration = updateExportDeclaration;
71792     /* @internal */
71793     function createEmptyExports() {
71794         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined);
71795     }
71796     ts.createEmptyExports = createEmptyExports;
71797     function createNamedExports(elements) {
71798         var node = createSynthesizedNode(261 /* NamedExports */);
71799         node.elements = createNodeArray(elements);
71800         return node;
71801     }
71802     ts.createNamedExports = createNamedExports;
71803     function updateNamedExports(node, elements) {
71804         return node.elements !== elements
71805             ? updateNode(createNamedExports(elements), node)
71806             : node;
71807     }
71808     ts.updateNamedExports = updateNamedExports;
71809     function createExportSpecifier(propertyName, name) {
71810         var node = createSynthesizedNode(263 /* ExportSpecifier */);
71811         node.propertyName = asName(propertyName);
71812         node.name = asName(name);
71813         return node;
71814     }
71815     ts.createExportSpecifier = createExportSpecifier;
71816     function updateExportSpecifier(node, propertyName, name) {
71817         return node.propertyName !== propertyName
71818             || node.name !== name
71819             ? updateNode(createExportSpecifier(propertyName, name), node)
71820             : node;
71821     }
71822     ts.updateExportSpecifier = updateExportSpecifier;
71823     // Module references
71824     function createExternalModuleReference(expression) {
71825         var node = createSynthesizedNode(265 /* ExternalModuleReference */);
71826         node.expression = expression;
71827         return node;
71828     }
71829     ts.createExternalModuleReference = createExternalModuleReference;
71830     function updateExternalModuleReference(node, expression) {
71831         return node.expression !== expression
71832             ? updateNode(createExternalModuleReference(expression), node)
71833             : node;
71834     }
71835     ts.updateExternalModuleReference = updateExternalModuleReference;
71836     // JSDoc
71837     /* @internal */
71838     function createJSDocTypeExpression(type) {
71839         var node = createSynthesizedNode(294 /* JSDocTypeExpression */);
71840         node.type = type;
71841         return node;
71842     }
71843     ts.createJSDocTypeExpression = createJSDocTypeExpression;
71844     /* @internal */
71845     function createJSDocTypeTag(typeExpression, comment) {
71846         var tag = createJSDocTag(320 /* JSDocTypeTag */, "type");
71847         tag.typeExpression = typeExpression;
71848         tag.comment = comment;
71849         return tag;
71850     }
71851     ts.createJSDocTypeTag = createJSDocTypeTag;
71852     /* @internal */
71853     function createJSDocReturnTag(typeExpression, comment) {
71854         var tag = createJSDocTag(318 /* JSDocReturnTag */, "returns");
71855         tag.typeExpression = typeExpression;
71856         tag.comment = comment;
71857         return tag;
71858     }
71859     ts.createJSDocReturnTag = createJSDocReturnTag;
71860     /** @internal */
71861     function createJSDocThisTag(typeExpression) {
71862         var tag = createJSDocTag(319 /* JSDocThisTag */, "this");
71863         tag.typeExpression = typeExpression;
71864         return tag;
71865     }
71866     ts.createJSDocThisTag = createJSDocThisTag;
71867     /* @internal */
71868     function createJSDocParamTag(name, isBracketed, typeExpression, comment) {
71869         var tag = createJSDocTag(317 /* JSDocParameterTag */, "param");
71870         tag.typeExpression = typeExpression;
71871         tag.name = name;
71872         tag.isBracketed = isBracketed;
71873         tag.comment = comment;
71874         return tag;
71875     }
71876     ts.createJSDocParamTag = createJSDocParamTag;
71877     /* @internal */
71878     function createJSDocClassTag() {
71879         return createJSDocTag(310 /* JSDocClassTag */, "class");
71880     }
71881     ts.createJSDocClassTag = createJSDocClassTag;
71882     /* @internal */
71883     function createJSDocComment(comment, tags) {
71884         var node = createSynthesizedNode(303 /* JSDocComment */);
71885         node.comment = comment;
71886         node.tags = tags;
71887         return node;
71888     }
71889     ts.createJSDocComment = createJSDocComment;
71890     /* @internal */
71891     function createJSDocTag(kind, tagName) {
71892         var node = createSynthesizedNode(kind);
71893         node.tagName = createIdentifier(tagName);
71894         return node;
71895     }
71896     // JSX
71897     function createJsxElement(openingElement, children, closingElement) {
71898         var node = createSynthesizedNode(266 /* JsxElement */);
71899         node.openingElement = openingElement;
71900         node.children = createNodeArray(children);
71901         node.closingElement = closingElement;
71902         return node;
71903     }
71904     ts.createJsxElement = createJsxElement;
71905     function updateJsxElement(node, openingElement, children, closingElement) {
71906         return node.openingElement !== openingElement
71907             || node.children !== children
71908             || node.closingElement !== closingElement
71909             ? updateNode(createJsxElement(openingElement, children, closingElement), node)
71910             : node;
71911     }
71912     ts.updateJsxElement = updateJsxElement;
71913     function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
71914         var node = createSynthesizedNode(267 /* JsxSelfClosingElement */);
71915         node.tagName = tagName;
71916         node.typeArguments = asNodeArray(typeArguments);
71917         node.attributes = attributes;
71918         return node;
71919     }
71920     ts.createJsxSelfClosingElement = createJsxSelfClosingElement;
71921     function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
71922         return node.tagName !== tagName
71923             || node.typeArguments !== typeArguments
71924             || node.attributes !== attributes
71925             ? updateNode(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
71926             : node;
71927     }
71928     ts.updateJsxSelfClosingElement = updateJsxSelfClosingElement;
71929     function createJsxOpeningElement(tagName, typeArguments, attributes) {
71930         var node = createSynthesizedNode(268 /* JsxOpeningElement */);
71931         node.tagName = tagName;
71932         node.typeArguments = asNodeArray(typeArguments);
71933         node.attributes = attributes;
71934         return node;
71935     }
71936     ts.createJsxOpeningElement = createJsxOpeningElement;
71937     function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
71938         return node.tagName !== tagName
71939             || node.typeArguments !== typeArguments
71940             || node.attributes !== attributes
71941             ? updateNode(createJsxOpeningElement(tagName, typeArguments, attributes), node)
71942             : node;
71943     }
71944     ts.updateJsxOpeningElement = updateJsxOpeningElement;
71945     function createJsxClosingElement(tagName) {
71946         var node = createSynthesizedNode(269 /* JsxClosingElement */);
71947         node.tagName = tagName;
71948         return node;
71949     }
71950     ts.createJsxClosingElement = createJsxClosingElement;
71951     function updateJsxClosingElement(node, tagName) {
71952         return node.tagName !== tagName
71953             ? updateNode(createJsxClosingElement(tagName), node)
71954             : node;
71955     }
71956     ts.updateJsxClosingElement = updateJsxClosingElement;
71957     function createJsxFragment(openingFragment, children, closingFragment) {
71958         var node = createSynthesizedNode(270 /* JsxFragment */);
71959         node.openingFragment = openingFragment;
71960         node.children = createNodeArray(children);
71961         node.closingFragment = closingFragment;
71962         return node;
71963     }
71964     ts.createJsxFragment = createJsxFragment;
71965     function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
71966         var node = createSynthesizedNode(11 /* JsxText */);
71967         node.text = text;
71968         node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
71969         return node;
71970     }
71971     ts.createJsxText = createJsxText;
71972     function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
71973         return node.text !== text
71974             || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
71975             ? updateNode(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
71976             : node;
71977     }
71978     ts.updateJsxText = updateJsxText;
71979     function createJsxOpeningFragment() {
71980         return createSynthesizedNode(271 /* JsxOpeningFragment */);
71981     }
71982     ts.createJsxOpeningFragment = createJsxOpeningFragment;
71983     function createJsxJsxClosingFragment() {
71984         return createSynthesizedNode(272 /* JsxClosingFragment */);
71985     }
71986     ts.createJsxJsxClosingFragment = createJsxJsxClosingFragment;
71987     function updateJsxFragment(node, openingFragment, children, closingFragment) {
71988         return node.openingFragment !== openingFragment
71989             || node.children !== children
71990             || node.closingFragment !== closingFragment
71991             ? updateNode(createJsxFragment(openingFragment, children, closingFragment), node)
71992             : node;
71993     }
71994     ts.updateJsxFragment = updateJsxFragment;
71995     function createJsxAttribute(name, initializer) {
71996         var node = createSynthesizedNode(273 /* JsxAttribute */);
71997         node.name = name;
71998         node.initializer = initializer;
71999         return node;
72000     }
72001     ts.createJsxAttribute = createJsxAttribute;
72002     function updateJsxAttribute(node, name, initializer) {
72003         return node.name !== name
72004             || node.initializer !== initializer
72005             ? updateNode(createJsxAttribute(name, initializer), node)
72006             : node;
72007     }
72008     ts.updateJsxAttribute = updateJsxAttribute;
72009     function createJsxAttributes(properties) {
72010         var node = createSynthesizedNode(274 /* JsxAttributes */);
72011         node.properties = createNodeArray(properties);
72012         return node;
72013     }
72014     ts.createJsxAttributes = createJsxAttributes;
72015     function updateJsxAttributes(node, properties) {
72016         return node.properties !== properties
72017             ? updateNode(createJsxAttributes(properties), node)
72018             : node;
72019     }
72020     ts.updateJsxAttributes = updateJsxAttributes;
72021     function createJsxSpreadAttribute(expression) {
72022         var node = createSynthesizedNode(275 /* JsxSpreadAttribute */);
72023         node.expression = expression;
72024         return node;
72025     }
72026     ts.createJsxSpreadAttribute = createJsxSpreadAttribute;
72027     function updateJsxSpreadAttribute(node, expression) {
72028         return node.expression !== expression
72029             ? updateNode(createJsxSpreadAttribute(expression), node)
72030             : node;
72031     }
72032     ts.updateJsxSpreadAttribute = updateJsxSpreadAttribute;
72033     function createJsxExpression(dotDotDotToken, expression) {
72034         var node = createSynthesizedNode(276 /* JsxExpression */);
72035         node.dotDotDotToken = dotDotDotToken;
72036         node.expression = expression;
72037         return node;
72038     }
72039     ts.createJsxExpression = createJsxExpression;
72040     function updateJsxExpression(node, expression) {
72041         return node.expression !== expression
72042             ? updateNode(createJsxExpression(node.dotDotDotToken, expression), node)
72043             : node;
72044     }
72045     ts.updateJsxExpression = updateJsxExpression;
72046     // Clauses
72047     function createCaseClause(expression, statements) {
72048         var node = createSynthesizedNode(277 /* CaseClause */);
72049         node.expression = ts.parenthesizeExpressionForList(expression);
72050         node.statements = createNodeArray(statements);
72051         return node;
72052     }
72053     ts.createCaseClause = createCaseClause;
72054     function updateCaseClause(node, expression, statements) {
72055         return node.expression !== expression
72056             || node.statements !== statements
72057             ? updateNode(createCaseClause(expression, statements), node)
72058             : node;
72059     }
72060     ts.updateCaseClause = updateCaseClause;
72061     function createDefaultClause(statements) {
72062         var node = createSynthesizedNode(278 /* DefaultClause */);
72063         node.statements = createNodeArray(statements);
72064         return node;
72065     }
72066     ts.createDefaultClause = createDefaultClause;
72067     function updateDefaultClause(node, statements) {
72068         return node.statements !== statements
72069             ? updateNode(createDefaultClause(statements), node)
72070             : node;
72071     }
72072     ts.updateDefaultClause = updateDefaultClause;
72073     function createHeritageClause(token, types) {
72074         var node = createSynthesizedNode(279 /* HeritageClause */);
72075         node.token = token;
72076         node.types = createNodeArray(types);
72077         return node;
72078     }
72079     ts.createHeritageClause = createHeritageClause;
72080     function updateHeritageClause(node, types) {
72081         return node.types !== types
72082             ? updateNode(createHeritageClause(node.token, types), node)
72083             : node;
72084     }
72085     ts.updateHeritageClause = updateHeritageClause;
72086     function createCatchClause(variableDeclaration, block) {
72087         var node = createSynthesizedNode(280 /* CatchClause */);
72088         node.variableDeclaration = ts.isString(variableDeclaration) ? createVariableDeclaration(variableDeclaration) : variableDeclaration;
72089         node.block = block;
72090         return node;
72091     }
72092     ts.createCatchClause = createCatchClause;
72093     function updateCatchClause(node, variableDeclaration, block) {
72094         return node.variableDeclaration !== variableDeclaration
72095             || node.block !== block
72096             ? updateNode(createCatchClause(variableDeclaration, block), node)
72097             : node;
72098     }
72099     ts.updateCatchClause = updateCatchClause;
72100     // Property assignments
72101     function createPropertyAssignment(name, initializer) {
72102         var node = createSynthesizedNode(281 /* PropertyAssignment */);
72103         node.name = asName(name);
72104         node.questionToken = undefined;
72105         node.initializer = ts.parenthesizeExpressionForList(initializer);
72106         return node;
72107     }
72108     ts.createPropertyAssignment = createPropertyAssignment;
72109     function updatePropertyAssignment(node, name, initializer) {
72110         return node.name !== name
72111             || node.initializer !== initializer
72112             ? updateNode(createPropertyAssignment(name, initializer), node)
72113             : node;
72114     }
72115     ts.updatePropertyAssignment = updatePropertyAssignment;
72116     function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
72117         var node = createSynthesizedNode(282 /* ShorthandPropertyAssignment */);
72118         node.name = asName(name);
72119         node.objectAssignmentInitializer = objectAssignmentInitializer !== undefined ? ts.parenthesizeExpressionForList(objectAssignmentInitializer) : undefined;
72120         return node;
72121     }
72122     ts.createShorthandPropertyAssignment = createShorthandPropertyAssignment;
72123     function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
72124         return node.name !== name
72125             || node.objectAssignmentInitializer !== objectAssignmentInitializer
72126             ? updateNode(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
72127             : node;
72128     }
72129     ts.updateShorthandPropertyAssignment = updateShorthandPropertyAssignment;
72130     function createSpreadAssignment(expression) {
72131         var node = createSynthesizedNode(283 /* SpreadAssignment */);
72132         node.expression = ts.parenthesizeExpressionForList(expression);
72133         return node;
72134     }
72135     ts.createSpreadAssignment = createSpreadAssignment;
72136     function updateSpreadAssignment(node, expression) {
72137         return node.expression !== expression
72138             ? updateNode(createSpreadAssignment(expression), node)
72139             : node;
72140     }
72141     ts.updateSpreadAssignment = updateSpreadAssignment;
72142     // Enum
72143     function createEnumMember(name, initializer) {
72144         var node = createSynthesizedNode(284 /* EnumMember */);
72145         node.name = asName(name);
72146         node.initializer = initializer && ts.parenthesizeExpressionForList(initializer);
72147         return node;
72148     }
72149     ts.createEnumMember = createEnumMember;
72150     function updateEnumMember(node, name, initializer) {
72151         return node.name !== name
72152             || node.initializer !== initializer
72153             ? updateNode(createEnumMember(name, initializer), node)
72154             : node;
72155     }
72156     ts.updateEnumMember = updateEnumMember;
72157     // Top-level nodes
72158     function updateSourceFileNode(node, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
72159         if (node.statements !== statements ||
72160             (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) ||
72161             (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) ||
72162             (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) ||
72163             (libReferences !== undefined && node.libReferenceDirectives !== libReferences) ||
72164             (hasNoDefaultLib !== undefined && node.hasNoDefaultLib !== hasNoDefaultLib)) {
72165             var updated = createSynthesizedNode(290 /* SourceFile */);
72166             updated.flags |= node.flags;
72167             updated.statements = createNodeArray(statements);
72168             updated.endOfFileToken = node.endOfFileToken;
72169             updated.fileName = node.fileName;
72170             updated.path = node.path;
72171             updated.text = node.text;
72172             updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile;
72173             updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles;
72174             updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences;
72175             updated.hasNoDefaultLib = hasNoDefaultLib === undefined ? node.hasNoDefaultLib : hasNoDefaultLib;
72176             updated.libReferenceDirectives = libReferences === undefined ? node.libReferenceDirectives : libReferences;
72177             if (node.amdDependencies !== undefined)
72178                 updated.amdDependencies = node.amdDependencies;
72179             if (node.moduleName !== undefined)
72180                 updated.moduleName = node.moduleName;
72181             if (node.languageVariant !== undefined)
72182                 updated.languageVariant = node.languageVariant;
72183             if (node.renamedDependencies !== undefined)
72184                 updated.renamedDependencies = node.renamedDependencies;
72185             if (node.languageVersion !== undefined)
72186                 updated.languageVersion = node.languageVersion;
72187             if (node.scriptKind !== undefined)
72188                 updated.scriptKind = node.scriptKind;
72189             if (node.externalModuleIndicator !== undefined)
72190                 updated.externalModuleIndicator = node.externalModuleIndicator;
72191             if (node.commonJsModuleIndicator !== undefined)
72192                 updated.commonJsModuleIndicator = node.commonJsModuleIndicator;
72193             if (node.identifiers !== undefined)
72194                 updated.identifiers = node.identifiers;
72195             if (node.nodeCount !== undefined)
72196                 updated.nodeCount = node.nodeCount;
72197             if (node.identifierCount !== undefined)
72198                 updated.identifierCount = node.identifierCount;
72199             if (node.symbolCount !== undefined)
72200                 updated.symbolCount = node.symbolCount;
72201             if (node.parseDiagnostics !== undefined)
72202                 updated.parseDiagnostics = node.parseDiagnostics;
72203             if (node.bindDiagnostics !== undefined)
72204                 updated.bindDiagnostics = node.bindDiagnostics;
72205             if (node.bindSuggestionDiagnostics !== undefined)
72206                 updated.bindSuggestionDiagnostics = node.bindSuggestionDiagnostics;
72207             if (node.lineMap !== undefined)
72208                 updated.lineMap = node.lineMap;
72209             if (node.classifiableNames !== undefined)
72210                 updated.classifiableNames = node.classifiableNames;
72211             if (node.resolvedModules !== undefined)
72212                 updated.resolvedModules = node.resolvedModules;
72213             if (node.resolvedTypeReferenceDirectiveNames !== undefined)
72214                 updated.resolvedTypeReferenceDirectiveNames = node.resolvedTypeReferenceDirectiveNames;
72215             if (node.imports !== undefined)
72216                 updated.imports = node.imports;
72217             if (node.moduleAugmentations !== undefined)
72218                 updated.moduleAugmentations = node.moduleAugmentations;
72219             if (node.pragmas !== undefined)
72220                 updated.pragmas = node.pragmas;
72221             if (node.localJsxFactory !== undefined)
72222                 updated.localJsxFactory = node.localJsxFactory;
72223             if (node.localJsxNamespace !== undefined)
72224                 updated.localJsxNamespace = node.localJsxNamespace;
72225             return updateNode(updated, node);
72226         }
72227         return node;
72228     }
72229     ts.updateSourceFileNode = updateSourceFileNode;
72230     /**
72231      * Creates a shallow, memberwise clone of a node for mutation.
72232      */
72233     function getMutableClone(node) {
72234         var clone = getSynthesizedClone(node);
72235         clone.pos = node.pos;
72236         clone.end = node.end;
72237         clone.parent = node.parent;
72238         return clone;
72239     }
72240     ts.getMutableClone = getMutableClone;
72241     // Transformation nodes
72242     /**
72243      * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
72244      * order to preserve comments.
72245      *
72246      * @param original The original statement.
72247      */
72248     function createNotEmittedStatement(original) {
72249         var node = createSynthesizedNode(325 /* NotEmittedStatement */);
72250         node.original = original;
72251         setTextRange(node, original);
72252         return node;
72253     }
72254     ts.createNotEmittedStatement = createNotEmittedStatement;
72255     /**
72256      * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
72257      * order to properly emit exports.
72258      */
72259     /* @internal */
72260     function createEndOfDeclarationMarker(original) {
72261         var node = createSynthesizedNode(329 /* EndOfDeclarationMarker */);
72262         node.emitNode = {};
72263         node.original = original;
72264         return node;
72265     }
72266     ts.createEndOfDeclarationMarker = createEndOfDeclarationMarker;
72267     /**
72268      * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
72269      * order to properly emit exports.
72270      */
72271     /* @internal */
72272     function createMergeDeclarationMarker(original) {
72273         var node = createSynthesizedNode(328 /* MergeDeclarationMarker */);
72274         node.emitNode = {};
72275         node.original = original;
72276         return node;
72277     }
72278     ts.createMergeDeclarationMarker = createMergeDeclarationMarker;
72279     /**
72280      * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
72281      * order to preserve comments or sourcemap positions.
72282      *
72283      * @param expression The inner expression to emit.
72284      * @param original The original outer expression.
72285      * @param location The location for the expression. Defaults to the positions from "original" if provided.
72286      */
72287     function createPartiallyEmittedExpression(expression, original) {
72288         var node = createSynthesizedNode(326 /* PartiallyEmittedExpression */);
72289         node.expression = expression;
72290         node.original = original;
72291         setTextRange(node, original);
72292         return node;
72293     }
72294     ts.createPartiallyEmittedExpression = createPartiallyEmittedExpression;
72295     function updatePartiallyEmittedExpression(node, expression) {
72296         if (node.expression !== expression) {
72297             return updateNode(createPartiallyEmittedExpression(expression, node.original), node);
72298         }
72299         return node;
72300     }
72301     ts.updatePartiallyEmittedExpression = updatePartiallyEmittedExpression;
72302     function flattenCommaElements(node) {
72303         if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
72304             if (node.kind === 327 /* CommaListExpression */) {
72305                 return node.elements;
72306             }
72307             if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
72308                 return [node.left, node.right];
72309             }
72310         }
72311         return node;
72312     }
72313     function createCommaList(elements) {
72314         var node = createSynthesizedNode(327 /* CommaListExpression */);
72315         node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
72316         return node;
72317     }
72318     ts.createCommaList = createCommaList;
72319     function updateCommaList(node, elements) {
72320         return node.elements !== elements
72321             ? updateNode(createCommaList(elements), node)
72322             : node;
72323     }
72324     ts.updateCommaList = updateCommaList;
72325     /* @internal */
72326     function createSyntheticReferenceExpression(expression, thisArg) {
72327         var node = createSynthesizedNode(330 /* SyntheticReferenceExpression */);
72328         node.expression = expression;
72329         node.thisArg = thisArg;
72330         return node;
72331     }
72332     ts.createSyntheticReferenceExpression = createSyntheticReferenceExpression;
72333     /* @internal */
72334     function updateSyntheticReferenceExpression(node, expression, thisArg) {
72335         return node.expression !== expression
72336             || node.thisArg !== thisArg
72337             ? updateNode(createSyntheticReferenceExpression(expression, thisArg), node)
72338             : node;
72339     }
72340     ts.updateSyntheticReferenceExpression = updateSyntheticReferenceExpression;
72341     function createBundle(sourceFiles, prepends) {
72342         if (prepends === void 0) { prepends = ts.emptyArray; }
72343         var node = ts.createNode(291 /* Bundle */);
72344         node.prepends = prepends;
72345         node.sourceFiles = sourceFiles;
72346         return node;
72347     }
72348     ts.createBundle = createBundle;
72349     var allUnscopedEmitHelpers;
72350     function getAllUnscopedEmitHelpers() {
72351         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
72352             ts.valuesHelper,
72353             ts.readHelper,
72354             ts.spreadHelper,
72355             ts.spreadArraysHelper,
72356             ts.restHelper,
72357             ts.decorateHelper,
72358             ts.metadataHelper,
72359             ts.paramHelper,
72360             ts.awaiterHelper,
72361             ts.assignHelper,
72362             ts.awaitHelper,
72363             ts.asyncGeneratorHelper,
72364             ts.asyncDelegator,
72365             ts.asyncValues,
72366             ts.extendsHelper,
72367             ts.templateObjectHelper,
72368             ts.generatorHelper,
72369             ts.importStarHelper,
72370             ts.importDefaultHelper,
72371             ts.classPrivateFieldGetHelper,
72372             ts.classPrivateFieldSetHelper,
72373             ts.createBindingHelper,
72374             ts.setModuleDefaultHelper
72375         ], function (helper) { return helper.name; }));
72376     }
72377     function createUnparsedSource() {
72378         var node = ts.createNode(292 /* UnparsedSource */);
72379         node.prologues = ts.emptyArray;
72380         node.referencedFiles = ts.emptyArray;
72381         node.libReferenceDirectives = ts.emptyArray;
72382         node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
72383         return node;
72384     }
72385     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
72386         var node = createUnparsedSource();
72387         var stripInternal;
72388         var bundleFileInfo;
72389         if (!ts.isString(textOrInputFiles)) {
72390             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
72391             node.fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
72392             node.sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
72393             Object.defineProperties(node, {
72394                 text: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; } },
72395                 sourceMapText: { get: function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; } },
72396             });
72397             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
72398                 node.oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
72399                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
72400                 stripInternal = mapTextOrStripInternal;
72401                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
72402                 if (node.oldFileOfCurrentEmit) {
72403                     parseOldFileOfCurrentEmit(node, ts.Debug.checkDefined(bundleFileInfo));
72404                     return node;
72405                 }
72406             }
72407         }
72408         else {
72409             node.fileName = "";
72410             node.text = textOrInputFiles;
72411             node.sourceMapPath = mapPathOrType;
72412             node.sourceMapText = mapTextOrStripInternal;
72413         }
72414         ts.Debug.assert(!node.oldFileOfCurrentEmit);
72415         parseUnparsedSourceFile(node, bundleFileInfo, stripInternal);
72416         return node;
72417     }
72418     ts.createUnparsedSourceFile = createUnparsedSourceFile;
72419     function parseUnparsedSourceFile(node, bundleFileInfo, stripInternal) {
72420         var prologues;
72421         var helpers;
72422         var referencedFiles;
72423         var typeReferenceDirectives;
72424         var libReferenceDirectives;
72425         var texts;
72426         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
72427             var section = _a[_i];
72428             switch (section.kind) {
72429                 case "prologue" /* Prologue */:
72430                     (prologues || (prologues = [])).push(createUnparsedNode(section, node));
72431                     break;
72432                 case "emitHelpers" /* EmitHelpers */:
72433                     (helpers || (helpers = [])).push(getAllUnscopedEmitHelpers().get(section.data));
72434                     break;
72435                 case "no-default-lib" /* NoDefaultLib */:
72436                     node.hasNoDefaultLib = true;
72437                     break;
72438                 case "reference" /* Reference */:
72439                     (referencedFiles || (referencedFiles = [])).push({ pos: -1, end: -1, fileName: section.data });
72440                     break;
72441                 case "type" /* Type */:
72442                     (typeReferenceDirectives || (typeReferenceDirectives = [])).push(section.data);
72443                     break;
72444                 case "lib" /* Lib */:
72445                     (libReferenceDirectives || (libReferenceDirectives = [])).push({ pos: -1, end: -1, fileName: section.data });
72446                     break;
72447                 case "prepend" /* Prepend */:
72448                     var prependNode = createUnparsedNode(section, node);
72449                     var prependTexts = void 0;
72450                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
72451                         var text = _c[_b];
72452                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
72453                             (prependTexts || (prependTexts = [])).push(createUnparsedNode(text, node));
72454                         }
72455                     }
72456                     prependNode.texts = prependTexts || ts.emptyArray;
72457                     (texts || (texts = [])).push(prependNode);
72458                     break;
72459                 case "internal" /* Internal */:
72460                     if (stripInternal) {
72461                         if (!texts)
72462                             texts = [];
72463                         break;
72464                     }
72465                 // falls through
72466                 case "text" /* Text */:
72467                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72468                     break;
72469                 default:
72470                     ts.Debug.assertNever(section);
72471             }
72472         }
72473         node.prologues = prologues || ts.emptyArray;
72474         node.helpers = helpers;
72475         node.referencedFiles = referencedFiles || ts.emptyArray;
72476         node.typeReferenceDirectives = typeReferenceDirectives;
72477         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
72478         node.texts = texts || [createUnparsedNode({ kind: "text" /* Text */, pos: 0, end: node.text.length }, node)];
72479     }
72480     function parseOldFileOfCurrentEmit(node, bundleFileInfo) {
72481         ts.Debug.assert(!!node.oldFileOfCurrentEmit);
72482         var texts;
72483         var syntheticReferences;
72484         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
72485             var section = _a[_i];
72486             switch (section.kind) {
72487                 case "internal" /* Internal */:
72488                 case "text" /* Text */:
72489                     (texts || (texts = [])).push(createUnparsedNode(section, node));
72490                     break;
72491                 case "no-default-lib" /* NoDefaultLib */:
72492                 case "reference" /* Reference */:
72493                 case "type" /* Type */:
72494                 case "lib" /* Lib */:
72495                     (syntheticReferences || (syntheticReferences = [])).push(createUnparsedSyntheticReference(section, node));
72496                     break;
72497                 // Ignore
72498                 case "prologue" /* Prologue */:
72499                 case "emitHelpers" /* EmitHelpers */:
72500                 case "prepend" /* Prepend */:
72501                     break;
72502                 default:
72503                     ts.Debug.assertNever(section);
72504             }
72505         }
72506         node.texts = texts || ts.emptyArray;
72507         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return getAllUnscopedEmitHelpers().get(name); });
72508         node.syntheticReferences = syntheticReferences;
72509         return node;
72510     }
72511     function mapBundleFileSectionKindToSyntaxKind(kind) {
72512         switch (kind) {
72513             case "prologue" /* Prologue */: return 285 /* UnparsedPrologue */;
72514             case "prepend" /* Prepend */: return 286 /* UnparsedPrepend */;
72515             case "internal" /* Internal */: return 288 /* UnparsedInternalText */;
72516             case "text" /* Text */: return 287 /* UnparsedText */;
72517             case "emitHelpers" /* EmitHelpers */:
72518             case "no-default-lib" /* NoDefaultLib */:
72519             case "reference" /* Reference */:
72520             case "type" /* Type */:
72521             case "lib" /* Lib */:
72522                 return ts.Debug.fail("BundleFileSectionKind: " + kind + " not yet mapped to SyntaxKind");
72523             default:
72524                 return ts.Debug.assertNever(kind);
72525         }
72526     }
72527     function createUnparsedNode(section, parent) {
72528         var node = ts.createNode(mapBundleFileSectionKindToSyntaxKind(section.kind), section.pos, section.end);
72529         node.parent = parent;
72530         node.data = section.data;
72531         return node;
72532     }
72533     function createUnparsedSyntheticReference(section, parent) {
72534         var node = ts.createNode(289 /* UnparsedSyntheticReference */, section.pos, section.end);
72535         node.parent = parent;
72536         node.data = section.data;
72537         node.section = section;
72538         return node;
72539     }
72540     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
72541         var node = ts.createNode(293 /* InputFiles */);
72542         if (!ts.isString(javascriptTextOrReadFileText)) {
72543             var cache_1 = ts.createMap();
72544             var textGetter_1 = function (path) {
72545                 if (path === undefined)
72546                     return undefined;
72547                 var value = cache_1.get(path);
72548                 if (value === undefined) {
72549                     value = javascriptTextOrReadFileText(path);
72550                     cache_1.set(path, value !== undefined ? value : false);
72551                 }
72552                 return value !== false ? value : undefined;
72553             };
72554             var definedTextGetter_1 = function (path) {
72555                 var result = textGetter_1(path);
72556                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
72557             };
72558             var buildInfo_1;
72559             var getAndCacheBuildInfo_1 = function (getText) {
72560                 if (buildInfo_1 === undefined) {
72561                     var result = getText();
72562                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
72563                 }
72564                 return buildInfo_1 || undefined;
72565             };
72566             node.javascriptPath = declarationTextOrJavascriptPath;
72567             node.javascriptMapPath = javascriptMapPath;
72568             node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath);
72569             node.declarationMapPath = declarationMapPath;
72570             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
72571             Object.defineProperties(node, {
72572                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
72573                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
72574                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } },
72575                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
72576                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
72577             });
72578         }
72579         else {
72580             node.javascriptText = javascriptTextOrReadFileText;
72581             node.javascriptMapPath = javascriptMapPath;
72582             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
72583             node.declarationText = declarationTextOrJavascriptPath;
72584             node.declarationMapPath = declarationMapPath;
72585             node.declarationMapText = declarationMapTextOrBuildInfoPath;
72586             node.javascriptPath = javascriptPath;
72587             node.declarationPath = declarationPath;
72588             node.buildInfoPath = buildInfoPath;
72589             node.buildInfo = buildInfo;
72590             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
72591         }
72592         return node;
72593     }
72594     ts.createInputFiles = createInputFiles;
72595     function updateBundle(node, sourceFiles, prepends) {
72596         if (prepends === void 0) { prepends = ts.emptyArray; }
72597         if (node.sourceFiles !== sourceFiles || node.prepends !== prepends) {
72598             return createBundle(sourceFiles, prepends);
72599         }
72600         return node;
72601     }
72602     ts.updateBundle = updateBundle;
72603     function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
72604         return createCall(createFunctionExpression(
72605         /*modifiers*/ undefined, 
72606         /*asteriskToken*/ undefined, 
72607         /*name*/ undefined, 
72608         /*typeParameters*/ undefined, 
72609         /*parameters*/ param ? [param] : [], 
72610         /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72611         /*typeArguments*/ undefined, 
72612         /*argumentsArray*/ paramValue ? [paramValue] : []);
72613     }
72614     ts.createImmediatelyInvokedFunctionExpression = createImmediatelyInvokedFunctionExpression;
72615     function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
72616         return createCall(createArrowFunction(
72617         /*modifiers*/ undefined, 
72618         /*typeParameters*/ undefined, 
72619         /*parameters*/ param ? [param] : [], 
72620         /*type*/ undefined, 
72621         /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
72622         /*typeArguments*/ undefined, 
72623         /*argumentsArray*/ paramValue ? [paramValue] : []);
72624     }
72625     ts.createImmediatelyInvokedArrowFunction = createImmediatelyInvokedArrowFunction;
72626     function createComma(left, right) {
72627         return createBinary(left, 27 /* CommaToken */, right);
72628     }
72629     ts.createComma = createComma;
72630     function createLessThan(left, right) {
72631         return createBinary(left, 29 /* LessThanToken */, right);
72632     }
72633     ts.createLessThan = createLessThan;
72634     function createAssignment(left, right) {
72635         return createBinary(left, 62 /* EqualsToken */, right);
72636     }
72637     ts.createAssignment = createAssignment;
72638     function createStrictEquality(left, right) {
72639         return createBinary(left, 36 /* EqualsEqualsEqualsToken */, right);
72640     }
72641     ts.createStrictEquality = createStrictEquality;
72642     function createStrictInequality(left, right) {
72643         return createBinary(left, 37 /* ExclamationEqualsEqualsToken */, right);
72644     }
72645     ts.createStrictInequality = createStrictInequality;
72646     function createAdd(left, right) {
72647         return createBinary(left, 39 /* PlusToken */, right);
72648     }
72649     ts.createAdd = createAdd;
72650     function createSubtract(left, right) {
72651         return createBinary(left, 40 /* MinusToken */, right);
72652     }
72653     ts.createSubtract = createSubtract;
72654     function createPostfixIncrement(operand) {
72655         return createPostfix(operand, 45 /* PlusPlusToken */);
72656     }
72657     ts.createPostfixIncrement = createPostfixIncrement;
72658     function createLogicalAnd(left, right) {
72659         return createBinary(left, 55 /* AmpersandAmpersandToken */, right);
72660     }
72661     ts.createLogicalAnd = createLogicalAnd;
72662     function createLogicalOr(left, right) {
72663         return createBinary(left, 56 /* BarBarToken */, right);
72664     }
72665     ts.createLogicalOr = createLogicalOr;
72666     function createNullishCoalesce(left, right) {
72667         return createBinary(left, 60 /* QuestionQuestionToken */, right);
72668     }
72669     ts.createNullishCoalesce = createNullishCoalesce;
72670     function createLogicalNot(operand) {
72671         return createPrefix(53 /* ExclamationToken */, operand);
72672     }
72673     ts.createLogicalNot = createLogicalNot;
72674     function createVoidZero() {
72675         return createVoid(createLiteral(0));
72676     }
72677     ts.createVoidZero = createVoidZero;
72678     function createExportDefault(expression) {
72679         return createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportEquals*/ false, expression);
72680     }
72681     ts.createExportDefault = createExportDefault;
72682     function createExternalModuleExport(exportName) {
72683         return createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([createExportSpecifier(/*propertyName*/ undefined, exportName)]));
72684     }
72685     ts.createExternalModuleExport = createExternalModuleExport;
72686     // Utilities
72687     function asName(name) {
72688         return ts.isString(name) ? createIdentifier(name) : name;
72689     }
72690     function asExpression(value) {
72691         return typeof value === "string" ? createStringLiteral(value) :
72692             typeof value === "number" ? createNumericLiteral("" + value) :
72693                 typeof value === "boolean" ? value ? createTrue() : createFalse() :
72694                     value;
72695     }
72696     function asNodeArray(array) {
72697         return array ? createNodeArray(array) : undefined;
72698     }
72699     function asToken(value) {
72700         return typeof value === "number" ? createToken(value) : value;
72701     }
72702     function asEmbeddedStatement(statement) {
72703         return statement && ts.isNotEmittedStatement(statement) ? setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
72704     }
72705     /**
72706      * Clears any EmitNode entries from parse-tree nodes.
72707      * @param sourceFile A source file.
72708      */
72709     function disposeEmitNodes(sourceFile) {
72710         // During transformation we may need to annotate a parse tree node with transient
72711         // transformation properties. As parse tree nodes live longer than transformation
72712         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
72713         // from these nodes to ensure we do not hold onto entire subtrees just for position
72714         // information. We also need to reset these nodes to a pre-transformation state
72715         // for incremental parsing scenarios so that we do not impact later emit.
72716         sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile));
72717         var emitNode = sourceFile && sourceFile.emitNode;
72718         var annotatedNodes = emitNode && emitNode.annotatedNodes;
72719         if (annotatedNodes) {
72720             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
72721                 var node = annotatedNodes_1[_i];
72722                 node.emitNode = undefined;
72723             }
72724         }
72725     }
72726     ts.disposeEmitNodes = disposeEmitNodes;
72727     /**
72728      * Associates a node with the current transformation, initializing
72729      * various transient transformation properties.
72730      */
72731     /* @internal */
72732     function getOrCreateEmitNode(node) {
72733         if (!node.emitNode) {
72734             if (ts.isParseTreeNode(node)) {
72735                 // To avoid holding onto transformation artifacts, we keep track of any
72736                 // parse tree node we are annotating. This allows us to clean them up after
72737                 // all transformations have completed.
72738                 if (node.kind === 290 /* SourceFile */) {
72739                     return node.emitNode = { annotatedNodes: [node] };
72740                 }
72741                 var sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)));
72742                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
72743             }
72744             node.emitNode = {};
72745         }
72746         return node.emitNode;
72747     }
72748     ts.getOrCreateEmitNode = getOrCreateEmitNode;
72749     /**
72750      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
72751      * @internal
72752      */
72753     function removeAllComments(node) {
72754         var emitNode = getOrCreateEmitNode(node);
72755         emitNode.flags |= 1536 /* NoComments */;
72756         emitNode.leadingComments = undefined;
72757         emitNode.trailingComments = undefined;
72758         return node;
72759     }
72760     ts.removeAllComments = removeAllComments;
72761     function setTextRange(range, location) {
72762         if (location) {
72763             range.pos = location.pos;
72764             range.end = location.end;
72765         }
72766         return range;
72767     }
72768     ts.setTextRange = setTextRange;
72769     /**
72770      * Sets flags that control emit behavior of a node.
72771      */
72772     function setEmitFlags(node, emitFlags) {
72773         getOrCreateEmitNode(node).flags = emitFlags;
72774         return node;
72775     }
72776     ts.setEmitFlags = setEmitFlags;
72777     /**
72778      * Sets flags that control emit behavior of a node.
72779      */
72780     /* @internal */
72781     function addEmitFlags(node, emitFlags) {
72782         var emitNode = getOrCreateEmitNode(node);
72783         emitNode.flags = emitNode.flags | emitFlags;
72784         return node;
72785     }
72786     ts.addEmitFlags = addEmitFlags;
72787     /**
72788      * Gets a custom text range to use when emitting source maps.
72789      */
72790     function getSourceMapRange(node) {
72791         var emitNode = node.emitNode;
72792         return (emitNode && emitNode.sourceMapRange) || node;
72793     }
72794     ts.getSourceMapRange = getSourceMapRange;
72795     /**
72796      * Sets a custom text range to use when emitting source maps.
72797      */
72798     function setSourceMapRange(node, range) {
72799         getOrCreateEmitNode(node).sourceMapRange = range;
72800         return node;
72801     }
72802     ts.setSourceMapRange = setSourceMapRange;
72803     var SourceMapSource;
72804     /**
72805      * Create an external source map source file reference
72806      */
72807     function createSourceMapSource(fileName, text, skipTrivia) {
72808         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
72809     }
72810     ts.createSourceMapSource = createSourceMapSource;
72811     /**
72812      * Gets the TextRange to use for source maps for a token of a node.
72813      */
72814     function getTokenSourceMapRange(node, token) {
72815         var emitNode = node.emitNode;
72816         var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges;
72817         return tokenSourceMapRanges && tokenSourceMapRanges[token];
72818     }
72819     ts.getTokenSourceMapRange = getTokenSourceMapRange;
72820     /**
72821      * Sets the TextRange to use for source maps for a token of a node.
72822      */
72823     function setTokenSourceMapRange(node, token, range) {
72824         var emitNode = getOrCreateEmitNode(node);
72825         var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = []);
72826         tokenSourceMapRanges[token] = range;
72827         return node;
72828     }
72829     ts.setTokenSourceMapRange = setTokenSourceMapRange;
72830     /**
72831      * Gets a custom text range to use when emitting comments.
72832      */
72833     /*@internal*/
72834     function getStartsOnNewLine(node) {
72835         var emitNode = node.emitNode;
72836         return emitNode && emitNode.startsOnNewLine;
72837     }
72838     ts.getStartsOnNewLine = getStartsOnNewLine;
72839     /**
72840      * Sets a custom text range to use when emitting comments.
72841      */
72842     /*@internal*/
72843     function setStartsOnNewLine(node, newLine) {
72844         getOrCreateEmitNode(node).startsOnNewLine = newLine;
72845         return node;
72846     }
72847     ts.setStartsOnNewLine = setStartsOnNewLine;
72848     /**
72849      * Gets a custom text range to use when emitting comments.
72850      */
72851     function getCommentRange(node) {
72852         var emitNode = node.emitNode;
72853         return (emitNode && emitNode.commentRange) || node;
72854     }
72855     ts.getCommentRange = getCommentRange;
72856     /**
72857      * Sets a custom text range to use when emitting comments.
72858      */
72859     function setCommentRange(node, range) {
72860         getOrCreateEmitNode(node).commentRange = range;
72861         return node;
72862     }
72863     ts.setCommentRange = setCommentRange;
72864     function getSyntheticLeadingComments(node) {
72865         var emitNode = node.emitNode;
72866         return emitNode && emitNode.leadingComments;
72867     }
72868     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
72869     function setSyntheticLeadingComments(node, comments) {
72870         getOrCreateEmitNode(node).leadingComments = comments;
72871         return node;
72872     }
72873     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
72874     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
72875         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72876     }
72877     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
72878     function getSyntheticTrailingComments(node) {
72879         var emitNode = node.emitNode;
72880         return emitNode && emitNode.trailingComments;
72881     }
72882     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
72883     function setSyntheticTrailingComments(node, comments) {
72884         getOrCreateEmitNode(node).trailingComments = comments;
72885         return node;
72886     }
72887     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
72888     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
72889         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
72890     }
72891     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
72892     function moveSyntheticComments(node, original) {
72893         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
72894         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
72895         var emit = getOrCreateEmitNode(original);
72896         emit.leadingComments = undefined;
72897         emit.trailingComments = undefined;
72898         return node;
72899     }
72900     ts.moveSyntheticComments = moveSyntheticComments;
72901     /** @internal */
72902     function ignoreSourceNewlines(node) {
72903         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
72904         return node;
72905     }
72906     ts.ignoreSourceNewlines = ignoreSourceNewlines;
72907     /**
72908      * Gets the constant value to emit for an expression.
72909      */
72910     function getConstantValue(node) {
72911         var emitNode = node.emitNode;
72912         return emitNode && emitNode.constantValue;
72913     }
72914     ts.getConstantValue = getConstantValue;
72915     /**
72916      * Sets the constant value to emit for an expression.
72917      */
72918     function setConstantValue(node, value) {
72919         var emitNode = getOrCreateEmitNode(node);
72920         emitNode.constantValue = value;
72921         return node;
72922     }
72923     ts.setConstantValue = setConstantValue;
72924     /**
72925      * Adds an EmitHelper to a node.
72926      */
72927     function addEmitHelper(node, helper) {
72928         var emitNode = getOrCreateEmitNode(node);
72929         emitNode.helpers = ts.append(emitNode.helpers, helper);
72930         return node;
72931     }
72932     ts.addEmitHelper = addEmitHelper;
72933     /**
72934      * Add EmitHelpers to a node.
72935      */
72936     function addEmitHelpers(node, helpers) {
72937         if (ts.some(helpers)) {
72938             var emitNode = getOrCreateEmitNode(node);
72939             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
72940                 var helper = helpers_1[_i];
72941                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
72942             }
72943         }
72944         return node;
72945     }
72946     ts.addEmitHelpers = addEmitHelpers;
72947     /**
72948      * Removes an EmitHelper from a node.
72949      */
72950     function removeEmitHelper(node, helper) {
72951         var emitNode = node.emitNode;
72952         if (emitNode) {
72953             var helpers = emitNode.helpers;
72954             if (helpers) {
72955                 return ts.orderedRemoveItem(helpers, helper);
72956             }
72957         }
72958         return false;
72959     }
72960     ts.removeEmitHelper = removeEmitHelper;
72961     /**
72962      * Gets the EmitHelpers of a node.
72963      */
72964     function getEmitHelpers(node) {
72965         var emitNode = node.emitNode;
72966         return emitNode && emitNode.helpers;
72967     }
72968     ts.getEmitHelpers = getEmitHelpers;
72969     /**
72970      * Moves matching emit helpers from a source node to a target node.
72971      */
72972     function moveEmitHelpers(source, target, predicate) {
72973         var sourceEmitNode = source.emitNode;
72974         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
72975         if (!ts.some(sourceEmitHelpers))
72976             return;
72977         var targetEmitNode = getOrCreateEmitNode(target);
72978         var helpersRemoved = 0;
72979         for (var i = 0; i < sourceEmitHelpers.length; i++) {
72980             var helper = sourceEmitHelpers[i];
72981             if (predicate(helper)) {
72982                 helpersRemoved++;
72983                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
72984             }
72985             else if (helpersRemoved > 0) {
72986                 sourceEmitHelpers[i - helpersRemoved] = helper;
72987             }
72988         }
72989         if (helpersRemoved > 0) {
72990             sourceEmitHelpers.length -= helpersRemoved;
72991         }
72992     }
72993     ts.moveEmitHelpers = moveEmitHelpers;
72994     /* @internal */
72995     function compareEmitHelpers(x, y) {
72996         if (x === y)
72997             return 0 /* EqualTo */;
72998         if (x.priority === y.priority)
72999             return 0 /* EqualTo */;
73000         if (x.priority === undefined)
73001             return 1 /* GreaterThan */;
73002         if (y.priority === undefined)
73003             return -1 /* LessThan */;
73004         return ts.compareValues(x.priority, y.priority);
73005     }
73006     ts.compareEmitHelpers = compareEmitHelpers;
73007     function setOriginalNode(node, original) {
73008         node.original = original;
73009         if (original) {
73010             var emitNode = original.emitNode;
73011             if (emitNode)
73012                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
73013         }
73014         return node;
73015     }
73016     ts.setOriginalNode = setOriginalNode;
73017     function mergeEmitNode(sourceEmitNode, destEmitNode) {
73018         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;
73019         if (!destEmitNode)
73020             destEmitNode = {};
73021         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
73022         if (leadingComments)
73023             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
73024         if (trailingComments)
73025             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
73026         if (flags)
73027             destEmitNode.flags = flags;
73028         if (commentRange)
73029             destEmitNode.commentRange = commentRange;
73030         if (sourceMapRange)
73031             destEmitNode.sourceMapRange = sourceMapRange;
73032         if (tokenSourceMapRanges)
73033             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
73034         if (constantValue !== undefined)
73035             destEmitNode.constantValue = constantValue;
73036         if (helpers)
73037             destEmitNode.helpers = ts.addRange(destEmitNode.helpers, helpers);
73038         if (startsOnNewLine !== undefined)
73039             destEmitNode.startsOnNewLine = startsOnNewLine;
73040         return destEmitNode;
73041     }
73042     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
73043         if (!destRanges)
73044             destRanges = [];
73045         for (var key in sourceRanges) {
73046             destRanges[key] = sourceRanges[key];
73047         }
73048         return destRanges;
73049     }
73050 })(ts || (ts = {}));
73051 /* @internal */
73052 var ts;
73053 (function (ts) {
73054     ts.nullTransformationContext = {
73055         enableEmitNotification: ts.noop,
73056         enableSubstitution: ts.noop,
73057         endLexicalEnvironment: ts.returnUndefined,
73058         getCompilerOptions: function () { return ({}); },
73059         getEmitHost: ts.notImplemented,
73060         getEmitResolver: ts.notImplemented,
73061         setLexicalEnvironmentFlags: ts.noop,
73062         getLexicalEnvironmentFlags: function () { return 0; },
73063         hoistFunctionDeclaration: ts.noop,
73064         hoistVariableDeclaration: ts.noop,
73065         addInitializationStatement: ts.noop,
73066         isEmitNotificationEnabled: ts.notImplemented,
73067         isSubstitutionEnabled: ts.notImplemented,
73068         onEmitNode: ts.noop,
73069         onSubstituteNode: ts.notImplemented,
73070         readEmitHelpers: ts.notImplemented,
73071         requestEmitHelper: ts.noop,
73072         resumeLexicalEnvironment: ts.noop,
73073         startLexicalEnvironment: ts.noop,
73074         suspendLexicalEnvironment: ts.noop,
73075         addDiagnostic: ts.noop,
73076     };
73077     function createTypeCheck(value, tag) {
73078         return tag === "undefined"
73079             ? ts.createStrictEquality(value, ts.createVoidZero())
73080             : ts.createStrictEquality(ts.createTypeOf(value), ts.createLiteral(tag));
73081     }
73082     ts.createTypeCheck = createTypeCheck;
73083     function createMemberAccessForPropertyName(target, memberName, location) {
73084         if (ts.isComputedPropertyName(memberName)) {
73085             return ts.setTextRange(ts.createElementAccess(target, memberName.expression), location);
73086         }
73087         else {
73088             var expression = ts.setTextRange((ts.isIdentifier(memberName) || ts.isPrivateIdentifier(memberName))
73089                 ? ts.createPropertyAccess(target, memberName)
73090                 : ts.createElementAccess(target, memberName), memberName);
73091             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
73092             return expression;
73093         }
73094     }
73095     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
73096     function createFunctionCall(func, thisArg, argumentsList, location) {
73097         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "call"), 
73098         /*typeArguments*/ undefined, __spreadArrays([
73099             thisArg
73100         ], argumentsList)), location);
73101     }
73102     ts.createFunctionCall = createFunctionCall;
73103     function createFunctionApply(func, thisArg, argumentsExpression, location) {
73104         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(func, "apply"), 
73105         /*typeArguments*/ undefined, [
73106             thisArg,
73107             argumentsExpression
73108         ]), location);
73109     }
73110     ts.createFunctionApply = createFunctionApply;
73111     function createArraySlice(array, start) {
73112         var argumentsList = [];
73113         if (start !== undefined) {
73114             argumentsList.push(typeof start === "number" ? ts.createLiteral(start) : start);
73115         }
73116         return ts.createCall(ts.createPropertyAccess(array, "slice"), /*typeArguments*/ undefined, argumentsList);
73117     }
73118     ts.createArraySlice = createArraySlice;
73119     function createArrayConcat(array, values) {
73120         return ts.createCall(ts.createPropertyAccess(array, "concat"), 
73121         /*typeArguments*/ undefined, values);
73122     }
73123     ts.createArrayConcat = createArrayConcat;
73124     function createMathPow(left, right, location) {
73125         return ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Math"), "pow"), 
73126         /*typeArguments*/ undefined, [left, right]), location);
73127     }
73128     ts.createMathPow = createMathPow;
73129     function createReactNamespace(reactNamespace, parent) {
73130         // To ensure the emit resolver can properly resolve the namespace, we need to
73131         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
73132         // flag and setting a parent node.
73133         var react = ts.createIdentifier(reactNamespace || "React");
73134         react.flags &= ~8 /* Synthesized */;
73135         // Set the parent that is in parse tree
73136         // this makes sure that parent chain is intact for checker to traverse complete scope tree
73137         react.parent = ts.getParseTreeNode(parent);
73138         return react;
73139     }
73140     function createJsxFactoryExpressionFromEntityName(jsxFactory, parent) {
73141         if (ts.isQualifiedName(jsxFactory)) {
73142             var left = createJsxFactoryExpressionFromEntityName(jsxFactory.left, parent);
73143             var right = ts.createIdentifier(ts.idText(jsxFactory.right));
73144             right.escapedText = jsxFactory.right.escapedText;
73145             return ts.createPropertyAccess(left, right);
73146         }
73147         else {
73148             return createReactNamespace(ts.idText(jsxFactory), parent);
73149         }
73150     }
73151     function createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parent) {
73152         return jsxFactoryEntity ?
73153             createJsxFactoryExpressionFromEntityName(jsxFactoryEntity, parent) :
73154             ts.createPropertyAccess(createReactNamespace(reactNamespace, parent), "createElement");
73155     }
73156     function createExpressionForJsxElement(jsxFactoryEntity, reactNamespace, tagName, props, children, parentElement, location) {
73157         var argumentsList = [tagName];
73158         if (props) {
73159             argumentsList.push(props);
73160         }
73161         if (children && children.length > 0) {
73162             if (!props) {
73163                 argumentsList.push(ts.createNull());
73164             }
73165             if (children.length > 1) {
73166                 for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
73167                     var child = children_2[_i];
73168                     startOnNewLine(child);
73169                     argumentsList.push(child);
73170                 }
73171             }
73172             else {
73173                 argumentsList.push(children[0]);
73174             }
73175         }
73176         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73177         /*typeArguments*/ undefined, argumentsList), location);
73178     }
73179     ts.createExpressionForJsxElement = createExpressionForJsxElement;
73180     function createExpressionForJsxFragment(jsxFactoryEntity, reactNamespace, children, parentElement, location) {
73181         var tagName = ts.createPropertyAccess(createReactNamespace(reactNamespace, parentElement), "Fragment");
73182         var argumentsList = [tagName];
73183         argumentsList.push(ts.createNull());
73184         if (children && children.length > 0) {
73185             if (children.length > 1) {
73186                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
73187                     var child = children_3[_i];
73188                     startOnNewLine(child);
73189                     argumentsList.push(child);
73190                 }
73191             }
73192             else {
73193                 argumentsList.push(children[0]);
73194             }
73195         }
73196         return ts.setTextRange(ts.createCall(createJsxFactoryExpression(jsxFactoryEntity, reactNamespace, parentElement), 
73197         /*typeArguments*/ undefined, argumentsList), location);
73198     }
73199     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
73200     // Helpers
73201     /**
73202      * Gets an identifier for the name of an *unscoped* emit helper.
73203      */
73204     function getUnscopedHelperName(name) {
73205         return ts.setEmitFlags(ts.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
73206     }
73207     ts.getUnscopedHelperName = getUnscopedHelperName;
73208     ts.valuesHelper = {
73209         name: "typescript:values",
73210         importName: "__values",
73211         scoped: false,
73212         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            };"
73213     };
73214     function createValuesHelper(context, expression, location) {
73215         context.requestEmitHelper(ts.valuesHelper);
73216         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__values"), 
73217         /*typeArguments*/ undefined, [expression]), location);
73218     }
73219     ts.createValuesHelper = createValuesHelper;
73220     ts.readHelper = {
73221         name: "typescript:read",
73222         importName: "__read",
73223         scoped: false,
73224         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            };"
73225     };
73226     function createReadHelper(context, iteratorRecord, count, location) {
73227         context.requestEmitHelper(ts.readHelper);
73228         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__read"), 
73229         /*typeArguments*/ undefined, count !== undefined
73230             ? [iteratorRecord, ts.createLiteral(count)]
73231             : [iteratorRecord]), location);
73232     }
73233     ts.createReadHelper = createReadHelper;
73234     ts.spreadHelper = {
73235         name: "typescript:spread",
73236         importName: "__spread",
73237         scoped: false,
73238         dependencies: [ts.readHelper],
73239         text: "\n            var __spread = (this && this.__spread) || function () {\n                for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n                return ar;\n            };"
73240     };
73241     function createSpreadHelper(context, argumentList, location) {
73242         context.requestEmitHelper(ts.spreadHelper);
73243         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spread"), 
73244         /*typeArguments*/ undefined, argumentList), location);
73245     }
73246     ts.createSpreadHelper = createSpreadHelper;
73247     ts.spreadArraysHelper = {
73248         name: "typescript:spreadArrays",
73249         importName: "__spreadArrays",
73250         scoped: false,
73251         text: "\n            var __spreadArrays = (this && this.__spreadArrays) || function () {\n                for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n                for (var r = Array(s), k = 0, i = 0; i < il; i++)\n                    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n                        r[k] = a[j];\n                return r;\n            };"
73252     };
73253     function createSpreadArraysHelper(context, argumentList, location) {
73254         context.requestEmitHelper(ts.spreadArraysHelper);
73255         return ts.setTextRange(ts.createCall(getUnscopedHelperName("__spreadArrays"), 
73256         /*typeArguments*/ undefined, argumentList), location);
73257     }
73258     ts.createSpreadArraysHelper = createSpreadArraysHelper;
73259     // Utilities
73260     function createForOfBindingStatement(node, boundValue) {
73261         if (ts.isVariableDeclarationList(node)) {
73262             var firstDeclaration = ts.first(node.declarations);
73263             var updatedDeclaration = ts.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
73264             /*typeNode*/ undefined, boundValue);
73265             return ts.setTextRange(ts.createVariableStatement(
73266             /*modifiers*/ undefined, ts.updateVariableDeclarationList(node, [updatedDeclaration])), 
73267             /*location*/ node);
73268         }
73269         else {
73270             var updatedExpression = ts.setTextRange(ts.createAssignment(node, boundValue), /*location*/ node);
73271             return ts.setTextRange(ts.createStatement(updatedExpression), /*location*/ node);
73272         }
73273     }
73274     ts.createForOfBindingStatement = createForOfBindingStatement;
73275     function insertLeadingStatement(dest, source) {
73276         if (ts.isBlock(dest)) {
73277             return ts.updateBlock(dest, ts.setTextRange(ts.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
73278         }
73279         else {
73280             return ts.createBlock(ts.createNodeArray([dest, source]), /*multiLine*/ true);
73281         }
73282     }
73283     ts.insertLeadingStatement = insertLeadingStatement;
73284     function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
73285         if (!outermostLabeledStatement) {
73286             return node;
73287         }
73288         var updated = ts.updateLabel(outermostLabeledStatement, outermostLabeledStatement.label, outermostLabeledStatement.statement.kind === 238 /* LabeledStatement */
73289             ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
73290             : node);
73291         if (afterRestoreLabelCallback) {
73292             afterRestoreLabelCallback(outermostLabeledStatement);
73293         }
73294         return updated;
73295     }
73296     ts.restoreEnclosingLabel = restoreEnclosingLabel;
73297     function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
73298         var target = ts.skipParentheses(node);
73299         switch (target.kind) {
73300             case 75 /* Identifier */:
73301                 return cacheIdentifiers;
73302             case 104 /* ThisKeyword */:
73303             case 8 /* NumericLiteral */:
73304             case 9 /* BigIntLiteral */:
73305             case 10 /* StringLiteral */:
73306                 return false;
73307             case 192 /* ArrayLiteralExpression */:
73308                 var elements = target.elements;
73309                 if (elements.length === 0) {
73310                     return false;
73311                 }
73312                 return true;
73313             case 193 /* ObjectLiteralExpression */:
73314                 return target.properties.length > 0;
73315             default:
73316                 return true;
73317         }
73318     }
73319     function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
73320         if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
73321         var callee = skipOuterExpressions(expression, 15 /* All */);
73322         var thisArg;
73323         var target;
73324         if (ts.isSuperProperty(callee)) {
73325             thisArg = ts.createThis();
73326             target = callee;
73327         }
73328         else if (callee.kind === 102 /* SuperKeyword */) {
73329             thisArg = ts.createThis();
73330             target = languageVersion < 2 /* ES2015 */
73331                 ? ts.setTextRange(ts.createIdentifier("_super"), callee)
73332                 : callee;
73333         }
73334         else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
73335             thisArg = ts.createVoidZero();
73336             target = parenthesizeForAccess(callee);
73337         }
73338         else {
73339             switch (callee.kind) {
73340                 case 194 /* PropertyAccessExpression */: {
73341                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73342                         // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
73343                         thisArg = ts.createTempVariable(recordTempVariable);
73344                         target = ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
73345                         ts.setTextRange(target, callee);
73346                     }
73347                     else {
73348                         thisArg = callee.expression;
73349                         target = callee;
73350                     }
73351                     break;
73352                 }
73353                 case 195 /* ElementAccessExpression */: {
73354                     if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
73355                         // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
73356                         thisArg = ts.createTempVariable(recordTempVariable);
73357                         target = ts.createElementAccess(ts.setTextRange(ts.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
73358                         ts.setTextRange(target, callee);
73359                     }
73360                     else {
73361                         thisArg = callee.expression;
73362                         target = callee;
73363                     }
73364                     break;
73365                 }
73366                 default: {
73367                     // for `a()` target is `a` and thisArg is `void 0`
73368                     thisArg = ts.createVoidZero();
73369                     target = parenthesizeForAccess(expression);
73370                     break;
73371                 }
73372             }
73373         }
73374         return { target: target, thisArg: thisArg };
73375     }
73376     ts.createCallBinding = createCallBinding;
73377     function inlineExpressions(expressions) {
73378         // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
73379         // stack size exceeded" errors.
73380         return expressions.length > 10
73381             ? ts.createCommaList(expressions)
73382             : ts.reduceLeft(expressions, ts.createComma);
73383     }
73384     ts.inlineExpressions = inlineExpressions;
73385     function createExpressionFromEntityName(node) {
73386         if (ts.isQualifiedName(node)) {
73387             var left = createExpressionFromEntityName(node.left);
73388             var right = ts.getMutableClone(node.right);
73389             return ts.setTextRange(ts.createPropertyAccess(left, right), node);
73390         }
73391         else {
73392             return ts.getMutableClone(node);
73393         }
73394     }
73395     ts.createExpressionFromEntityName = createExpressionFromEntityName;
73396     function createExpressionForPropertyName(memberName) {
73397         if (ts.isIdentifier(memberName)) {
73398             return ts.createLiteral(memberName);
73399         }
73400         else if (ts.isComputedPropertyName(memberName)) {
73401             return ts.getMutableClone(memberName.expression);
73402         }
73403         else {
73404             return ts.getMutableClone(memberName);
73405         }
73406     }
73407     ts.createExpressionForPropertyName = createExpressionForPropertyName;
73408     function createExpressionForObjectLiteralElementLike(node, property, receiver) {
73409         if (property.name && ts.isPrivateIdentifier(property.name)) {
73410             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
73411         }
73412         switch (property.kind) {
73413             case 163 /* GetAccessor */:
73414             case 164 /* SetAccessor */:
73415                 return createExpressionForAccessorDeclaration(node.properties, property, receiver, !!node.multiLine);
73416             case 281 /* PropertyAssignment */:
73417                 return createExpressionForPropertyAssignment(property, receiver);
73418             case 282 /* ShorthandPropertyAssignment */:
73419                 return createExpressionForShorthandPropertyAssignment(property, receiver);
73420             case 161 /* MethodDeclaration */:
73421                 return createExpressionForMethodDeclaration(property, receiver);
73422         }
73423     }
73424     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
73425     function createExpressionForAccessorDeclaration(properties, property, receiver, multiLine) {
73426         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
73427         if (property === firstAccessor) {
73428             var properties_7 = [];
73429             if (getAccessor) {
73430                 var getterFunction = ts.createFunctionExpression(getAccessor.modifiers, 
73431                 /*asteriskToken*/ undefined, 
73432                 /*name*/ undefined, 
73433                 /*typeParameters*/ undefined, getAccessor.parameters, 
73434                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
73435                 );
73436                 ts.setTextRange(getterFunction, getAccessor);
73437                 ts.setOriginalNode(getterFunction, getAccessor);
73438                 var getter = ts.createPropertyAssignment("get", getterFunction);
73439                 properties_7.push(getter);
73440             }
73441             if (setAccessor) {
73442                 var setterFunction = ts.createFunctionExpression(setAccessor.modifiers, 
73443                 /*asteriskToken*/ undefined, 
73444                 /*name*/ undefined, 
73445                 /*typeParameters*/ undefined, setAccessor.parameters, 
73446                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
73447                 );
73448                 ts.setTextRange(setterFunction, setAccessor);
73449                 ts.setOriginalNode(setterFunction, setAccessor);
73450                 var setter = ts.createPropertyAssignment("set", setterFunction);
73451                 properties_7.push(setter);
73452             }
73453             properties_7.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()));
73454             properties_7.push(ts.createPropertyAssignment("configurable", ts.createTrue()));
73455             var expression = ts.setTextRange(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
73456             /*typeArguments*/ undefined, [
73457                 receiver,
73458                 createExpressionForPropertyName(property.name),
73459                 ts.createObjectLiteral(properties_7, multiLine)
73460             ]), 
73461             /*location*/ firstAccessor);
73462             return ts.aggregateTransformFlags(expression);
73463         }
73464         return undefined;
73465     }
73466     function createExpressionForPropertyAssignment(property, receiver) {
73467         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), property.initializer), property), property));
73468     }
73469     function createExpressionForShorthandPropertyAssignment(property, receiver) {
73470         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, property.name, /*location*/ property.name), ts.getSynthesizedClone(property.name)), 
73471         /*location*/ property), 
73472         /*original*/ property));
73473     }
73474     function createExpressionForMethodDeclaration(method, receiver) {
73475         return ts.aggregateTransformFlags(ts.setOriginalNode(ts.setTextRange(ts.createAssignment(createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(method.modifiers, method.asteriskToken, 
73476         /*name*/ undefined, 
73477         /*typeParameters*/ undefined, method.parameters, 
73478         /*type*/ undefined, method.body // TODO: GH#18217
73479         ), 
73480         /*location*/ method), 
73481         /*original*/ method)), 
73482         /*location*/ method), 
73483         /*original*/ method));
73484     }
73485     /**
73486      * Gets the internal name of a declaration. This is primarily used for declarations that can be
73487      * referred to by name in the body of an ES5 class function body. An internal name will *never*
73488      * be prefixed with an module or namespace export modifier like "exports." when emitted as an
73489      * expression. An internal name will also *never* be renamed due to a collision with a block
73490      * scoped variable.
73491      *
73492      * @param node The declaration.
73493      * @param allowComments A value indicating whether comments may be emitted for the name.
73494      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73495      */
73496     function getInternalName(node, allowComments, allowSourceMaps) {
73497         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
73498     }
73499     ts.getInternalName = getInternalName;
73500     /**
73501      * Gets whether an identifier should only be referred to by its internal name.
73502      */
73503     function isInternalName(node) {
73504         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
73505     }
73506     ts.isInternalName = isInternalName;
73507     /**
73508      * Gets the local name of a declaration. This is primarily used for declarations that can be
73509      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
73510      * local name will *never* be prefixed with an module or namespace export modifier like
73511      * "exports." when emitted as an expression.
73512      *
73513      * @param node The declaration.
73514      * @param allowComments A value indicating whether comments may be emitted for the name.
73515      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73516      */
73517     function getLocalName(node, allowComments, allowSourceMaps) {
73518         return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
73519     }
73520     ts.getLocalName = getLocalName;
73521     /**
73522      * Gets whether an identifier should only be referred to by its local name.
73523      */
73524     function isLocalName(node) {
73525         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
73526     }
73527     ts.isLocalName = isLocalName;
73528     /**
73529      * Gets the export name of a declaration. This is primarily used for declarations that can be
73530      * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
73531      * export name will *always* be prefixed with an module or namespace export modifier like
73532      * `"exports."` when emitted as an expression if the name points to an exported symbol.
73533      *
73534      * @param node The declaration.
73535      * @param allowComments A value indicating whether comments may be emitted for the name.
73536      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73537      */
73538     function getExportName(node, allowComments, allowSourceMaps) {
73539         return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
73540     }
73541     ts.getExportName = getExportName;
73542     /**
73543      * Gets whether an identifier should only be referred to by its export representation if the
73544      * name points to an exported symbol.
73545      */
73546     function isExportName(node) {
73547         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
73548     }
73549     ts.isExportName = isExportName;
73550     /**
73551      * Gets the name of a declaration for use in declarations.
73552      *
73553      * @param node The declaration.
73554      * @param allowComments A value indicating whether comments may be emitted for the name.
73555      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73556      */
73557     function getDeclarationName(node, allowComments, allowSourceMaps) {
73558         return getName(node, allowComments, allowSourceMaps);
73559     }
73560     ts.getDeclarationName = getDeclarationName;
73561     function getName(node, allowComments, allowSourceMaps, emitFlags) {
73562         if (emitFlags === void 0) { emitFlags = 0; }
73563         var nodeName = ts.getNameOfDeclaration(node);
73564         if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
73565             var name = ts.getMutableClone(nodeName);
73566             emitFlags |= ts.getEmitFlags(nodeName);
73567             if (!allowSourceMaps)
73568                 emitFlags |= 48 /* NoSourceMap */;
73569             if (!allowComments)
73570                 emitFlags |= 1536 /* NoComments */;
73571             if (emitFlags)
73572                 ts.setEmitFlags(name, emitFlags);
73573             return name;
73574         }
73575         return ts.getGeneratedNameForNode(node);
73576     }
73577     /**
73578      * Gets the exported name of a declaration for use in expressions.
73579      *
73580      * An exported name will *always* be prefixed with an module or namespace export modifier like
73581      * "exports." if the name points to an exported symbol.
73582      *
73583      * @param ns The namespace identifier.
73584      * @param node The declaration.
73585      * @param allowComments A value indicating whether comments may be emitted for the name.
73586      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73587      */
73588     function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
73589         if (ns && ts.hasModifier(node, 1 /* Export */)) {
73590             return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
73591         }
73592         return getExportName(node, allowComments, allowSourceMaps);
73593     }
73594     ts.getExternalModuleOrNamespaceExportName = getExternalModuleOrNamespaceExportName;
73595     /**
73596      * Gets a namespace-qualified name for use in expressions.
73597      *
73598      * @param ns The namespace identifier.
73599      * @param name The name.
73600      * @param allowComments A value indicating whether comments may be emitted for the name.
73601      * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
73602      */
73603     function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
73604         var qualifiedName = ts.createPropertyAccess(ns, ts.nodeIsSynthesized(name) ? name : ts.getSynthesizedClone(name));
73605         ts.setTextRange(qualifiedName, name);
73606         var emitFlags = 0;
73607         if (!allowSourceMaps)
73608             emitFlags |= 48 /* NoSourceMap */;
73609         if (!allowComments)
73610             emitFlags |= 1536 /* NoComments */;
73611         if (emitFlags)
73612             ts.setEmitFlags(qualifiedName, emitFlags);
73613         return qualifiedName;
73614     }
73615     ts.getNamespaceMemberName = getNamespaceMemberName;
73616     function convertToFunctionBody(node, multiLine) {
73617         return ts.isBlock(node) ? node : ts.setTextRange(ts.createBlock([ts.setTextRange(ts.createReturn(node), node)], multiLine), node);
73618     }
73619     ts.convertToFunctionBody = convertToFunctionBody;
73620     function convertFunctionDeclarationToExpression(node) {
73621         if (!node.body)
73622             return ts.Debug.fail();
73623         var updated = ts.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
73624         ts.setOriginalNode(updated, node);
73625         ts.setTextRange(updated, node);
73626         if (ts.getStartsOnNewLine(node)) {
73627             ts.setStartsOnNewLine(updated, /*newLine*/ true);
73628         }
73629         ts.aggregateTransformFlags(updated);
73630         return updated;
73631     }
73632     ts.convertFunctionDeclarationToExpression = convertFunctionDeclarationToExpression;
73633     function isUseStrictPrologue(node) {
73634         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
73635     }
73636     /**
73637      * Add any necessary prologue-directives into target statement-array.
73638      * The function needs to be called during each transformation step.
73639      * This function needs to be called whenever we transform the statement
73640      * list of a source file, namespace, or function-like body.
73641      *
73642      * @param target: result statements array
73643      * @param source: origin statements array
73644      * @param ensureUseStrict: boolean determining whether the function need to add prologue-directives
73645      * @param visitor: Optional callback used to visit any custom prologue directives.
73646      */
73647     function addPrologue(target, source, ensureUseStrict, visitor) {
73648         var offset = addStandardPrologue(target, source, ensureUseStrict);
73649         return addCustomPrologue(target, source, offset, visitor);
73650     }
73651     ts.addPrologue = addPrologue;
73652     /**
73653      * Add just the standard (string-expression) prologue-directives into target statement-array.
73654      * The function needs to be called during each transformation step.
73655      * This function needs to be called whenever we transform the statement
73656      * list of a source file, namespace, or function-like body.
73657      */
73658     function addStandardPrologue(target, source, ensureUseStrict) {
73659         ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
73660         var foundUseStrict = false;
73661         var statementOffset = 0;
73662         var numStatements = source.length;
73663         while (statementOffset < numStatements) {
73664             var statement = source[statementOffset];
73665             if (ts.isPrologueDirective(statement)) {
73666                 if (isUseStrictPrologue(statement)) {
73667                     foundUseStrict = true;
73668                 }
73669                 target.push(statement);
73670             }
73671             else {
73672                 break;
73673             }
73674             statementOffset++;
73675         }
73676         if (ensureUseStrict && !foundUseStrict) {
73677             target.push(startOnNewLine(ts.createStatement(ts.createLiteral("use strict"))));
73678         }
73679         return statementOffset;
73680     }
73681     ts.addStandardPrologue = addStandardPrologue;
73682     function addCustomPrologue(target, source, statementOffset, visitor, filter) {
73683         if (filter === void 0) { filter = ts.returnTrue; }
73684         var numStatements = source.length;
73685         while (statementOffset !== undefined && statementOffset < numStatements) {
73686             var statement = source[statementOffset];
73687             if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
73688                 ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
73689             }
73690             else {
73691                 break;
73692             }
73693             statementOffset++;
73694         }
73695         return statementOffset;
73696     }
73697     ts.addCustomPrologue = addCustomPrologue;
73698     function findUseStrictPrologue(statements) {
73699         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
73700             var statement = statements_4[_i];
73701             if (ts.isPrologueDirective(statement)) {
73702                 if (isUseStrictPrologue(statement)) {
73703                     return statement;
73704                 }
73705             }
73706             else {
73707                 break;
73708             }
73709         }
73710         return undefined;
73711     }
73712     ts.findUseStrictPrologue = findUseStrictPrologue;
73713     function startsWithUseStrict(statements) {
73714         var firstStatement = ts.firstOrUndefined(statements);
73715         return firstStatement !== undefined
73716             && ts.isPrologueDirective(firstStatement)
73717             && isUseStrictPrologue(firstStatement);
73718     }
73719     ts.startsWithUseStrict = startsWithUseStrict;
73720     /**
73721      * Ensures "use strict" directive is added
73722      *
73723      * @param statements An array of statements
73724      */
73725     function ensureUseStrict(statements) {
73726         var foundUseStrict = findUseStrictPrologue(statements);
73727         if (!foundUseStrict) {
73728             return ts.setTextRange(ts.createNodeArray(__spreadArrays([
73729                 startOnNewLine(ts.createStatement(ts.createLiteral("use strict")))
73730             ], statements)), statements);
73731         }
73732         return statements;
73733     }
73734     ts.ensureUseStrict = ensureUseStrict;
73735     /**
73736      * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
73737      * order of operations.
73738      *
73739      * @param binaryOperator The operator for the BinaryExpression.
73740      * @param operand The operand for the BinaryExpression.
73741      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73742      *                           BinaryExpression.
73743      */
73744     function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73745         var skipped = ts.skipPartiallyEmittedExpressions(operand);
73746         // If the resulting expression is already parenthesized, we do not need to do any further processing.
73747         if (skipped.kind === 200 /* ParenthesizedExpression */) {
73748             return operand;
73749         }
73750         return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
73751             ? ts.createParen(operand)
73752             : operand;
73753     }
73754     ts.parenthesizeBinaryOperand = parenthesizeBinaryOperand;
73755     /**
73756      * Determines whether the operand to a BinaryExpression needs to be parenthesized.
73757      *
73758      * @param binaryOperator The operator for the BinaryExpression.
73759      * @param operand The operand for the BinaryExpression.
73760      * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
73761      *                           BinaryExpression.
73762      */
73763     function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
73764         // If the operand has lower precedence, then it needs to be parenthesized to preserve the
73765         // intent of the expression. For example, if the operand is `a + b` and the operator is
73766         // `*`, then we need to parenthesize the operand to preserve the intended order of
73767         // operations: `(a + b) * x`.
73768         //
73769         // If the operand has higher precedence, then it does not need to be parenthesized. For
73770         // example, if the operand is `a * b` and the operator is `+`, then we do not need to
73771         // parenthesize to preserve the intended order of operations: `a * b + x`.
73772         //
73773         // If the operand has the same precedence, then we need to check the associativity of
73774         // the operator based on whether this is the left or right operand of the expression.
73775         //
73776         // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
73777         // to preserve the intended order of operations: `x * (a / d)`
73778         //
73779         // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
73780         // the intended order of operations: `(a ** b) ** c`
73781         var binaryOperatorPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, binaryOperator);
73782         var binaryOperatorAssociativity = ts.getOperatorAssociativity(209 /* BinaryExpression */, binaryOperator);
73783         var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
73784         if (!isLeftSideOfBinary && operand.kind === 202 /* ArrowFunction */ && binaryOperatorPrecedence > 3) {
73785             // We need to parenthesize arrow functions on the right side to avoid it being
73786             // parsed as parenthesized expression: `a && (() => {})`
73787             return true;
73788         }
73789         var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
73790         switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
73791             case -1 /* LessThan */:
73792                 // If the operand is the right side of a right-associative binary operation
73793                 // and is a yield expression, then we do not need parentheses.
73794                 if (!isLeftSideOfBinary
73795                     && binaryOperatorAssociativity === 1 /* Right */
73796                     && operand.kind === 212 /* YieldExpression */) {
73797                     return false;
73798                 }
73799                 return true;
73800             case 1 /* GreaterThan */:
73801                 return false;
73802             case 0 /* EqualTo */:
73803                 if (isLeftSideOfBinary) {
73804                     // No need to parenthesize the left operand when the binary operator is
73805                     // left associative:
73806                     //  (a*b)/x    -> a*b/x
73807                     //  (a**b)/x   -> a**b/x
73808                     //
73809                     // Parentheses are needed for the left operand when the binary operator is
73810                     // right associative:
73811                     //  (a/b)**x   -> (a/b)**x
73812                     //  (a**b)**x  -> (a**b)**x
73813                     return binaryOperatorAssociativity === 1 /* Right */;
73814                 }
73815                 else {
73816                     if (ts.isBinaryExpression(emittedOperand)
73817                         && emittedOperand.operatorToken.kind === binaryOperator) {
73818                         // No need to parenthesize the right operand when the binary operator and
73819                         // operand are the same and one of the following:
73820                         //  x*(a*b)     => x*a*b
73821                         //  x|(a|b)     => x|a|b
73822                         //  x&(a&b)     => x&a&b
73823                         //  x^(a^b)     => x^a^b
73824                         if (operatorHasAssociativeProperty(binaryOperator)) {
73825                             return false;
73826                         }
73827                         // No need to parenthesize the right operand when the binary operator
73828                         // is plus (+) if both the left and right operands consist solely of either
73829                         // literals of the same kind or binary plus (+) expressions for literals of
73830                         // the same kind (recursively).
73831                         //  "a"+(1+2)       => "a"+(1+2)
73832                         //  "a"+("b"+"c")   => "a"+"b"+"c"
73833                         if (binaryOperator === 39 /* PlusToken */) {
73834                             var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
73835                             if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
73836                                 return false;
73837                             }
73838                         }
73839                     }
73840                     // No need to parenthesize the right operand when the operand is right
73841                     // associative:
73842                     //  x/(a**b)    -> x/a**b
73843                     //  x**(a**b)   -> x**a**b
73844                     //
73845                     // Parentheses are needed for the right operand when the operand is left
73846                     // associative:
73847                     //  x/(a*b)     -> x/(a*b)
73848                     //  x**(a/b)    -> x**(a/b)
73849                     var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
73850                     return operandAssociativity === 0 /* Left */;
73851                 }
73852         }
73853     }
73854     /**
73855      * Determines whether a binary operator is mathematically associative.
73856      *
73857      * @param binaryOperator The binary operator.
73858      */
73859     function operatorHasAssociativeProperty(binaryOperator) {
73860         // The following operators are associative in JavaScript:
73861         //  (a*b)*c     -> a*(b*c)  -> a*b*c
73862         //  (a|b)|c     -> a|(b|c)  -> a|b|c
73863         //  (a&b)&c     -> a&(b&c)  -> a&b&c
73864         //  (a^b)^c     -> a^(b^c)  -> a^b^c
73865         //
73866         // While addition is associative in mathematics, JavaScript's `+` is not
73867         // guaranteed to be associative as it is overloaded with string concatenation.
73868         return binaryOperator === 41 /* AsteriskToken */
73869             || binaryOperator === 51 /* BarToken */
73870             || binaryOperator === 50 /* AmpersandToken */
73871             || binaryOperator === 52 /* CaretToken */;
73872     }
73873     /**
73874      * This function determines whether an expression consists of a homogeneous set of
73875      * literal expressions or binary plus expressions that all share the same literal kind.
73876      * It is used to determine whether the right-hand operand of a binary plus expression can be
73877      * emitted without parentheses.
73878      */
73879     function getLiteralKindOfBinaryPlusOperand(node) {
73880         node = ts.skipPartiallyEmittedExpressions(node);
73881         if (ts.isLiteralKind(node.kind)) {
73882             return node.kind;
73883         }
73884         if (node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
73885             if (node.cachedLiteralKind !== undefined) {
73886                 return node.cachedLiteralKind;
73887             }
73888             var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
73889             var literalKind = ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(node.right) ? leftKind :
73890                 0 /* Unknown */;
73891             node.cachedLiteralKind = literalKind;
73892             return literalKind;
73893         }
73894         return 0 /* Unknown */;
73895     }
73896     function parenthesizeForConditionalHead(condition) {
73897         var conditionalPrecedence = ts.getOperatorPrecedence(210 /* ConditionalExpression */, 57 /* QuestionToken */);
73898         var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
73899         var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
73900         if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
73901             return ts.createParen(condition);
73902         }
73903         return condition;
73904     }
73905     ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead;
73906     function parenthesizeSubexpressionOfConditionalExpression(e) {
73907         // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
73908         // so in case when comma expression is introduced as a part of previous transformations
73909         // if should be wrapped in parens since comma operator has the lowest precedence
73910         var emittedExpression = ts.skipPartiallyEmittedExpressions(e);
73911         return isCommaSequence(emittedExpression)
73912             ? ts.createParen(e)
73913             : e;
73914     }
73915     ts.parenthesizeSubexpressionOfConditionalExpression = parenthesizeSubexpressionOfConditionalExpression;
73916     /**
73917      *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
73918      *  has a lookahead restriction for `function`, `async function`, and `class`.
73919      *
73920      * Basically, that means we need to parenthesize in the following cases:
73921      *
73922      * - BinaryExpression of CommaToken
73923      * - CommaList (synthetic list of multiple comma expressions)
73924      * - FunctionExpression
73925      * - ClassExpression
73926      */
73927     function parenthesizeDefaultExpression(e) {
73928         var check = ts.skipPartiallyEmittedExpressions(e);
73929         var needsParens = isCommaSequence(check);
73930         if (!needsParens) {
73931             switch (getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
73932                 case 214 /* ClassExpression */:
73933                 case 201 /* FunctionExpression */:
73934                     needsParens = true;
73935             }
73936         }
73937         return needsParens ? ts.createParen(e) : e;
73938     }
73939     ts.parenthesizeDefaultExpression = parenthesizeDefaultExpression;
73940     /**
73941      * Wraps an expression in parentheses if it is needed in order to use the expression
73942      * as the expression of a NewExpression node.
73943      *
73944      * @param expression The Expression node.
73945      */
73946     function parenthesizeForNew(expression) {
73947         var leftmostExpr = getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
73948         switch (leftmostExpr.kind) {
73949             case 196 /* CallExpression */:
73950                 return ts.createParen(expression);
73951             case 197 /* NewExpression */:
73952                 return !leftmostExpr.arguments
73953                     ? ts.createParen(expression)
73954                     : expression;
73955         }
73956         return parenthesizeForAccess(expression);
73957     }
73958     ts.parenthesizeForNew = parenthesizeForNew;
73959     /**
73960      * Wraps an expression in parentheses if it is needed in order to use the expression for
73961      * property or element access.
73962      *
73963      * @param expr The expression node.
73964      */
73965     function parenthesizeForAccess(expression) {
73966         // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
73967         // to parenthesize the expression before a dot. The known exception is:
73968         //
73969         //    NewExpression:
73970         //       new C.x        -> not the same as (new C).x
73971         //
73972         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
73973         if (ts.isLeftHandSideExpression(emittedExpression)
73974             && (emittedExpression.kind !== 197 /* NewExpression */ || emittedExpression.arguments)) {
73975             return expression;
73976         }
73977         return ts.setTextRange(ts.createParen(expression), expression);
73978     }
73979     ts.parenthesizeForAccess = parenthesizeForAccess;
73980     function parenthesizePostfixOperand(operand) {
73981         return ts.isLeftHandSideExpression(operand)
73982             ? operand
73983             : ts.setTextRange(ts.createParen(operand), operand);
73984     }
73985     ts.parenthesizePostfixOperand = parenthesizePostfixOperand;
73986     function parenthesizePrefixOperand(operand) {
73987         return ts.isUnaryExpression(operand)
73988             ? operand
73989             : ts.setTextRange(ts.createParen(operand), operand);
73990     }
73991     ts.parenthesizePrefixOperand = parenthesizePrefixOperand;
73992     function parenthesizeListElements(elements) {
73993         var result;
73994         for (var i = 0; i < elements.length; i++) {
73995             var element = parenthesizeExpressionForList(elements[i]);
73996             if (result !== undefined || element !== elements[i]) {
73997                 if (result === undefined) {
73998                     result = elements.slice(0, i);
73999                 }
74000                 result.push(element);
74001             }
74002         }
74003         if (result !== undefined) {
74004             return ts.setTextRange(ts.createNodeArray(result, elements.hasTrailingComma), elements);
74005         }
74006         return elements;
74007     }
74008     ts.parenthesizeListElements = parenthesizeListElements;
74009     function parenthesizeExpressionForList(expression) {
74010         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74011         var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
74012         var commaPrecedence = ts.getOperatorPrecedence(209 /* BinaryExpression */, 27 /* CommaToken */);
74013         return expressionPrecedence > commaPrecedence
74014             ? expression
74015             : ts.setTextRange(ts.createParen(expression), expression);
74016     }
74017     ts.parenthesizeExpressionForList = parenthesizeExpressionForList;
74018     function parenthesizeExpressionForExpressionStatement(expression) {
74019         var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
74020         if (ts.isCallExpression(emittedExpression)) {
74021             var callee = emittedExpression.expression;
74022             var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
74023             if (kind === 201 /* FunctionExpression */ || kind === 202 /* ArrowFunction */) {
74024                 var mutableCall = ts.getMutableClone(emittedExpression);
74025                 mutableCall.expression = ts.setTextRange(ts.createParen(callee), callee);
74026                 return recreateOuterExpressions(expression, mutableCall, 8 /* PartiallyEmittedExpressions */);
74027             }
74028         }
74029         var leftmostExpressionKind = getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
74030         if (leftmostExpressionKind === 193 /* ObjectLiteralExpression */ || leftmostExpressionKind === 201 /* FunctionExpression */) {
74031             return ts.setTextRange(ts.createParen(expression), expression);
74032         }
74033         return expression;
74034     }
74035     ts.parenthesizeExpressionForExpressionStatement = parenthesizeExpressionForExpressionStatement;
74036     function parenthesizeConditionalTypeMember(member) {
74037         return member.kind === 180 /* ConditionalType */ ? ts.createParenthesizedType(member) : member;
74038     }
74039     ts.parenthesizeConditionalTypeMember = parenthesizeConditionalTypeMember;
74040     function parenthesizeElementTypeMember(member) {
74041         switch (member.kind) {
74042             case 178 /* UnionType */:
74043             case 179 /* IntersectionType */:
74044             case 170 /* FunctionType */:
74045             case 171 /* ConstructorType */:
74046                 return ts.createParenthesizedType(member);
74047         }
74048         return parenthesizeConditionalTypeMember(member);
74049     }
74050     ts.parenthesizeElementTypeMember = parenthesizeElementTypeMember;
74051     function parenthesizeArrayTypeMember(member) {
74052         switch (member.kind) {
74053             case 172 /* TypeQuery */:
74054             case 184 /* TypeOperator */:
74055             case 181 /* InferType */:
74056                 return ts.createParenthesizedType(member);
74057         }
74058         return parenthesizeElementTypeMember(member);
74059     }
74060     ts.parenthesizeArrayTypeMember = parenthesizeArrayTypeMember;
74061     function parenthesizeElementTypeMembers(members) {
74062         return ts.createNodeArray(ts.sameMap(members, parenthesizeElementTypeMember));
74063     }
74064     ts.parenthesizeElementTypeMembers = parenthesizeElementTypeMembers;
74065     function parenthesizeTypeParameters(typeParameters) {
74066         if (ts.some(typeParameters)) {
74067             var params = [];
74068             for (var i = 0; i < typeParameters.length; ++i) {
74069                 var entry = typeParameters[i];
74070                 params.push(i === 0 && ts.isFunctionOrConstructorTypeNode(entry) && entry.typeParameters ?
74071                     ts.createParenthesizedType(entry) :
74072                     entry);
74073             }
74074             return ts.createNodeArray(params);
74075         }
74076     }
74077     ts.parenthesizeTypeParameters = parenthesizeTypeParameters;
74078     function getLeftmostExpression(node, stopAtCallExpressions) {
74079         while (true) {
74080             switch (node.kind) {
74081                 case 208 /* PostfixUnaryExpression */:
74082                     node = node.operand;
74083                     continue;
74084                 case 209 /* BinaryExpression */:
74085                     node = node.left;
74086                     continue;
74087                 case 210 /* ConditionalExpression */:
74088                     node = node.condition;
74089                     continue;
74090                 case 198 /* TaggedTemplateExpression */:
74091                     node = node.tag;
74092                     continue;
74093                 case 196 /* CallExpression */:
74094                     if (stopAtCallExpressions) {
74095                         return node;
74096                     }
74097                 // falls through
74098                 case 217 /* AsExpression */:
74099                 case 195 /* ElementAccessExpression */:
74100                 case 194 /* PropertyAccessExpression */:
74101                 case 218 /* NonNullExpression */:
74102                 case 326 /* PartiallyEmittedExpression */:
74103                     node = node.expression;
74104                     continue;
74105             }
74106             return node;
74107         }
74108     }
74109     ts.getLeftmostExpression = getLeftmostExpression;
74110     function parenthesizeConciseBody(body) {
74111         if (!ts.isBlock(body) && (isCommaSequence(body) || getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 193 /* ObjectLiteralExpression */)) {
74112             return ts.setTextRange(ts.createParen(body), body);
74113         }
74114         return body;
74115     }
74116     ts.parenthesizeConciseBody = parenthesizeConciseBody;
74117     function isCommaSequence(node) {
74118         return node.kind === 209 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
74119             node.kind === 327 /* CommaListExpression */;
74120     }
74121     ts.isCommaSequence = isCommaSequence;
74122     var OuterExpressionKinds;
74123     (function (OuterExpressionKinds) {
74124         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
74125         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
74126         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
74127         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
74128         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
74129         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
74130     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
74131     function isOuterExpression(node, kinds) {
74132         if (kinds === void 0) { kinds = 15 /* All */; }
74133         switch (node.kind) {
74134             case 200 /* ParenthesizedExpression */:
74135                 return (kinds & 1 /* Parentheses */) !== 0;
74136             case 199 /* TypeAssertionExpression */:
74137             case 217 /* AsExpression */:
74138                 return (kinds & 2 /* TypeAssertions */) !== 0;
74139             case 218 /* NonNullExpression */:
74140                 return (kinds & 4 /* NonNullAssertions */) !== 0;
74141             case 326 /* PartiallyEmittedExpression */:
74142                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
74143         }
74144         return false;
74145     }
74146     ts.isOuterExpression = isOuterExpression;
74147     function skipOuterExpressions(node, kinds) {
74148         if (kinds === void 0) { kinds = 15 /* All */; }
74149         while (isOuterExpression(node, kinds)) {
74150             node = node.expression;
74151         }
74152         return node;
74153     }
74154     ts.skipOuterExpressions = skipOuterExpressions;
74155     function skipAssertions(node) {
74156         return skipOuterExpressions(node, 6 /* Assertions */);
74157     }
74158     ts.skipAssertions = skipAssertions;
74159     function updateOuterExpression(outerExpression, expression) {
74160         switch (outerExpression.kind) {
74161             case 200 /* ParenthesizedExpression */: return ts.updateParen(outerExpression, expression);
74162             case 199 /* TypeAssertionExpression */: return ts.updateTypeAssertion(outerExpression, outerExpression.type, expression);
74163             case 217 /* AsExpression */: return ts.updateAsExpression(outerExpression, expression, outerExpression.type);
74164             case 218 /* NonNullExpression */: return ts.updateNonNullExpression(outerExpression, expression);
74165             case 326 /* PartiallyEmittedExpression */: return ts.updatePartiallyEmittedExpression(outerExpression, expression);
74166         }
74167     }
74168     /**
74169      * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
74170      *
74171      * A parenthesized expression can be ignored when all of the following are true:
74172      *
74173      * - It's `pos` and `end` are not -1
74174      * - It does not have a custom source map range
74175      * - It does not have a custom comment range
74176      * - It does not have synthetic leading or trailing comments
74177      *
74178      * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
74179      * the expression to maintain precedence, a new parenthesized expression should be created automatically when
74180      * the containing expression is created/updated.
74181      */
74182     function isIgnorableParen(node) {
74183         return node.kind === 200 /* ParenthesizedExpression */
74184             && ts.nodeIsSynthesized(node)
74185             && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
74186             && ts.nodeIsSynthesized(ts.getCommentRange(node))
74187             && !ts.some(ts.getSyntheticLeadingComments(node))
74188             && !ts.some(ts.getSyntheticTrailingComments(node));
74189     }
74190     function recreateOuterExpressions(outerExpression, innerExpression, kinds) {
74191         if (kinds === void 0) { kinds = 15 /* All */; }
74192         if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
74193             return updateOuterExpression(outerExpression, recreateOuterExpressions(outerExpression.expression, innerExpression));
74194         }
74195         return innerExpression;
74196     }
74197     ts.recreateOuterExpressions = recreateOuterExpressions;
74198     function startOnNewLine(node) {
74199         return ts.setStartsOnNewLine(node, /*newLine*/ true);
74200     }
74201     ts.startOnNewLine = startOnNewLine;
74202     function getExternalHelpersModuleName(node) {
74203         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74204         var emitNode = parseNode && parseNode.emitNode;
74205         return emitNode && emitNode.externalHelpersModuleName;
74206     }
74207     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
74208     function hasRecordedExternalHelpers(sourceFile) {
74209         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74210         var emitNode = parseNode && parseNode.emitNode;
74211         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
74212     }
74213     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
74214     function createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
74215         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
74216             var namedBindings = void 0;
74217             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74218             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
74219                 // use named imports
74220                 var helpers = ts.getEmitHelpers(sourceFile);
74221                 if (helpers) {
74222                     var helperNames = [];
74223                     for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
74224                         var helper = helpers_2[_i];
74225                         if (!helper.scoped) {
74226                             var importName = helper.importName;
74227                             if (importName) {
74228                                 ts.pushIfUnique(helperNames, importName);
74229                             }
74230                         }
74231                     }
74232                     if (ts.some(helperNames)) {
74233                         helperNames.sort(ts.compareStringsCaseSensitive);
74234                         // Alias the imports if the names are used somewhere in the file.
74235                         // NOTE: We don't need to care about global import collisions as this is a module.
74236                         namedBindings = ts.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
74237                             ? ts.createImportSpecifier(/*propertyName*/ undefined, ts.createIdentifier(name))
74238                             : ts.createImportSpecifier(ts.createIdentifier(name), getUnscopedHelperName(name)); }));
74239                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
74240                         var emitNode = ts.getOrCreateEmitNode(parseNode);
74241                         emitNode.externalHelpers = true;
74242                     }
74243                 }
74244             }
74245             else {
74246                 // use a namespace import
74247                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
74248                 if (externalHelpersModuleName) {
74249                     namedBindings = ts.createNamespaceImport(externalHelpersModuleName);
74250                 }
74251             }
74252             if (namedBindings) {
74253                 var externalHelpersImportDeclaration = ts.createImportDeclaration(
74254                 /*decorators*/ undefined, 
74255                 /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, namedBindings), ts.createLiteral(ts.externalHelpersModuleNameText));
74256                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
74257                 return externalHelpersImportDeclaration;
74258             }
74259         }
74260     }
74261     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
74262     function getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
74263         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
74264             var externalHelpersModuleName = getExternalHelpersModuleName(node);
74265             if (externalHelpersModuleName) {
74266                 return externalHelpersModuleName;
74267             }
74268             var moduleKind = ts.getEmitModuleKind(compilerOptions);
74269             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
74270                 && moduleKind !== ts.ModuleKind.System
74271                 && moduleKind < ts.ModuleKind.ES2015;
74272             if (!create) {
74273                 var helpers = ts.getEmitHelpers(node);
74274                 if (helpers) {
74275                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
74276                         var helper = helpers_3[_i];
74277                         if (!helper.scoped) {
74278                             create = true;
74279                             break;
74280                         }
74281                     }
74282                 }
74283             }
74284             if (create) {
74285                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
74286                 var emitNode = ts.getOrCreateEmitNode(parseNode);
74287                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = ts.createUniqueName(ts.externalHelpersModuleNameText));
74288             }
74289         }
74290     }
74291     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
74292     /**
74293      * Get the name of that target module from an import or export declaration
74294      */
74295     function getLocalNameForExternalImport(node, sourceFile) {
74296         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
74297         if (namespaceDeclaration && !ts.isDefaultImport(node)) {
74298             var name = namespaceDeclaration.name;
74299             return ts.isGeneratedIdentifier(name) ? name : ts.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
74300         }
74301         if (node.kind === 254 /* ImportDeclaration */ && node.importClause) {
74302             return ts.getGeneratedNameForNode(node);
74303         }
74304         if (node.kind === 260 /* ExportDeclaration */ && node.moduleSpecifier) {
74305             return ts.getGeneratedNameForNode(node);
74306         }
74307         return undefined;
74308     }
74309     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
74310     /**
74311      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
74312      * The emitted output name can be different from the input if:
74313      *  1. The module has a /// <amd-module name="<new name>" />
74314      *  2. --out or --outFile is used, making the name relative to the rootDir
74315      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
74316      * Otherwise, a new StringLiteral node representing the module name will be returned.
74317      */
74318     function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) {
74319         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
74320         if (moduleName.kind === 10 /* StringLiteral */) {
74321             return tryGetModuleNameFromDeclaration(importNode, host, resolver, compilerOptions)
74322                 || tryRenameExternalModule(moduleName, sourceFile)
74323                 || ts.getSynthesizedClone(moduleName);
74324         }
74325         return undefined;
74326     }
74327     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
74328     /**
74329      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
74330      * Here we check if alternative name was provided for a given moduleName and return it if possible.
74331      */
74332     function tryRenameExternalModule(moduleName, sourceFile) {
74333         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
74334         return rename && ts.createLiteral(rename);
74335     }
74336     /**
74337      * Get the name of a module as should be written in the emitted output.
74338      * The emitted output name can be different from the input if:
74339      *  1. The module has a /// <amd-module name="<new name>" />
74340      *  2. --out or --outFile is used, making the name relative to the rootDir
74341      * Otherwise, a new StringLiteral node representing the module name will be returned.
74342      */
74343     function tryGetModuleNameFromFile(file, host, options) {
74344         if (!file) {
74345             return undefined;
74346         }
74347         if (file.moduleName) {
74348             return ts.createLiteral(file.moduleName);
74349         }
74350         if (!file.isDeclarationFile && (options.out || options.outFile)) {
74351             return ts.createLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
74352         }
74353         return undefined;
74354     }
74355     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
74356     function tryGetModuleNameFromDeclaration(declaration, host, resolver, compilerOptions) {
74357         return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
74358     }
74359     /**
74360      * Gets the initializer of an BindingOrAssignmentElement.
74361      */
74362     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
74363         if (ts.isDeclarationBindingElement(bindingElement)) {
74364             // `1` in `let { a = 1 } = ...`
74365             // `1` in `let { a: b = 1 } = ...`
74366             // `1` in `let { a: {b} = 1 } = ...`
74367             // `1` in `let { a: [b] = 1 } = ...`
74368             // `1` in `let [a = 1] = ...`
74369             // `1` in `let [{a} = 1] = ...`
74370             // `1` in `let [[a] = 1] = ...`
74371             return bindingElement.initializer;
74372         }
74373         if (ts.isPropertyAssignment(bindingElement)) {
74374             // `1` in `({ a: b = 1 } = ...)`
74375             // `1` in `({ a: {b} = 1 } = ...)`
74376             // `1` in `({ a: [b] = 1 } = ...)`
74377             var initializer = bindingElement.initializer;
74378             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
74379                 ? initializer.right
74380                 : undefined;
74381         }
74382         if (ts.isShorthandPropertyAssignment(bindingElement)) {
74383             // `1` in `({ a = 1 } = ...)`
74384             return bindingElement.objectAssignmentInitializer;
74385         }
74386         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74387             // `1` in `[a = 1] = ...`
74388             // `1` in `[{a} = 1] = ...`
74389             // `1` in `[[a] = 1] = ...`
74390             return bindingElement.right;
74391         }
74392         if (ts.isSpreadElement(bindingElement)) {
74393             // Recovery consistent with existing emit.
74394             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
74395         }
74396     }
74397     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
74398     /**
74399      * Gets the name of an BindingOrAssignmentElement.
74400      */
74401     function getTargetOfBindingOrAssignmentElement(bindingElement) {
74402         if (ts.isDeclarationBindingElement(bindingElement)) {
74403             // `a` in `let { a } = ...`
74404             // `a` in `let { a = 1 } = ...`
74405             // `b` in `let { a: b } = ...`
74406             // `b` in `let { a: b = 1 } = ...`
74407             // `a` in `let { ...a } = ...`
74408             // `{b}` in `let { a: {b} } = ...`
74409             // `{b}` in `let { a: {b} = 1 } = ...`
74410             // `[b]` in `let { a: [b] } = ...`
74411             // `[b]` in `let { a: [b] = 1 } = ...`
74412             // `a` in `let [a] = ...`
74413             // `a` in `let [a = 1] = ...`
74414             // `a` in `let [...a] = ...`
74415             // `{a}` in `let [{a}] = ...`
74416             // `{a}` in `let [{a} = 1] = ...`
74417             // `[a]` in `let [[a]] = ...`
74418             // `[a]` in `let [[a] = 1] = ...`
74419             return bindingElement.name;
74420         }
74421         if (ts.isObjectLiteralElementLike(bindingElement)) {
74422             switch (bindingElement.kind) {
74423                 case 281 /* PropertyAssignment */:
74424                     // `b` in `({ a: b } = ...)`
74425                     // `b` in `({ a: b = 1 } = ...)`
74426                     // `{b}` in `({ a: {b} } = ...)`
74427                     // `{b}` in `({ a: {b} = 1 } = ...)`
74428                     // `[b]` in `({ a: [b] } = ...)`
74429                     // `[b]` in `({ a: [b] = 1 } = ...)`
74430                     // `b.c` in `({ a: b.c } = ...)`
74431                     // `b.c` in `({ a: b.c = 1 } = ...)`
74432                     // `b[0]` in `({ a: b[0] } = ...)`
74433                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
74434                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
74435                 case 282 /* ShorthandPropertyAssignment */:
74436                     // `a` in `({ a } = ...)`
74437                     // `a` in `({ a = 1 } = ...)`
74438                     return bindingElement.name;
74439                 case 283 /* SpreadAssignment */:
74440                     // `a` in `({ ...a } = ...)`
74441                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74442             }
74443             // no target
74444             return undefined;
74445         }
74446         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
74447             // `a` in `[a = 1] = ...`
74448             // `{a}` in `[{a} = 1] = ...`
74449             // `[a]` in `[[a] = 1] = ...`
74450             // `a.b` in `[a.b = 1] = ...`
74451             // `a[0]` in `[a[0] = 1] = ...`
74452             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
74453         }
74454         if (ts.isSpreadElement(bindingElement)) {
74455             // `a` in `[...a] = ...`
74456             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
74457         }
74458         // `a` in `[a] = ...`
74459         // `{a}` in `[{a}] = ...`
74460         // `[a]` in `[[a]] = ...`
74461         // `a.b` in `[a.b] = ...`
74462         // `a[0]` in `[a[0]] = ...`
74463         return bindingElement;
74464     }
74465     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
74466     /**
74467      * Determines whether an BindingOrAssignmentElement is a rest element.
74468      */
74469     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
74470         switch (bindingElement.kind) {
74471             case 156 /* Parameter */:
74472             case 191 /* BindingElement */:
74473                 // `...` in `let [...a] = ...`
74474                 return bindingElement.dotDotDotToken;
74475             case 213 /* SpreadElement */:
74476             case 283 /* SpreadAssignment */:
74477                 // `...` in `[...a] = ...`
74478                 return bindingElement;
74479         }
74480         return undefined;
74481     }
74482     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
74483     /**
74484      * Gets the property name of a BindingOrAssignmentElement
74485      */
74486     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74487         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
74488         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
74489         return propertyName;
74490     }
74491     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
74492     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
74493         switch (bindingElement.kind) {
74494             case 191 /* BindingElement */:
74495                 // `a` in `let { a: b } = ...`
74496                 // `[a]` in `let { [a]: b } = ...`
74497                 // `"a"` in `let { "a": b } = ...`
74498                 // `1` in `let { 1: b } = ...`
74499                 if (bindingElement.propertyName) {
74500                     var propertyName = bindingElement.propertyName;
74501                     if (ts.isPrivateIdentifier(propertyName)) {
74502                         return ts.Debug.failBadSyntaxKind(propertyName);
74503                     }
74504                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74505                         ? propertyName.expression
74506                         : propertyName;
74507                 }
74508                 break;
74509             case 281 /* PropertyAssignment */:
74510                 // `a` in `({ a: b } = ...)`
74511                 // `[a]` in `({ [a]: b } = ...)`
74512                 // `"a"` in `({ "a": b } = ...)`
74513                 // `1` in `({ 1: b } = ...)`
74514                 if (bindingElement.name) {
74515                     var propertyName = bindingElement.name;
74516                     if (ts.isPrivateIdentifier(propertyName)) {
74517                         return ts.Debug.failBadSyntaxKind(propertyName);
74518                     }
74519                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
74520                         ? propertyName.expression
74521                         : propertyName;
74522                 }
74523                 break;
74524             case 283 /* SpreadAssignment */:
74525                 // `a` in `({ ...a } = ...)`
74526                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
74527                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
74528                 }
74529                 return bindingElement.name;
74530         }
74531         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
74532         if (target && ts.isPropertyName(target)) {
74533             return target;
74534         }
74535     }
74536     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
74537     function isStringOrNumericLiteral(node) {
74538         var kind = node.kind;
74539         return kind === 10 /* StringLiteral */
74540             || kind === 8 /* NumericLiteral */;
74541     }
74542     /**
74543      * Gets the elements of a BindingOrAssignmentPattern
74544      */
74545     function getElementsOfBindingOrAssignmentPattern(name) {
74546         switch (name.kind) {
74547             case 189 /* ObjectBindingPattern */:
74548             case 190 /* ArrayBindingPattern */:
74549             case 192 /* ArrayLiteralExpression */:
74550                 // `a` in `{a}`
74551                 // `a` in `[a]`
74552                 return name.elements;
74553             case 193 /* ObjectLiteralExpression */:
74554                 // `a` in `{a}`
74555                 return name.properties;
74556         }
74557     }
74558     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
74559     function convertToArrayAssignmentElement(element) {
74560         if (ts.isBindingElement(element)) {
74561             if (element.dotDotDotToken) {
74562                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74563                 return ts.setOriginalNode(ts.setTextRange(ts.createSpread(element.name), element), element);
74564             }
74565             var expression = convertToAssignmentElementTarget(element.name);
74566             return element.initializer
74567                 ? ts.setOriginalNode(ts.setTextRange(ts.createAssignment(expression, element.initializer), element), element)
74568                 : expression;
74569         }
74570         ts.Debug.assertNode(element, ts.isExpression);
74571         return element;
74572     }
74573     ts.convertToArrayAssignmentElement = convertToArrayAssignmentElement;
74574     function convertToObjectAssignmentElement(element) {
74575         if (ts.isBindingElement(element)) {
74576             if (element.dotDotDotToken) {
74577                 ts.Debug.assertNode(element.name, ts.isIdentifier);
74578                 return ts.setOriginalNode(ts.setTextRange(ts.createSpreadAssignment(element.name), element), element);
74579             }
74580             if (element.propertyName) {
74581                 var expression = convertToAssignmentElementTarget(element.name);
74582                 return ts.setOriginalNode(ts.setTextRange(ts.createPropertyAssignment(element.propertyName, element.initializer ? ts.createAssignment(expression, element.initializer) : expression), element), element);
74583             }
74584             ts.Debug.assertNode(element.name, ts.isIdentifier);
74585             return ts.setOriginalNode(ts.setTextRange(ts.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
74586         }
74587         ts.Debug.assertNode(element, ts.isObjectLiteralElementLike);
74588         return element;
74589     }
74590     ts.convertToObjectAssignmentElement = convertToObjectAssignmentElement;
74591     function convertToAssignmentPattern(node) {
74592         switch (node.kind) {
74593             case 190 /* ArrayBindingPattern */:
74594             case 192 /* ArrayLiteralExpression */:
74595                 return convertToArrayAssignmentPattern(node);
74596             case 189 /* ObjectBindingPattern */:
74597             case 193 /* ObjectLiteralExpression */:
74598                 return convertToObjectAssignmentPattern(node);
74599         }
74600     }
74601     ts.convertToAssignmentPattern = convertToAssignmentPattern;
74602     function convertToObjectAssignmentPattern(node) {
74603         if (ts.isObjectBindingPattern(node)) {
74604             return ts.setOriginalNode(ts.setTextRange(ts.createObjectLiteral(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
74605         }
74606         ts.Debug.assertNode(node, ts.isObjectLiteralExpression);
74607         return node;
74608     }
74609     ts.convertToObjectAssignmentPattern = convertToObjectAssignmentPattern;
74610     function convertToArrayAssignmentPattern(node) {
74611         if (ts.isArrayBindingPattern(node)) {
74612             return ts.setOriginalNode(ts.setTextRange(ts.createArrayLiteral(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
74613         }
74614         ts.Debug.assertNode(node, ts.isArrayLiteralExpression);
74615         return node;
74616     }
74617     ts.convertToArrayAssignmentPattern = convertToArrayAssignmentPattern;
74618     function convertToAssignmentElementTarget(node) {
74619         if (ts.isBindingPattern(node)) {
74620             return convertToAssignmentPattern(node);
74621         }
74622         ts.Debug.assertNode(node, ts.isExpression);
74623         return node;
74624     }
74625     ts.convertToAssignmentElementTarget = convertToAssignmentElementTarget;
74626 })(ts || (ts = {}));
74627 var ts;
74628 (function (ts) {
74629     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
74630     function visitNode(node, visitor, test, lift) {
74631         if (node === undefined || visitor === undefined) {
74632             return node;
74633         }
74634         ts.aggregateTransformFlags(node);
74635         var visited = visitor(node);
74636         if (visited === node) {
74637             return node;
74638         }
74639         var visitedNode;
74640         if (visited === undefined) {
74641             return undefined;
74642         }
74643         else if (ts.isArray(visited)) {
74644             visitedNode = (lift || extractSingleNode)(visited);
74645         }
74646         else {
74647             visitedNode = visited;
74648         }
74649         ts.Debug.assertNode(visitedNode, test);
74650         ts.aggregateTransformFlags(visitedNode);
74651         return visitedNode;
74652     }
74653     ts.visitNode = visitNode;
74654     /**
74655      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
74656      *
74657      * @param nodes The NodeArray to visit.
74658      * @param visitor The callback used to visit a Node.
74659      * @param test A node test to execute for each node.
74660      * @param start An optional value indicating the starting offset at which to start visiting.
74661      * @param count An optional value indicating the maximum number of nodes to visit.
74662      */
74663     function visitNodes(nodes, visitor, test, start, count) {
74664         if (nodes === undefined || visitor === undefined) {
74665             return nodes;
74666         }
74667         var updated;
74668         // Ensure start and count have valid values
74669         var length = nodes.length;
74670         if (start === undefined || start < 0) {
74671             start = 0;
74672         }
74673         if (count === undefined || count > length - start) {
74674             count = length - start;
74675         }
74676         if (start > 0 || count < length) {
74677             // If we are not visiting all of the original nodes, we must always create a new array.
74678             // Since this is a fragment of a node array, we do not copy over the previous location
74679             // and will only copy over `hasTrailingComma` if we are including the last element.
74680             updated = ts.createNodeArray([], /*hasTrailingComma*/ nodes.hasTrailingComma && start + count === length);
74681         }
74682         // Visit each original node.
74683         for (var i = 0; i < count; i++) {
74684             var node = nodes[i + start];
74685             ts.aggregateTransformFlags(node);
74686             var visited = node !== undefined ? visitor(node) : undefined;
74687             if (updated !== undefined || visited === undefined || visited !== node) {
74688                 if (updated === undefined) {
74689                     // Ensure we have a copy of `nodes`, up to the current index.
74690                     updated = ts.createNodeArray(nodes.slice(0, i), nodes.hasTrailingComma);
74691                     ts.setTextRange(updated, nodes);
74692                 }
74693                 if (visited) {
74694                     if (ts.isArray(visited)) {
74695                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
74696                             var visitedNode = visited_1[_i];
74697                             ts.Debug.assertNode(visitedNode, test);
74698                             ts.aggregateTransformFlags(visitedNode);
74699                             updated.push(visitedNode);
74700                         }
74701                     }
74702                     else {
74703                         ts.Debug.assertNode(visited, test);
74704                         ts.aggregateTransformFlags(visited);
74705                         updated.push(visited);
74706                     }
74707                 }
74708             }
74709         }
74710         return updated || nodes;
74711     }
74712     ts.visitNodes = visitNodes;
74713     /**
74714      * Starts a new lexical environment and visits a statement list, ending the lexical environment
74715      * and merging hoisted declarations upon completion.
74716      */
74717     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict) {
74718         context.startLexicalEnvironment();
74719         statements = visitNodes(statements, visitor, ts.isStatement, start);
74720         if (ensureUseStrict)
74721             statements = ts.ensureUseStrict(statements); // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier
74722         return ts.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
74723     }
74724     ts.visitLexicalEnvironment = visitLexicalEnvironment;
74725     function visitParameterList(nodes, visitor, context, nodesVisitor) {
74726         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74727         var updated;
74728         context.startLexicalEnvironment();
74729         if (nodes) {
74730             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
74731             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
74732             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
74733             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
74734             // that we might transform that introduces a temporary variable would fail as the temporary variable
74735             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
74736             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
74737             // when the emit target is greater than ES2015.
74738             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
74739                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
74740                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
74741             }
74742             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
74743         }
74744         context.suspendLexicalEnvironment();
74745         return updated;
74746     }
74747     ts.visitParameterList = visitParameterList;
74748     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
74749         var result;
74750         for (var i = 0; i < parameters.length; i++) {
74751             var parameter = parameters[i];
74752             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
74753             if (result || updated !== parameter) {
74754                 if (!result)
74755                     result = parameters.slice(0, i);
74756                 result[i] = updated;
74757             }
74758         }
74759         if (result) {
74760             return ts.setTextRange(ts.createNodeArray(result, parameters.hasTrailingComma), parameters);
74761         }
74762         return parameters;
74763     }
74764     function addDefaultValueAssignmentIfNeeded(parameter, context) {
74765         // A rest parameter cannot have a binding pattern or an initializer,
74766         // so let's just ignore it.
74767         return parameter.dotDotDotToken ? parameter :
74768             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
74769                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
74770                     parameter;
74771     }
74772     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
74773         context.addInitializationStatement(ts.createVariableStatement(
74774         /*modifiers*/ undefined, ts.createVariableDeclarationList([
74775             ts.createVariableDeclaration(parameter.name, parameter.type, parameter.initializer ?
74776                 ts.createConditional(ts.createStrictEquality(ts.getGeneratedNameForNode(parameter), ts.createVoidZero()), parameter.initializer, ts.getGeneratedNameForNode(parameter)) :
74777                 ts.getGeneratedNameForNode(parameter)),
74778         ])));
74779         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, ts.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
74780         /*initializer*/ undefined);
74781     }
74782     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
74783         context.addInitializationStatement(ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
74784             ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
74785         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
74786         return ts.updateParameter(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
74787         /*initializer*/ undefined);
74788     }
74789     function visitFunctionBody(node, visitor, context) {
74790         context.resumeLexicalEnvironment();
74791         var updated = visitNode(node, visitor, ts.isConciseBody);
74792         var declarations = context.endLexicalEnvironment();
74793         if (ts.some(declarations)) {
74794             var block = ts.convertToFunctionBody(updated);
74795             var statements = ts.mergeLexicalEnvironment(block.statements, declarations);
74796             return ts.updateBlock(block, statements);
74797         }
74798         return updated;
74799     }
74800     ts.visitFunctionBody = visitFunctionBody;
74801     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor) {
74802         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
74803         if (node === undefined) {
74804             return undefined;
74805         }
74806         var kind = node.kind;
74807         // No need to visit nodes with no children.
74808         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */) || kind === 183 /* ThisType */) {
74809             return node;
74810         }
74811         switch (kind) {
74812             // Names
74813             case 75 /* Identifier */:
74814                 return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
74815             case 153 /* QualifiedName */:
74816                 return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier));
74817             case 154 /* ComputedPropertyName */:
74818                 return ts.updateComputedPropertyName(node, visitNode(node.expression, visitor, ts.isExpression));
74819             // Signature elements
74820             case 155 /* TypeParameter */:
74821                 return ts.updateTypeParameterDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.constraint, visitor, ts.isTypeNode), visitNode(node.default, visitor, ts.isTypeNode));
74822             case 156 /* Parameter */:
74823                 return ts.updateParameter(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74824             case 157 /* Decorator */:
74825                 return ts.updateDecorator(node, visitNode(node.expression, visitor, ts.isExpression));
74826             // Type elements
74827             case 158 /* PropertySignature */:
74828                 return ts.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74829             case 159 /* PropertyDeclaration */:
74830                 return ts.updateProperty(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), 
74831                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
74832                 visitNode(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
74833             case 160 /* MethodSignature */:
74834                 return ts.updateMethodSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken));
74835             case 161 /* MethodDeclaration */:
74836                 return ts.updateMethod(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
74837             case 162 /* Constructor */:
74838                 return ts.updateConstructor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
74839             case 163 /* GetAccessor */:
74840                 return ts.updateGetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
74841             case 164 /* SetAccessor */:
74842                 return ts.updateSetAccessor(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context));
74843             case 165 /* CallSignature */:
74844                 return ts.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74845             case 166 /* ConstructSignature */:
74846                 return ts.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74847             case 167 /* IndexSignature */:
74848                 return ts.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74849             // Types
74850             case 168 /* TypePredicate */:
74851                 return ts.updateTypePredicateNodeWithModifier(node, visitNode(node.assertsModifier, visitor), visitNode(node.parameterName, visitor), visitNode(node.type, visitor, ts.isTypeNode));
74852             case 169 /* TypeReference */:
74853                 return ts.updateTypeReferenceNode(node, visitNode(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
74854             case 170 /* FunctionType */:
74855                 return ts.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74856             case 171 /* ConstructorType */:
74857                 return ts.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
74858             case 172 /* TypeQuery */:
74859                 return ts.updateTypeQueryNode(node, visitNode(node.exprName, visitor, ts.isEntityName));
74860             case 173 /* TypeLiteral */:
74861                 return ts.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
74862             case 174 /* ArrayType */:
74863                 return ts.updateArrayTypeNode(node, visitNode(node.elementType, visitor, ts.isTypeNode));
74864             case 175 /* TupleType */:
74865                 return ts.updateTupleTypeNode(node, nodesVisitor(node.elementTypes, visitor, ts.isTypeNode));
74866             case 176 /* OptionalType */:
74867                 return ts.updateOptionalTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74868             case 177 /* RestType */:
74869                 return ts.updateRestTypeNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74870             case 178 /* UnionType */:
74871                 return ts.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74872             case 179 /* IntersectionType */:
74873                 return ts.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
74874             case 180 /* ConditionalType */:
74875                 return ts.updateConditionalTypeNode(node, visitNode(node.checkType, visitor, ts.isTypeNode), visitNode(node.extendsType, visitor, ts.isTypeNode), visitNode(node.trueType, visitor, ts.isTypeNode), visitNode(node.falseType, visitor, ts.isTypeNode));
74876             case 181 /* InferType */:
74877                 return ts.updateInferTypeNode(node, visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
74878             case 188 /* ImportType */:
74879                 return ts.updateImportTypeNode(node, visitNode(node.argument, visitor, ts.isTypeNode), visitNode(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
74880             case 182 /* ParenthesizedType */:
74881                 return ts.updateParenthesizedType(node, visitNode(node.type, visitor, ts.isTypeNode));
74882             case 184 /* TypeOperator */:
74883                 return ts.updateTypeOperatorNode(node, visitNode(node.type, visitor, ts.isTypeNode));
74884             case 185 /* IndexedAccessType */:
74885                 return ts.updateIndexedAccessTypeNode(node, visitNode(node.objectType, visitor, ts.isTypeNode), visitNode(node.indexType, visitor, ts.isTypeNode));
74886             case 186 /* MappedType */:
74887                 return ts.updateMappedTypeNode(node, visitNode(node.readonlyToken, tokenVisitor, ts.isToken), visitNode(node.typeParameter, visitor, ts.isTypeParameterDeclaration), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
74888             case 187 /* LiteralType */:
74889                 return ts.updateLiteralTypeNode(node, visitNode(node.literal, visitor, ts.isExpression));
74890             // Binding patterns
74891             case 189 /* ObjectBindingPattern */:
74892                 return ts.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
74893             case 190 /* ArrayBindingPattern */:
74894                 return ts.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
74895             case 191 /* BindingElement */:
74896                 return ts.updateBindingElement(node, visitNode(node.dotDotDotToken, tokenVisitor, ts.isToken), visitNode(node.propertyName, visitor, ts.isPropertyName), visitNode(node.name, visitor, ts.isBindingName), visitNode(node.initializer, visitor, ts.isExpression));
74897             // Expression
74898             case 192 /* ArrayLiteralExpression */:
74899                 return ts.updateArrayLiteral(node, nodesVisitor(node.elements, visitor, ts.isExpression));
74900             case 193 /* ObjectLiteralExpression */:
74901                 return ts.updateObjectLiteral(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
74902             case 194 /* PropertyAccessExpression */:
74903                 if (node.flags & 32 /* OptionalChain */) {
74904                     return ts.updatePropertyAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier));
74905                 }
74906                 return ts.updatePropertyAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
74907             case 195 /* ElementAccessExpression */:
74908                 if (node.flags & 32 /* OptionalChain */) {
74909                     return ts.updateElementAccessChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), visitNode(node.argumentExpression, visitor, ts.isExpression));
74910                 }
74911                 return ts.updateElementAccess(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.argumentExpression, visitor, ts.isExpression));
74912             case 196 /* CallExpression */:
74913                 if (node.flags & 32 /* OptionalChain */) {
74914                     return ts.updateCallChain(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74915                 }
74916                 return ts.updateCall(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74917             case 197 /* NewExpression */:
74918                 return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
74919             case 198 /* TaggedTemplateExpression */:
74920                 return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral));
74921             case 199 /* TypeAssertionExpression */:
74922                 return ts.updateTypeAssertion(node, visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74923             case 200 /* ParenthesizedExpression */:
74924                 return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression));
74925             case 201 /* FunctionExpression */:
74926                 return ts.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
74927             case 202 /* ArrowFunction */:
74928                 return ts.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context));
74929             case 203 /* DeleteExpression */:
74930                 return ts.updateDelete(node, visitNode(node.expression, visitor, ts.isExpression));
74931             case 204 /* TypeOfExpression */:
74932                 return ts.updateTypeOf(node, visitNode(node.expression, visitor, ts.isExpression));
74933             case 205 /* VoidExpression */:
74934                 return ts.updateVoid(node, visitNode(node.expression, visitor, ts.isExpression));
74935             case 206 /* AwaitExpression */:
74936                 return ts.updateAwait(node, visitNode(node.expression, visitor, ts.isExpression));
74937             case 207 /* PrefixUnaryExpression */:
74938                 return ts.updatePrefix(node, visitNode(node.operand, visitor, ts.isExpression));
74939             case 208 /* PostfixUnaryExpression */:
74940                 return ts.updatePostfix(node, visitNode(node.operand, visitor, ts.isExpression));
74941             case 209 /* BinaryExpression */:
74942                 return ts.updateBinary(node, visitNode(node.left, visitor, ts.isExpression), visitNode(node.right, visitor, ts.isExpression), visitNode(node.operatorToken, tokenVisitor, ts.isToken));
74943             case 210 /* ConditionalExpression */:
74944                 return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.questionToken, tokenVisitor, ts.isToken), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.colonToken, tokenVisitor, ts.isToken), visitNode(node.whenFalse, visitor, ts.isExpression));
74945             case 211 /* TemplateExpression */:
74946                 return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
74947             case 212 /* YieldExpression */:
74948                 return ts.updateYield(node, visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.expression, visitor, ts.isExpression));
74949             case 213 /* SpreadElement */:
74950                 return ts.updateSpread(node, visitNode(node.expression, visitor, ts.isExpression));
74951             case 214 /* ClassExpression */:
74952                 return ts.updateClassExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
74953             case 216 /* ExpressionWithTypeArguments */:
74954                 return ts.updateExpressionWithTypeArguments(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression));
74955             case 217 /* AsExpression */:
74956                 return ts.updateAsExpression(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.type, visitor, ts.isTypeNode));
74957             case 218 /* NonNullExpression */:
74958                 return ts.updateNonNullExpression(node, visitNode(node.expression, visitor, ts.isExpression));
74959             case 219 /* MetaProperty */:
74960                 return ts.updateMetaProperty(node, visitNode(node.name, visitor, ts.isIdentifier));
74961             // Misc
74962             case 221 /* TemplateSpan */:
74963                 return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
74964             // Element
74965             case 223 /* Block */:
74966                 return ts.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
74967             case 225 /* VariableStatement */:
74968                 return ts.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.declarationList, visitor, ts.isVariableDeclarationList));
74969             case 226 /* ExpressionStatement */:
74970                 return ts.updateExpressionStatement(node, visitNode(node.expression, visitor, ts.isExpression));
74971             case 227 /* IfStatement */:
74972                 return ts.updateIf(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.thenStatement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.elseStatement, visitor, ts.isStatement, ts.liftToBlock));
74973             case 228 /* DoStatement */:
74974                 return ts.updateDo(node, visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock), visitNode(node.expression, visitor, ts.isExpression));
74975             case 229 /* WhileStatement */:
74976                 return ts.updateWhile(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74977             case 230 /* ForStatement */:
74978                 return ts.updateFor(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.condition, visitor, ts.isExpression), visitNode(node.incrementor, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74979             case 231 /* ForInStatement */:
74980                 return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74981             case 232 /* ForOfStatement */:
74982                 return ts.updateForOf(node, visitNode(node.awaitModifier, tokenVisitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74983             case 233 /* ContinueStatement */:
74984                 return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier));
74985             case 234 /* BreakStatement */:
74986                 return ts.updateBreak(node, visitNode(node.label, visitor, ts.isIdentifier));
74987             case 235 /* ReturnStatement */:
74988                 return ts.updateReturn(node, visitNode(node.expression, visitor, ts.isExpression));
74989             case 236 /* WithStatement */:
74990                 return ts.updateWith(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74991             case 237 /* SwitchStatement */:
74992                 return ts.updateSwitch(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.caseBlock, visitor, ts.isCaseBlock));
74993             case 238 /* LabeledStatement */:
74994                 return ts.updateLabel(node, visitNode(node.label, visitor, ts.isIdentifier), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
74995             case 239 /* ThrowStatement */:
74996                 return ts.updateThrow(node, visitNode(node.expression, visitor, ts.isExpression));
74997             case 240 /* TryStatement */:
74998                 return ts.updateTry(node, visitNode(node.tryBlock, visitor, ts.isBlock), visitNode(node.catchClause, visitor, ts.isCatchClause), visitNode(node.finallyBlock, visitor, ts.isBlock));
74999             case 242 /* VariableDeclaration */:
75000                 return ts.updateTypeScriptVariableDeclaration(node, visitNode(node.name, visitor, ts.isBindingName), visitNode(node.exclamationToken, tokenVisitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode), visitNode(node.initializer, visitor, ts.isExpression));
75001             case 243 /* VariableDeclarationList */:
75002                 return ts.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
75003             case 244 /* FunctionDeclaration */:
75004                 return ts.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.asteriskToken, tokenVisitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitNode(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context));
75005             case 245 /* ClassDeclaration */:
75006                 return ts.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
75007             case 246 /* InterfaceDeclaration */:
75008                 return ts.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement));
75009             case 247 /* TypeAliasDeclaration */:
75010                 return ts.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitNode(node.type, visitor, ts.isTypeNode));
75011             case 248 /* EnumDeclaration */:
75012                 return ts.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
75013             case 249 /* ModuleDeclaration */:
75014                 return ts.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.body, visitor, ts.isModuleBody));
75015             case 250 /* ModuleBlock */:
75016                 return ts.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75017             case 251 /* CaseBlock */:
75018                 return ts.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
75019             case 252 /* NamespaceExportDeclaration */:
75020                 return ts.updateNamespaceExportDeclaration(node, visitNode(node.name, visitor, ts.isIdentifier));
75021             case 253 /* ImportEqualsDeclaration */:
75022                 return ts.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.moduleReference, visitor, ts.isModuleReference));
75023             case 254 /* ImportDeclaration */:
75024                 return ts.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.importClause, visitor, ts.isImportClause), visitNode(node.moduleSpecifier, visitor, ts.isExpression));
75025             case 255 /* ImportClause */:
75026                 return ts.updateImportClause(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.namedBindings, visitor, ts.isNamedImportBindings), node.isTypeOnly);
75027             case 256 /* NamespaceImport */:
75028                 return ts.updateNamespaceImport(node, visitNode(node.name, visitor, ts.isIdentifier));
75029             case 262 /* NamespaceExport */:
75030                 return ts.updateNamespaceExport(node, visitNode(node.name, visitor, ts.isIdentifier));
75031             case 257 /* NamedImports */:
75032                 return ts.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
75033             case 258 /* ImportSpecifier */:
75034                 return ts.updateImportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75035             case 259 /* ExportAssignment */:
75036                 return ts.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.expression, visitor, ts.isExpression));
75037             case 260 /* ExportDeclaration */:
75038                 return ts.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitNode(node.exportClause, visitor, ts.isNamedExportBindings), visitNode(node.moduleSpecifier, visitor, ts.isExpression), node.isTypeOnly);
75039             case 261 /* NamedExports */:
75040                 return ts.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
75041             case 263 /* ExportSpecifier */:
75042                 return ts.updateExportSpecifier(node, visitNode(node.propertyName, visitor, ts.isIdentifier), visitNode(node.name, visitor, ts.isIdentifier));
75043             // Module references
75044             case 265 /* ExternalModuleReference */:
75045                 return ts.updateExternalModuleReference(node, visitNode(node.expression, visitor, ts.isExpression));
75046             // JSX
75047             case 266 /* JsxElement */:
75048                 return ts.updateJsxElement(node, visitNode(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingElement, visitor, ts.isJsxClosingElement));
75049             case 267 /* JsxSelfClosingElement */:
75050                 return ts.updateJsxSelfClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75051             case 268 /* JsxOpeningElement */:
75052                 return ts.updateJsxOpeningElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.attributes, visitor, ts.isJsxAttributes));
75053             case 269 /* JsxClosingElement */:
75054                 return ts.updateJsxClosingElement(node, visitNode(node.tagName, visitor, ts.isJsxTagNameExpression));
75055             case 270 /* JsxFragment */:
75056                 return ts.updateJsxFragment(node, visitNode(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), visitNode(node.closingFragment, visitor, ts.isJsxClosingFragment));
75057             case 273 /* JsxAttribute */:
75058                 return ts.updateJsxAttribute(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
75059             case 274 /* JsxAttributes */:
75060                 return ts.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
75061             case 275 /* JsxSpreadAttribute */:
75062                 return ts.updateJsxSpreadAttribute(node, visitNode(node.expression, visitor, ts.isExpression));
75063             case 276 /* JsxExpression */:
75064                 return ts.updateJsxExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75065             // Clauses
75066             case 277 /* CaseClause */:
75067                 return ts.updateCaseClause(node, visitNode(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
75068             case 278 /* DefaultClause */:
75069                 return ts.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
75070             case 279 /* HeritageClause */:
75071                 return ts.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
75072             case 280 /* CatchClause */:
75073                 return ts.updateCatchClause(node, visitNode(node.variableDeclaration, visitor, ts.isVariableDeclaration), visitNode(node.block, visitor, ts.isBlock));
75074             // Property assignments
75075             case 281 /* PropertyAssignment */:
75076                 return ts.updatePropertyAssignment(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75077             case 282 /* ShorthandPropertyAssignment */:
75078                 return ts.updateShorthandPropertyAssignment(node, visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.objectAssignmentInitializer, visitor, ts.isExpression));
75079             case 283 /* SpreadAssignment */:
75080                 return ts.updateSpreadAssignment(node, visitNode(node.expression, visitor, ts.isExpression));
75081             // Enum
75082             case 284 /* EnumMember */:
75083                 return ts.updateEnumMember(node, visitNode(node.name, visitor, ts.isPropertyName), visitNode(node.initializer, visitor, ts.isExpression));
75084             // Top-level nodes
75085             case 290 /* SourceFile */:
75086                 return ts.updateSourceFileNode(node, visitLexicalEnvironment(node.statements, visitor, context));
75087             // Transformation nodes
75088             case 326 /* PartiallyEmittedExpression */:
75089                 return ts.updatePartiallyEmittedExpression(node, visitNode(node.expression, visitor, ts.isExpression));
75090             case 327 /* CommaListExpression */:
75091                 return ts.updateCommaList(node, nodesVisitor(node.elements, visitor, ts.isExpression));
75092             default:
75093                 // No need to visit nodes with no children.
75094                 return node;
75095         }
75096     }
75097     ts.visitEachChild = visitEachChild;
75098     /**
75099      * Extracts the single node from a NodeArray.
75100      *
75101      * @param nodes The NodeArray.
75102      */
75103     function extractSingleNode(nodes) {
75104         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
75105         return ts.singleOrUndefined(nodes);
75106     }
75107 })(ts || (ts = {}));
75108 /* @internal */
75109 var ts;
75110 (function (ts) {
75111     function reduceNode(node, f, initial) {
75112         return node ? f(initial, node) : initial;
75113     }
75114     function reduceNodeArray(nodes, f, initial) {
75115         return nodes ? f(initial, nodes) : initial;
75116     }
75117     /**
75118      * Similar to `reduceLeft`, performs a reduction against each child of a node.
75119      * NOTE: Unlike `forEachChild`, this does *not* visit every node.
75120      *
75121      * @param node The node containing the children to reduce.
75122      * @param initial The initial value to supply to the reduction.
75123      * @param f The callback function
75124      */
75125     function reduceEachChild(node, initial, cbNode, cbNodeArray) {
75126         if (node === undefined) {
75127             return initial;
75128         }
75129         var reduceNodes = cbNodeArray ? reduceNodeArray : ts.reduceLeft;
75130         var cbNodes = cbNodeArray || cbNode;
75131         var kind = node.kind;
75132         // No need to visit nodes with no children.
75133         if ((kind > 0 /* FirstToken */ && kind <= 152 /* LastToken */)) {
75134             return initial;
75135         }
75136         // We do not yet support types.
75137         if ((kind >= 168 /* TypePredicate */ && kind <= 187 /* LiteralType */)) {
75138             return initial;
75139         }
75140         var result = initial;
75141         switch (node.kind) {
75142             // Leaf nodes
75143             case 222 /* SemicolonClassElement */:
75144             case 224 /* EmptyStatement */:
75145             case 215 /* OmittedExpression */:
75146             case 241 /* DebuggerStatement */:
75147             case 325 /* NotEmittedStatement */:
75148                 // No need to visit nodes with no children.
75149                 break;
75150             // Names
75151             case 153 /* QualifiedName */:
75152                 result = reduceNode(node.left, cbNode, result);
75153                 result = reduceNode(node.right, cbNode, result);
75154                 break;
75155             case 154 /* ComputedPropertyName */:
75156                 result = reduceNode(node.expression, cbNode, result);
75157                 break;
75158             // Signature elements
75159             case 156 /* Parameter */:
75160                 result = reduceNodes(node.decorators, cbNodes, result);
75161                 result = reduceNodes(node.modifiers, cbNodes, result);
75162                 result = reduceNode(node.name, cbNode, result);
75163                 result = reduceNode(node.type, cbNode, result);
75164                 result = reduceNode(node.initializer, cbNode, result);
75165                 break;
75166             case 157 /* Decorator */:
75167                 result = reduceNode(node.expression, cbNode, result);
75168                 break;
75169             // Type member
75170             case 158 /* PropertySignature */:
75171                 result = reduceNodes(node.modifiers, cbNodes, result);
75172                 result = reduceNode(node.name, cbNode, result);
75173                 result = reduceNode(node.questionToken, cbNode, result);
75174                 result = reduceNode(node.type, cbNode, result);
75175                 result = reduceNode(node.initializer, cbNode, result);
75176                 break;
75177             case 159 /* PropertyDeclaration */:
75178                 result = reduceNodes(node.decorators, cbNodes, result);
75179                 result = reduceNodes(node.modifiers, cbNodes, result);
75180                 result = reduceNode(node.name, cbNode, result);
75181                 result = reduceNode(node.type, cbNode, result);
75182                 result = reduceNode(node.initializer, cbNode, result);
75183                 break;
75184             case 161 /* MethodDeclaration */:
75185                 result = reduceNodes(node.decorators, cbNodes, result);
75186                 result = reduceNodes(node.modifiers, cbNodes, result);
75187                 result = reduceNode(node.name, cbNode, result);
75188                 result = reduceNodes(node.typeParameters, cbNodes, result);
75189                 result = reduceNodes(node.parameters, cbNodes, result);
75190                 result = reduceNode(node.type, cbNode, result);
75191                 result = reduceNode(node.body, cbNode, result);
75192                 break;
75193             case 162 /* Constructor */:
75194                 result = reduceNodes(node.modifiers, cbNodes, result);
75195                 result = reduceNodes(node.parameters, cbNodes, result);
75196                 result = reduceNode(node.body, cbNode, result);
75197                 break;
75198             case 163 /* GetAccessor */:
75199                 result = reduceNodes(node.decorators, cbNodes, result);
75200                 result = reduceNodes(node.modifiers, cbNodes, result);
75201                 result = reduceNode(node.name, cbNode, result);
75202                 result = reduceNodes(node.parameters, cbNodes, result);
75203                 result = reduceNode(node.type, cbNode, result);
75204                 result = reduceNode(node.body, cbNode, result);
75205                 break;
75206             case 164 /* SetAccessor */:
75207                 result = reduceNodes(node.decorators, cbNodes, result);
75208                 result = reduceNodes(node.modifiers, cbNodes, result);
75209                 result = reduceNode(node.name, cbNode, result);
75210                 result = reduceNodes(node.parameters, cbNodes, result);
75211                 result = reduceNode(node.body, cbNode, result);
75212                 break;
75213             // Binding patterns
75214             case 189 /* ObjectBindingPattern */:
75215             case 190 /* ArrayBindingPattern */:
75216                 result = reduceNodes(node.elements, cbNodes, result);
75217                 break;
75218             case 191 /* BindingElement */:
75219                 result = reduceNode(node.propertyName, cbNode, result);
75220                 result = reduceNode(node.name, cbNode, result);
75221                 result = reduceNode(node.initializer, cbNode, result);
75222                 break;
75223             // Expression
75224             case 192 /* ArrayLiteralExpression */:
75225                 result = reduceNodes(node.elements, cbNodes, result);
75226                 break;
75227             case 193 /* ObjectLiteralExpression */:
75228                 result = reduceNodes(node.properties, cbNodes, result);
75229                 break;
75230             case 194 /* PropertyAccessExpression */:
75231                 result = reduceNode(node.expression, cbNode, result);
75232                 result = reduceNode(node.name, cbNode, result);
75233                 break;
75234             case 195 /* ElementAccessExpression */:
75235                 result = reduceNode(node.expression, cbNode, result);
75236                 result = reduceNode(node.argumentExpression, cbNode, result);
75237                 break;
75238             case 196 /* CallExpression */:
75239                 result = reduceNode(node.expression, cbNode, result);
75240                 result = reduceNodes(node.typeArguments, cbNodes, result);
75241                 result = reduceNodes(node.arguments, cbNodes, result);
75242                 break;
75243             case 197 /* NewExpression */:
75244                 result = reduceNode(node.expression, cbNode, result);
75245                 result = reduceNodes(node.typeArguments, cbNodes, result);
75246                 result = reduceNodes(node.arguments, cbNodes, result);
75247                 break;
75248             case 198 /* TaggedTemplateExpression */:
75249                 result = reduceNode(node.tag, cbNode, result);
75250                 result = reduceNodes(node.typeArguments, cbNodes, result);
75251                 result = reduceNode(node.template, cbNode, result);
75252                 break;
75253             case 199 /* TypeAssertionExpression */:
75254                 result = reduceNode(node.type, cbNode, result);
75255                 result = reduceNode(node.expression, cbNode, result);
75256                 break;
75257             case 201 /* FunctionExpression */:
75258                 result = reduceNodes(node.modifiers, cbNodes, result);
75259                 result = reduceNode(node.name, cbNode, result);
75260                 result = reduceNodes(node.typeParameters, cbNodes, result);
75261                 result = reduceNodes(node.parameters, cbNodes, result);
75262                 result = reduceNode(node.type, cbNode, result);
75263                 result = reduceNode(node.body, cbNode, result);
75264                 break;
75265             case 202 /* ArrowFunction */:
75266                 result = reduceNodes(node.modifiers, cbNodes, result);
75267                 result = reduceNodes(node.typeParameters, cbNodes, result);
75268                 result = reduceNodes(node.parameters, cbNodes, result);
75269                 result = reduceNode(node.type, cbNode, result);
75270                 result = reduceNode(node.body, cbNode, result);
75271                 break;
75272             case 200 /* ParenthesizedExpression */:
75273             case 203 /* DeleteExpression */:
75274             case 204 /* TypeOfExpression */:
75275             case 205 /* VoidExpression */:
75276             case 206 /* AwaitExpression */:
75277             case 212 /* YieldExpression */:
75278             case 213 /* SpreadElement */:
75279             case 218 /* NonNullExpression */:
75280                 result = reduceNode(node.expression, cbNode, result);
75281                 break;
75282             case 207 /* PrefixUnaryExpression */:
75283             case 208 /* PostfixUnaryExpression */:
75284                 result = reduceNode(node.operand, cbNode, result);
75285                 break;
75286             case 209 /* BinaryExpression */:
75287                 result = reduceNode(node.left, cbNode, result);
75288                 result = reduceNode(node.right, cbNode, result);
75289                 break;
75290             case 210 /* ConditionalExpression */:
75291                 result = reduceNode(node.condition, cbNode, result);
75292                 result = reduceNode(node.whenTrue, cbNode, result);
75293                 result = reduceNode(node.whenFalse, cbNode, result);
75294                 break;
75295             case 211 /* TemplateExpression */:
75296                 result = reduceNode(node.head, cbNode, result);
75297                 result = reduceNodes(node.templateSpans, cbNodes, result);
75298                 break;
75299             case 214 /* ClassExpression */:
75300                 result = reduceNodes(node.modifiers, cbNodes, result);
75301                 result = reduceNode(node.name, cbNode, result);
75302                 result = reduceNodes(node.typeParameters, cbNodes, result);
75303                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75304                 result = reduceNodes(node.members, cbNodes, result);
75305                 break;
75306             case 216 /* ExpressionWithTypeArguments */:
75307                 result = reduceNode(node.expression, cbNode, result);
75308                 result = reduceNodes(node.typeArguments, cbNodes, result);
75309                 break;
75310             case 217 /* AsExpression */:
75311                 result = reduceNode(node.expression, cbNode, result);
75312                 result = reduceNode(node.type, cbNode, result);
75313                 break;
75314             // Misc
75315             case 221 /* TemplateSpan */:
75316                 result = reduceNode(node.expression, cbNode, result);
75317                 result = reduceNode(node.literal, cbNode, result);
75318                 break;
75319             // Element
75320             case 223 /* Block */:
75321                 result = reduceNodes(node.statements, cbNodes, result);
75322                 break;
75323             case 225 /* VariableStatement */:
75324                 result = reduceNodes(node.modifiers, cbNodes, result);
75325                 result = reduceNode(node.declarationList, cbNode, result);
75326                 break;
75327             case 226 /* ExpressionStatement */:
75328                 result = reduceNode(node.expression, cbNode, result);
75329                 break;
75330             case 227 /* IfStatement */:
75331                 result = reduceNode(node.expression, cbNode, result);
75332                 result = reduceNode(node.thenStatement, cbNode, result);
75333                 result = reduceNode(node.elseStatement, cbNode, result);
75334                 break;
75335             case 228 /* DoStatement */:
75336                 result = reduceNode(node.statement, cbNode, result);
75337                 result = reduceNode(node.expression, cbNode, result);
75338                 break;
75339             case 229 /* WhileStatement */:
75340             case 236 /* WithStatement */:
75341                 result = reduceNode(node.expression, cbNode, result);
75342                 result = reduceNode(node.statement, cbNode, result);
75343                 break;
75344             case 230 /* ForStatement */:
75345                 result = reduceNode(node.initializer, cbNode, result);
75346                 result = reduceNode(node.condition, cbNode, result);
75347                 result = reduceNode(node.incrementor, cbNode, result);
75348                 result = reduceNode(node.statement, cbNode, result);
75349                 break;
75350             case 231 /* ForInStatement */:
75351             case 232 /* ForOfStatement */:
75352                 result = reduceNode(node.initializer, cbNode, result);
75353                 result = reduceNode(node.expression, cbNode, result);
75354                 result = reduceNode(node.statement, cbNode, result);
75355                 break;
75356             case 235 /* ReturnStatement */:
75357             case 239 /* ThrowStatement */:
75358                 result = reduceNode(node.expression, cbNode, result);
75359                 break;
75360             case 237 /* SwitchStatement */:
75361                 result = reduceNode(node.expression, cbNode, result);
75362                 result = reduceNode(node.caseBlock, cbNode, result);
75363                 break;
75364             case 238 /* LabeledStatement */:
75365                 result = reduceNode(node.label, cbNode, result);
75366                 result = reduceNode(node.statement, cbNode, result);
75367                 break;
75368             case 240 /* TryStatement */:
75369                 result = reduceNode(node.tryBlock, cbNode, result);
75370                 result = reduceNode(node.catchClause, cbNode, result);
75371                 result = reduceNode(node.finallyBlock, cbNode, result);
75372                 break;
75373             case 242 /* VariableDeclaration */:
75374                 result = reduceNode(node.name, cbNode, result);
75375                 result = reduceNode(node.type, cbNode, result);
75376                 result = reduceNode(node.initializer, cbNode, result);
75377                 break;
75378             case 243 /* VariableDeclarationList */:
75379                 result = reduceNodes(node.declarations, cbNodes, result);
75380                 break;
75381             case 244 /* FunctionDeclaration */:
75382                 result = reduceNodes(node.decorators, cbNodes, result);
75383                 result = reduceNodes(node.modifiers, cbNodes, result);
75384                 result = reduceNode(node.name, cbNode, result);
75385                 result = reduceNodes(node.typeParameters, cbNodes, result);
75386                 result = reduceNodes(node.parameters, cbNodes, result);
75387                 result = reduceNode(node.type, cbNode, result);
75388                 result = reduceNode(node.body, cbNode, result);
75389                 break;
75390             case 245 /* ClassDeclaration */:
75391                 result = reduceNodes(node.decorators, cbNodes, result);
75392                 result = reduceNodes(node.modifiers, cbNodes, result);
75393                 result = reduceNode(node.name, cbNode, result);
75394                 result = reduceNodes(node.typeParameters, cbNodes, result);
75395                 result = reduceNodes(node.heritageClauses, cbNodes, result);
75396                 result = reduceNodes(node.members, cbNodes, result);
75397                 break;
75398             case 248 /* EnumDeclaration */:
75399                 result = reduceNodes(node.decorators, cbNodes, result);
75400                 result = reduceNodes(node.modifiers, cbNodes, result);
75401                 result = reduceNode(node.name, cbNode, result);
75402                 result = reduceNodes(node.members, cbNodes, result);
75403                 break;
75404             case 249 /* ModuleDeclaration */:
75405                 result = reduceNodes(node.decorators, cbNodes, result);
75406                 result = reduceNodes(node.modifiers, cbNodes, result);
75407                 result = reduceNode(node.name, cbNode, result);
75408                 result = reduceNode(node.body, cbNode, result);
75409                 break;
75410             case 250 /* ModuleBlock */:
75411                 result = reduceNodes(node.statements, cbNodes, result);
75412                 break;
75413             case 251 /* CaseBlock */:
75414                 result = reduceNodes(node.clauses, cbNodes, result);
75415                 break;
75416             case 253 /* ImportEqualsDeclaration */:
75417                 result = reduceNodes(node.decorators, cbNodes, result);
75418                 result = reduceNodes(node.modifiers, cbNodes, result);
75419                 result = reduceNode(node.name, cbNode, result);
75420                 result = reduceNode(node.moduleReference, cbNode, result);
75421                 break;
75422             case 254 /* ImportDeclaration */:
75423                 result = reduceNodes(node.decorators, cbNodes, result);
75424                 result = reduceNodes(node.modifiers, cbNodes, result);
75425                 result = reduceNode(node.importClause, cbNode, result);
75426                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75427                 break;
75428             case 255 /* ImportClause */:
75429                 result = reduceNode(node.name, cbNode, result);
75430                 result = reduceNode(node.namedBindings, cbNode, result);
75431                 break;
75432             case 256 /* NamespaceImport */:
75433                 result = reduceNode(node.name, cbNode, result);
75434                 break;
75435             case 262 /* NamespaceExport */:
75436                 result = reduceNode(node.name, cbNode, result);
75437                 break;
75438             case 257 /* NamedImports */:
75439             case 261 /* NamedExports */:
75440                 result = reduceNodes(node.elements, cbNodes, result);
75441                 break;
75442             case 258 /* ImportSpecifier */:
75443             case 263 /* ExportSpecifier */:
75444                 result = reduceNode(node.propertyName, cbNode, result);
75445                 result = reduceNode(node.name, cbNode, result);
75446                 break;
75447             case 259 /* ExportAssignment */:
75448                 result = ts.reduceLeft(node.decorators, cbNode, result);
75449                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75450                 result = reduceNode(node.expression, cbNode, result);
75451                 break;
75452             case 260 /* ExportDeclaration */:
75453                 result = ts.reduceLeft(node.decorators, cbNode, result);
75454                 result = ts.reduceLeft(node.modifiers, cbNode, result);
75455                 result = reduceNode(node.exportClause, cbNode, result);
75456                 result = reduceNode(node.moduleSpecifier, cbNode, result);
75457                 break;
75458             // Module references
75459             case 265 /* ExternalModuleReference */:
75460                 result = reduceNode(node.expression, cbNode, result);
75461                 break;
75462             // JSX
75463             case 266 /* JsxElement */:
75464                 result = reduceNode(node.openingElement, cbNode, result);
75465                 result = ts.reduceLeft(node.children, cbNode, result);
75466                 result = reduceNode(node.closingElement, cbNode, result);
75467                 break;
75468             case 270 /* JsxFragment */:
75469                 result = reduceNode(node.openingFragment, cbNode, result);
75470                 result = ts.reduceLeft(node.children, cbNode, result);
75471                 result = reduceNode(node.closingFragment, cbNode, result);
75472                 break;
75473             case 267 /* JsxSelfClosingElement */:
75474             case 268 /* JsxOpeningElement */:
75475                 result = reduceNode(node.tagName, cbNode, result);
75476                 result = reduceNodes(node.typeArguments, cbNode, result);
75477                 result = reduceNode(node.attributes, cbNode, result);
75478                 break;
75479             case 274 /* JsxAttributes */:
75480                 result = reduceNodes(node.properties, cbNodes, result);
75481                 break;
75482             case 269 /* JsxClosingElement */:
75483                 result = reduceNode(node.tagName, cbNode, result);
75484                 break;
75485             case 273 /* JsxAttribute */:
75486                 result = reduceNode(node.name, cbNode, result);
75487                 result = reduceNode(node.initializer, cbNode, result);
75488                 break;
75489             case 275 /* JsxSpreadAttribute */:
75490                 result = reduceNode(node.expression, cbNode, result);
75491                 break;
75492             case 276 /* JsxExpression */:
75493                 result = reduceNode(node.expression, cbNode, result);
75494                 break;
75495             // Clauses
75496             case 277 /* CaseClause */:
75497                 result = reduceNode(node.expression, cbNode, result);
75498             // falls through
75499             case 278 /* DefaultClause */:
75500                 result = reduceNodes(node.statements, cbNodes, result);
75501                 break;
75502             case 279 /* HeritageClause */:
75503                 result = reduceNodes(node.types, cbNodes, result);
75504                 break;
75505             case 280 /* CatchClause */:
75506                 result = reduceNode(node.variableDeclaration, cbNode, result);
75507                 result = reduceNode(node.block, cbNode, result);
75508                 break;
75509             // Property assignments
75510             case 281 /* PropertyAssignment */:
75511                 result = reduceNode(node.name, cbNode, result);
75512                 result = reduceNode(node.initializer, cbNode, result);
75513                 break;
75514             case 282 /* ShorthandPropertyAssignment */:
75515                 result = reduceNode(node.name, cbNode, result);
75516                 result = reduceNode(node.objectAssignmentInitializer, cbNode, result);
75517                 break;
75518             case 283 /* SpreadAssignment */:
75519                 result = reduceNode(node.expression, cbNode, result);
75520                 break;
75521             // Enum
75522             case 284 /* EnumMember */:
75523                 result = reduceNode(node.name, cbNode, result);
75524                 result = reduceNode(node.initializer, cbNode, result);
75525                 break;
75526             // Top-level nodes
75527             case 290 /* SourceFile */:
75528                 result = reduceNodes(node.statements, cbNodes, result);
75529                 break;
75530             // Transformation nodes
75531             case 326 /* PartiallyEmittedExpression */:
75532                 result = reduceNode(node.expression, cbNode, result);
75533                 break;
75534             case 327 /* CommaListExpression */:
75535                 result = reduceNodes(node.elements, cbNodes, result);
75536                 break;
75537             default:
75538                 break;
75539         }
75540         return result;
75541     }
75542     ts.reduceEachChild = reduceEachChild;
75543     function findSpanEnd(array, test, start) {
75544         var i = start;
75545         while (i < array.length && test(array[i])) {
75546             i++;
75547         }
75548         return i;
75549     }
75550     function mergeLexicalEnvironment(statements, declarations) {
75551         if (!ts.some(declarations)) {
75552             return statements;
75553         }
75554         // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
75555         //
75556         // Given:
75557         //
75558         // | Left                               | Right                               |
75559         // |------------------------------------|-------------------------------------|
75560         // | [standard prologues (left)]        | [standard prologues (right)]        |
75561         // | [hoisted functions (left)]         | [hoisted functions (right)]         |
75562         // | [hoisted variables (left)]         | [hoisted variables (right)]         |
75563         // | [lexical init statements (left)]   | [lexical init statements (right)]   |
75564         // | [other statements (left)]          |                                     |
75565         //
75566         // The resulting statement list will be:
75567         //
75568         // | Result                              |
75569         // |-------------------------------------|
75570         // | [standard prologues (right)]        |
75571         // | [standard prologues (left)]         |
75572         // | [hoisted functions (right)]         |
75573         // | [hoisted functions (left)]          |
75574         // | [hoisted variables (right)]         |
75575         // | [hoisted variables (left)]          |
75576         // | [lexical init statements (right)]   |
75577         // | [lexical init statements (left)]    |
75578         // | [other statements (left)]           |
75579         //
75580         // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
75581         // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
75582         // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
75583         var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
75584         var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
75585         var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
75586         // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
75587         var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
75588         var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
75589         var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
75590         var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
75591         ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
75592         // splice prologues from the right into the left. We do this in reverse order
75593         // so that we don't need to recompute the index on the left when we insert items.
75594         var left = ts.isNodeArray(statements) ? statements.slice() : statements;
75595         // splice other custom prologues from right into left
75596         if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
75597             left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
75598         }
75599         // splice hoisted variables from right into left
75600         if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
75601             left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
75602         }
75603         // splice hoisted functions from right into left
75604         if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
75605             left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
75606         }
75607         // splice standard prologues from right into left (that are not already in left)
75608         if (rightStandardPrologueEnd > 0) {
75609             if (leftStandardPrologueEnd === 0) {
75610                 left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
75611             }
75612             else {
75613                 var leftPrologues = ts.createMap();
75614                 for (var i = 0; i < leftStandardPrologueEnd; i++) {
75615                     var leftPrologue = statements[i];
75616                     leftPrologues.set(leftPrologue.expression.text, true);
75617                 }
75618                 for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
75619                     var rightPrologue = declarations[i];
75620                     if (!leftPrologues.has(rightPrologue.expression.text)) {
75621                         left.unshift(rightPrologue);
75622                     }
75623                 }
75624             }
75625         }
75626         if (ts.isNodeArray(statements)) {
75627             return ts.setTextRange(ts.createNodeArray(left, statements.hasTrailingComma), statements);
75628         }
75629         return statements;
75630     }
75631     ts.mergeLexicalEnvironment = mergeLexicalEnvironment;
75632     /**
75633      * Lifts a NodeArray containing only Statement nodes to a block.
75634      *
75635      * @param nodes The NodeArray.
75636      */
75637     function liftToBlock(nodes) {
75638         ts.Debug.assert(ts.every(nodes, ts.isStatement), "Cannot lift nodes to a Block.");
75639         return ts.singleOrUndefined(nodes) || ts.createBlock(nodes);
75640     }
75641     ts.liftToBlock = liftToBlock;
75642     /**
75643      * Aggregates the TransformFlags for a Node and its subtree.
75644      */
75645     function aggregateTransformFlags(node) {
75646         aggregateTransformFlagsForNode(node);
75647         return node;
75648     }
75649     ts.aggregateTransformFlags = aggregateTransformFlags;
75650     /**
75651      * Aggregates the TransformFlags for a Node and its subtree. The flags for the subtree are
75652      * computed first, then the transform flags for the current node are computed from the subtree
75653      * flags and the state of the current node. Finally, the transform flags of the node are
75654      * returned, excluding any flags that should not be included in its parent node's subtree
75655      * flags.
75656      */
75657     function aggregateTransformFlagsForNode(node) {
75658         if (node === undefined) {
75659             return 0 /* None */;
75660         }
75661         if (node.transformFlags & 536870912 /* HasComputedFlags */) {
75662             return node.transformFlags & ~ts.getTransformFlagsSubtreeExclusions(node.kind);
75663         }
75664         var subtreeFlags = aggregateTransformFlagsForSubtree(node);
75665         return ts.computeTransformFlagsForNode(node, subtreeFlags);
75666     }
75667     function aggregateTransformFlagsForNodeArray(nodes) {
75668         if (nodes === undefined) {
75669             return 0 /* None */;
75670         }
75671         var subtreeFlags = 0 /* None */;
75672         var nodeArrayFlags = 0 /* None */;
75673         for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) {
75674             var node = nodes_3[_i];
75675             subtreeFlags |= aggregateTransformFlagsForNode(node);
75676             nodeArrayFlags |= node.transformFlags & ~536870912 /* HasComputedFlags */;
75677         }
75678         nodes.transformFlags = nodeArrayFlags | 536870912 /* HasComputedFlags */;
75679         return subtreeFlags;
75680     }
75681     /**
75682      * Aggregates the transform flags for the subtree of a node.
75683      */
75684     function aggregateTransformFlagsForSubtree(node) {
75685         // We do not transform ambient declarations or types, so there is no need to
75686         // recursively aggregate transform flags.
75687         if (ts.hasModifier(node, 2 /* Ambient */) || (ts.isTypeNode(node) && node.kind !== 216 /* ExpressionWithTypeArguments */)) {
75688             return 0 /* None */;
75689         }
75690         // Aggregate the transform flags of each child.
75691         return reduceEachChild(node, 0 /* None */, aggregateTransformFlagsForChildNode, aggregateTransformFlagsForChildNodes);
75692     }
75693     /**
75694      * Aggregates the TransformFlags of a child node with the TransformFlags of its
75695      * siblings.
75696      */
75697     function aggregateTransformFlagsForChildNode(transformFlags, node) {
75698         return transformFlags | aggregateTransformFlagsForNode(node);
75699     }
75700     function aggregateTransformFlagsForChildNodes(transformFlags, nodes) {
75701         return transformFlags | aggregateTransformFlagsForNodeArray(nodes);
75702     }
75703 })(ts || (ts = {}));
75704 /* @internal */
75705 var ts;
75706 (function (ts) {
75707     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
75708         var _a = generatorOptions.extendedDiagnostics
75709             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
75710             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
75711         // Current source map file and its index in the sources list
75712         var rawSources = [];
75713         var sources = [];
75714         var sourceToSourceIndexMap = ts.createMap();
75715         var sourcesContent;
75716         var names = [];
75717         var nameToNameIndexMap;
75718         var mappings = "";
75719         // Last recorded and encoded mappings
75720         var lastGeneratedLine = 0;
75721         var lastGeneratedCharacter = 0;
75722         var lastSourceIndex = 0;
75723         var lastSourceLine = 0;
75724         var lastSourceCharacter = 0;
75725         var lastNameIndex = 0;
75726         var hasLast = false;
75727         var pendingGeneratedLine = 0;
75728         var pendingGeneratedCharacter = 0;
75729         var pendingSourceIndex = 0;
75730         var pendingSourceLine = 0;
75731         var pendingSourceCharacter = 0;
75732         var pendingNameIndex = 0;
75733         var hasPending = false;
75734         var hasPendingSource = false;
75735         var hasPendingName = false;
75736         return {
75737             getSources: function () { return rawSources; },
75738             addSource: addSource,
75739             setSourceContent: setSourceContent,
75740             addName: addName,
75741             addMapping: addMapping,
75742             appendSourceMap: appendSourceMap,
75743             toJSON: toJSON,
75744             toString: function () { return JSON.stringify(toJSON()); }
75745         };
75746         function addSource(fileName) {
75747             enter();
75748             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
75749             /*isAbsolutePathAnUrl*/ true);
75750             var sourceIndex = sourceToSourceIndexMap.get(source);
75751             if (sourceIndex === undefined) {
75752                 sourceIndex = sources.length;
75753                 sources.push(source);
75754                 rawSources.push(fileName);
75755                 sourceToSourceIndexMap.set(source, sourceIndex);
75756             }
75757             exit();
75758             return sourceIndex;
75759         }
75760         /* eslint-disable boolean-trivia, no-null/no-null */
75761         function setSourceContent(sourceIndex, content) {
75762             enter();
75763             if (content !== null) {
75764                 if (!sourcesContent)
75765                     sourcesContent = [];
75766                 while (sourcesContent.length < sourceIndex) {
75767                     sourcesContent.push(null);
75768                 }
75769                 sourcesContent[sourceIndex] = content;
75770             }
75771             exit();
75772         }
75773         /* eslint-enable boolean-trivia, no-null/no-null */
75774         function addName(name) {
75775             enter();
75776             if (!nameToNameIndexMap)
75777                 nameToNameIndexMap = ts.createMap();
75778             var nameIndex = nameToNameIndexMap.get(name);
75779             if (nameIndex === undefined) {
75780                 nameIndex = names.length;
75781                 names.push(name);
75782                 nameToNameIndexMap.set(name, nameIndex);
75783             }
75784             exit();
75785             return nameIndex;
75786         }
75787         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
75788             return !hasPending
75789                 || pendingGeneratedLine !== generatedLine
75790                 || pendingGeneratedCharacter !== generatedCharacter;
75791         }
75792         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
75793             return sourceIndex !== undefined
75794                 && sourceLine !== undefined
75795                 && sourceCharacter !== undefined
75796                 && pendingSourceIndex === sourceIndex
75797                 && (pendingSourceLine > sourceLine
75798                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
75799         }
75800         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
75801             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75802             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75803             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
75804             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
75805             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
75806             enter();
75807             // If this location wasn't recorded or the location in source is going backwards, record the mapping
75808             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
75809                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
75810                 commitPendingMapping();
75811                 pendingGeneratedLine = generatedLine;
75812                 pendingGeneratedCharacter = generatedCharacter;
75813                 hasPendingSource = false;
75814                 hasPendingName = false;
75815                 hasPending = true;
75816             }
75817             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
75818                 pendingSourceIndex = sourceIndex;
75819                 pendingSourceLine = sourceLine;
75820                 pendingSourceCharacter = sourceCharacter;
75821                 hasPendingSource = true;
75822                 if (nameIndex !== undefined) {
75823                     pendingNameIndex = nameIndex;
75824                     hasPendingName = true;
75825                 }
75826             }
75827             exit();
75828         }
75829         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
75830             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
75831             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
75832             enter();
75833             // First, decode the old component sourcemap
75834             var sourceIndexToNewSourceIndexMap = [];
75835             var nameIndexToNewNameIndexMap;
75836             var mappingIterator = decodeMappings(map.mappings);
75837             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
75838                 var raw = iterResult.value;
75839                 if (end && (raw.generatedLine > end.line ||
75840                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
75841                     break;
75842                 }
75843                 if (start && (raw.generatedLine < start.line ||
75844                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
75845                     continue;
75846                 }
75847                 // Then reencode all the updated mappings into the overall map
75848                 var newSourceIndex = void 0;
75849                 var newSourceLine = void 0;
75850                 var newSourceCharacter = void 0;
75851                 var newNameIndex = void 0;
75852                 if (raw.sourceIndex !== undefined) {
75853                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
75854                     if (newSourceIndex === undefined) {
75855                         // Apply offsets to each position and fixup source entries
75856                         var rawPath = map.sources[raw.sourceIndex];
75857                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
75858                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
75859                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
75860                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
75861                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
75862                         }
75863                     }
75864                     newSourceLine = raw.sourceLine;
75865                     newSourceCharacter = raw.sourceCharacter;
75866                     if (map.names && raw.nameIndex !== undefined) {
75867                         if (!nameIndexToNewNameIndexMap)
75868                             nameIndexToNewNameIndexMap = [];
75869                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
75870                         if (newNameIndex === undefined) {
75871                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
75872                         }
75873                     }
75874                 }
75875                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
75876                 var newGeneratedLine = rawGeneratedLine + generatedLine;
75877                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
75878                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
75879                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
75880             }
75881             exit();
75882         }
75883         function shouldCommitMapping() {
75884             return !hasLast
75885                 || lastGeneratedLine !== pendingGeneratedLine
75886                 || lastGeneratedCharacter !== pendingGeneratedCharacter
75887                 || lastSourceIndex !== pendingSourceIndex
75888                 || lastSourceLine !== pendingSourceLine
75889                 || lastSourceCharacter !== pendingSourceCharacter
75890                 || lastNameIndex !== pendingNameIndex;
75891         }
75892         function commitPendingMapping() {
75893             if (!hasPending || !shouldCommitMapping()) {
75894                 return;
75895             }
75896             enter();
75897             // Line/Comma delimiters
75898             if (lastGeneratedLine < pendingGeneratedLine) {
75899                 // Emit line delimiters
75900                 do {
75901                     mappings += ";";
75902                     lastGeneratedLine++;
75903                     lastGeneratedCharacter = 0;
75904                 } while (lastGeneratedLine < pendingGeneratedLine);
75905             }
75906             else {
75907                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
75908                 // Emit comma to separate the entry
75909                 if (hasLast) {
75910                     mappings += ",";
75911                 }
75912             }
75913             // 1. Relative generated character
75914             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
75915             lastGeneratedCharacter = pendingGeneratedCharacter;
75916             if (hasPendingSource) {
75917                 // 2. Relative sourceIndex
75918                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
75919                 lastSourceIndex = pendingSourceIndex;
75920                 // 3. Relative source line
75921                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
75922                 lastSourceLine = pendingSourceLine;
75923                 // 4. Relative source character
75924                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
75925                 lastSourceCharacter = pendingSourceCharacter;
75926                 if (hasPendingName) {
75927                     // 5. Relative nameIndex
75928                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
75929                     lastNameIndex = pendingNameIndex;
75930                 }
75931             }
75932             hasLast = true;
75933             exit();
75934         }
75935         function toJSON() {
75936             commitPendingMapping();
75937             return {
75938                 version: 3,
75939                 file: file,
75940                 sourceRoot: sourceRoot,
75941                 sources: sources,
75942                 names: names,
75943                 mappings: mappings,
75944                 sourcesContent: sourcesContent,
75945             };
75946         }
75947     }
75948     ts.createSourceMapGenerator = createSourceMapGenerator;
75949     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
75950     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
75951     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
75952     function getLineInfo(text, lineStarts) {
75953         return {
75954             getLineCount: function () { return lineStarts.length; },
75955             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
75956         };
75957     }
75958     ts.getLineInfo = getLineInfo;
75959     /**
75960      * Tries to find the sourceMappingURL comment at the end of a file.
75961      */
75962     function tryGetSourceMappingURL(lineInfo) {
75963         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
75964             var line = lineInfo.getLineText(index);
75965             var comment = sourceMapCommentRegExp.exec(line);
75966             if (comment) {
75967                 return comment[1];
75968             }
75969             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
75970             else if (!line.match(whitespaceOrMapCommentRegExp)) {
75971                 break;
75972             }
75973         }
75974     }
75975     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
75976     /* eslint-disable no-null/no-null */
75977     function isStringOrNull(x) {
75978         return typeof x === "string" || x === null;
75979     }
75980     function isRawSourceMap(x) {
75981         return x !== null
75982             && typeof x === "object"
75983             && x.version === 3
75984             && typeof x.file === "string"
75985             && typeof x.mappings === "string"
75986             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
75987             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
75988             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
75989             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
75990     }
75991     ts.isRawSourceMap = isRawSourceMap;
75992     /* eslint-enable no-null/no-null */
75993     function tryParseRawSourceMap(text) {
75994         try {
75995             var parsed = JSON.parse(text);
75996             if (isRawSourceMap(parsed)) {
75997                 return parsed;
75998             }
75999         }
76000         catch (_a) {
76001             // empty
76002         }
76003         return undefined;
76004     }
76005     ts.tryParseRawSourceMap = tryParseRawSourceMap;
76006     function decodeMappings(mappings) {
76007         var done = false;
76008         var pos = 0;
76009         var generatedLine = 0;
76010         var generatedCharacter = 0;
76011         var sourceIndex = 0;
76012         var sourceLine = 0;
76013         var sourceCharacter = 0;
76014         var nameIndex = 0;
76015         var error;
76016         return {
76017             get pos() { return pos; },
76018             get error() { return error; },
76019             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
76020             next: function () {
76021                 while (!done && pos < mappings.length) {
76022                     var ch = mappings.charCodeAt(pos);
76023                     if (ch === 59 /* semicolon */) {
76024                         // new line
76025                         generatedLine++;
76026                         generatedCharacter = 0;
76027                         pos++;
76028                         continue;
76029                     }
76030                     if (ch === 44 /* comma */) {
76031                         // Next entry is on same line - no action needed
76032                         pos++;
76033                         continue;
76034                     }
76035                     var hasSource = false;
76036                     var hasName = false;
76037                     generatedCharacter += base64VLQFormatDecode();
76038                     if (hasReportedError())
76039                         return stopIterating();
76040                     if (generatedCharacter < 0)
76041                         return setErrorAndStopIterating("Invalid generatedCharacter found");
76042                     if (!isSourceMappingSegmentEnd()) {
76043                         hasSource = true;
76044                         sourceIndex += base64VLQFormatDecode();
76045                         if (hasReportedError())
76046                             return stopIterating();
76047                         if (sourceIndex < 0)
76048                             return setErrorAndStopIterating("Invalid sourceIndex found");
76049                         if (isSourceMappingSegmentEnd())
76050                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
76051                         sourceLine += base64VLQFormatDecode();
76052                         if (hasReportedError())
76053                             return stopIterating();
76054                         if (sourceLine < 0)
76055                             return setErrorAndStopIterating("Invalid sourceLine found");
76056                         if (isSourceMappingSegmentEnd())
76057                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
76058                         sourceCharacter += base64VLQFormatDecode();
76059                         if (hasReportedError())
76060                             return stopIterating();
76061                         if (sourceCharacter < 0)
76062                             return setErrorAndStopIterating("Invalid sourceCharacter found");
76063                         if (!isSourceMappingSegmentEnd()) {
76064                             hasName = true;
76065                             nameIndex += base64VLQFormatDecode();
76066                             if (hasReportedError())
76067                                 return stopIterating();
76068                             if (nameIndex < 0)
76069                                 return setErrorAndStopIterating("Invalid nameIndex found");
76070                             if (!isSourceMappingSegmentEnd())
76071                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
76072                         }
76073                     }
76074                     return { value: captureMapping(hasSource, hasName), done: done };
76075                 }
76076                 return stopIterating();
76077             }
76078         };
76079         function captureMapping(hasSource, hasName) {
76080             return {
76081                 generatedLine: generatedLine,
76082                 generatedCharacter: generatedCharacter,
76083                 sourceIndex: hasSource ? sourceIndex : undefined,
76084                 sourceLine: hasSource ? sourceLine : undefined,
76085                 sourceCharacter: hasSource ? sourceCharacter : undefined,
76086                 nameIndex: hasName ? nameIndex : undefined
76087             };
76088         }
76089         function stopIterating() {
76090             done = true;
76091             return { value: undefined, done: true };
76092         }
76093         function setError(message) {
76094             if (error === undefined) {
76095                 error = message;
76096             }
76097         }
76098         function setErrorAndStopIterating(message) {
76099             setError(message);
76100             return stopIterating();
76101         }
76102         function hasReportedError() {
76103             return error !== undefined;
76104         }
76105         function isSourceMappingSegmentEnd() {
76106             return (pos === mappings.length ||
76107                 mappings.charCodeAt(pos) === 44 /* comma */ ||
76108                 mappings.charCodeAt(pos) === 59 /* semicolon */);
76109         }
76110         function base64VLQFormatDecode() {
76111             var moreDigits = true;
76112             var shiftCount = 0;
76113             var value = 0;
76114             for (; moreDigits; pos++) {
76115                 if (pos >= mappings.length)
76116                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
76117                 // 6 digit number
76118                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
76119                 if (currentByte === -1)
76120                     return setError("Invalid character in VLQ"), -1;
76121                 // If msb is set, we still have more bits to continue
76122                 moreDigits = (currentByte & 32) !== 0;
76123                 // least significant 5 bits are the next msbs in the final value.
76124                 value = value | ((currentByte & 31) << shiftCount);
76125                 shiftCount += 5;
76126             }
76127             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
76128             if ((value & 1) === 0) {
76129                 // + number
76130                 value = value >> 1;
76131             }
76132             else {
76133                 // - number
76134                 value = value >> 1;
76135                 value = -value;
76136             }
76137             return value;
76138         }
76139     }
76140     ts.decodeMappings = decodeMappings;
76141     function sameMapping(left, right) {
76142         return left === right
76143             || left.generatedLine === right.generatedLine
76144                 && left.generatedCharacter === right.generatedCharacter
76145                 && left.sourceIndex === right.sourceIndex
76146                 && left.sourceLine === right.sourceLine
76147                 && left.sourceCharacter === right.sourceCharacter
76148                 && left.nameIndex === right.nameIndex;
76149     }
76150     ts.sameMapping = sameMapping;
76151     function isSourceMapping(mapping) {
76152         return mapping.sourceIndex !== undefined
76153             && mapping.sourceLine !== undefined
76154             && mapping.sourceCharacter !== undefined;
76155     }
76156     ts.isSourceMapping = isSourceMapping;
76157     function base64FormatEncode(value) {
76158         return value >= 0 && value < 26 ? 65 /* A */ + value :
76159             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
76160                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
76161                     value === 62 ? 43 /* plus */ :
76162                         value === 63 ? 47 /* slash */ :
76163                             ts.Debug.fail(value + ": not a base64 value");
76164     }
76165     function base64FormatDecode(ch) {
76166         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
76167             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
76168                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
76169                     ch === 43 /* plus */ ? 62 :
76170                         ch === 47 /* slash */ ? 63 :
76171                             -1;
76172     }
76173     function base64VLQFormatEncode(inValue) {
76174         // Add a new least significant bit that has the sign of the value.
76175         // if negative number the least significant bit that gets added to the number has value 1
76176         // else least significant bit value that gets added is 0
76177         // eg. -1 changes to binary : 01 [1] => 3
76178         //     +1 changes to binary : 01 [0] => 2
76179         if (inValue < 0) {
76180             inValue = ((-inValue) << 1) + 1;
76181         }
76182         else {
76183             inValue = inValue << 1;
76184         }
76185         // Encode 5 bits at a time starting from least significant bits
76186         var encodedStr = "";
76187         do {
76188             var currentDigit = inValue & 31; // 11111
76189             inValue = inValue >> 5;
76190             if (inValue > 0) {
76191                 // There are still more digits to decode, set the msb (6th bit)
76192                 currentDigit = currentDigit | 32;
76193             }
76194             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
76195         } while (inValue > 0);
76196         return encodedStr;
76197     }
76198     function isSourceMappedPosition(value) {
76199         return value.sourceIndex !== undefined
76200             && value.sourcePosition !== undefined;
76201     }
76202     function sameMappedPosition(left, right) {
76203         return left.generatedPosition === right.generatedPosition
76204             && left.sourceIndex === right.sourceIndex
76205             && left.sourcePosition === right.sourcePosition;
76206     }
76207     function compareSourcePositions(left, right) {
76208         // Compares sourcePosition without comparing sourceIndex
76209         // since the mappings are grouped by sourceIndex
76210         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
76211         return ts.compareValues(left.sourcePosition, right.sourcePosition);
76212     }
76213     function compareGeneratedPositions(left, right) {
76214         return ts.compareValues(left.generatedPosition, right.generatedPosition);
76215     }
76216     function getSourcePositionOfMapping(value) {
76217         return value.sourcePosition;
76218     }
76219     function getGeneratedPositionOfMapping(value) {
76220         return value.generatedPosition;
76221     }
76222     function createDocumentPositionMapper(host, map, mapPath) {
76223         var mapDirectory = ts.getDirectoryPath(mapPath);
76224         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
76225         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
76226         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
76227         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
76228         var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
76229         var decodedMappings;
76230         var generatedMappings;
76231         var sourceMappings;
76232         return {
76233             getSourcePosition: getSourcePosition,
76234             getGeneratedPosition: getGeneratedPosition
76235         };
76236         function processMapping(mapping) {
76237             var generatedPosition = generatedFile !== undefined
76238                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
76239                 : -1;
76240             var source;
76241             var sourcePosition;
76242             if (isSourceMapping(mapping)) {
76243                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
76244                 source = map.sources[mapping.sourceIndex];
76245                 sourcePosition = sourceFile !== undefined
76246                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
76247                     : -1;
76248             }
76249             return {
76250                 generatedPosition: generatedPosition,
76251                 source: source,
76252                 sourceIndex: mapping.sourceIndex,
76253                 sourcePosition: sourcePosition,
76254                 nameIndex: mapping.nameIndex
76255             };
76256         }
76257         function getDecodedMappings() {
76258             if (decodedMappings === undefined) {
76259                 var decoder = decodeMappings(map.mappings);
76260                 var mappings = ts.arrayFrom(decoder, processMapping);
76261                 if (decoder.error !== undefined) {
76262                     if (host.log) {
76263                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
76264                     }
76265                     decodedMappings = ts.emptyArray;
76266                 }
76267                 else {
76268                     decodedMappings = mappings;
76269                 }
76270             }
76271             return decodedMappings;
76272         }
76273         function getSourceMappings(sourceIndex) {
76274             if (sourceMappings === undefined) {
76275                 var lists = [];
76276                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76277                     var mapping = _a[_i];
76278                     if (!isSourceMappedPosition(mapping))
76279                         continue;
76280                     var list = lists[mapping.sourceIndex];
76281                     if (!list)
76282                         lists[mapping.sourceIndex] = list = [];
76283                     list.push(mapping);
76284                 }
76285                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
76286             }
76287             return sourceMappings[sourceIndex];
76288         }
76289         function getGeneratedMappings() {
76290             if (generatedMappings === undefined) {
76291                 var list = [];
76292                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
76293                     var mapping = _a[_i];
76294                     list.push(mapping);
76295                 }
76296                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
76297             }
76298             return generatedMappings;
76299         }
76300         function getGeneratedPosition(loc) {
76301             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
76302             if (sourceIndex === undefined)
76303                 return loc;
76304             var sourceMappings = getSourceMappings(sourceIndex);
76305             if (!ts.some(sourceMappings))
76306                 return loc;
76307             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
76308             if (targetIndex < 0) {
76309                 // if no exact match, closest is 2's complement of result
76310                 targetIndex = ~targetIndex;
76311             }
76312             var mapping = sourceMappings[targetIndex];
76313             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
76314                 return loc;
76315             }
76316             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
76317         }
76318         function getSourcePosition(loc) {
76319             var generatedMappings = getGeneratedMappings();
76320             if (!ts.some(generatedMappings))
76321                 return loc;
76322             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
76323             if (targetIndex < 0) {
76324                 // if no exact match, closest is 2's complement of result
76325                 targetIndex = ~targetIndex;
76326             }
76327             var mapping = generatedMappings[targetIndex];
76328             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
76329                 return loc;
76330             }
76331             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
76332         }
76333     }
76334     ts.createDocumentPositionMapper = createDocumentPositionMapper;
76335     ts.identitySourceMapConsumer = {
76336         getSourcePosition: ts.identity,
76337         getGeneratedPosition: ts.identity
76338     };
76339 })(ts || (ts = {}));
76340 /* @internal */
76341 var ts;
76342 (function (ts) {
76343     function getOriginalNodeId(node) {
76344         node = ts.getOriginalNode(node);
76345         return node ? ts.getNodeId(node) : 0;
76346     }
76347     ts.getOriginalNodeId = getOriginalNodeId;
76348     function containsDefaultReference(node) {
76349         if (!node)
76350             return false;
76351         if (!ts.isNamedImports(node))
76352             return false;
76353         return ts.some(node.elements, isNamedDefaultReference);
76354     }
76355     function isNamedDefaultReference(e) {
76356         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
76357     }
76358     function chainBundle(transformSourceFile) {
76359         return transformSourceFileOrBundle;
76360         function transformSourceFileOrBundle(node) {
76361             return node.kind === 290 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
76362         }
76363         function transformBundle(node) {
76364             return ts.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
76365         }
76366     }
76367     ts.chainBundle = chainBundle;
76368     function getExportNeedsImportStarHelper(node) {
76369         return !!ts.getNamespaceDeclarationNode(node);
76370     }
76371     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
76372     function getImportNeedsImportStarHelper(node) {
76373         if (!!ts.getNamespaceDeclarationNode(node)) {
76374             return true;
76375         }
76376         var bindings = node.importClause && node.importClause.namedBindings;
76377         if (!bindings) {
76378             return false;
76379         }
76380         if (!ts.isNamedImports(bindings))
76381             return false;
76382         var defaultRefCount = 0;
76383         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
76384             var binding = _a[_i];
76385             if (isNamedDefaultReference(binding)) {
76386                 defaultRefCount++;
76387             }
76388         }
76389         // 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
76390         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
76391     }
76392     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
76393     function getImportNeedsImportDefaultHelper(node) {
76394         // 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)
76395         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
76396     }
76397     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
76398     function collectExternalModuleInfo(sourceFile, resolver, compilerOptions) {
76399         var externalImports = [];
76400         var exportSpecifiers = ts.createMultiMap();
76401         var exportedBindings = [];
76402         var uniqueExports = ts.createMap();
76403         var exportedNames;
76404         var hasExportDefault = false;
76405         var exportEquals;
76406         var hasExportStarsToExportValues = false;
76407         var hasImportStar = false;
76408         var hasImportDefault = false;
76409         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76410             var node = _a[_i];
76411             switch (node.kind) {
76412                 case 254 /* ImportDeclaration */:
76413                     // import "mod"
76414                     // import x from "mod"
76415                     // import * as x from "mod"
76416                     // import { x, y } from "mod"
76417                     externalImports.push(node);
76418                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
76419                         hasImportStar = true;
76420                     }
76421                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
76422                         hasImportDefault = true;
76423                     }
76424                     break;
76425                 case 253 /* ImportEqualsDeclaration */:
76426                     if (node.moduleReference.kind === 265 /* ExternalModuleReference */) {
76427                         // import x = require("mod")
76428                         externalImports.push(node);
76429                     }
76430                     break;
76431                 case 260 /* ExportDeclaration */:
76432                     if (node.moduleSpecifier) {
76433                         if (!node.exportClause) {
76434                             // export * from "mod"
76435                             externalImports.push(node);
76436                             hasExportStarsToExportValues = true;
76437                         }
76438                         else {
76439                             // export * as ns from "mod"
76440                             // export { x, y } from "mod"
76441                             externalImports.push(node);
76442                         }
76443                     }
76444                     else {
76445                         // export { x, y }
76446                         for (var _b = 0, _c = ts.cast(node.exportClause, ts.isNamedExports).elements; _b < _c.length; _b++) {
76447                             var specifier = _c[_b];
76448                             if (!uniqueExports.get(ts.idText(specifier.name))) {
76449                                 var name = specifier.propertyName || specifier.name;
76450                                 exportSpecifiers.add(ts.idText(name), specifier);
76451                                 var decl = resolver.getReferencedImportDeclaration(name)
76452                                     || resolver.getReferencedValueDeclaration(name);
76453                                 if (decl) {
76454                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
76455                                 }
76456                                 uniqueExports.set(ts.idText(specifier.name), true);
76457                                 exportedNames = ts.append(exportedNames, specifier.name);
76458                             }
76459                         }
76460                     }
76461                     break;
76462                 case 259 /* ExportAssignment */:
76463                     if (node.isExportEquals && !exportEquals) {
76464                         // export = x
76465                         exportEquals = node;
76466                     }
76467                     break;
76468                 case 225 /* VariableStatement */:
76469                     if (ts.hasModifier(node, 1 /* Export */)) {
76470                         for (var _d = 0, _e = node.declarationList.declarations; _d < _e.length; _d++) {
76471                             var decl = _e[_d];
76472                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
76473                         }
76474                     }
76475                     break;
76476                 case 244 /* FunctionDeclaration */:
76477                     if (ts.hasModifier(node, 1 /* Export */)) {
76478                         if (ts.hasModifier(node, 512 /* Default */)) {
76479                             // export default function() { }
76480                             if (!hasExportDefault) {
76481                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76482                                 hasExportDefault = true;
76483                             }
76484                         }
76485                         else {
76486                             // export function x() { }
76487                             var name = node.name;
76488                             if (!uniqueExports.get(ts.idText(name))) {
76489                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76490                                 uniqueExports.set(ts.idText(name), true);
76491                                 exportedNames = ts.append(exportedNames, name);
76492                             }
76493                         }
76494                     }
76495                     break;
76496                 case 245 /* ClassDeclaration */:
76497                     if (ts.hasModifier(node, 1 /* Export */)) {
76498                         if (ts.hasModifier(node, 512 /* Default */)) {
76499                             // export default class { }
76500                             if (!hasExportDefault) {
76501                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), ts.getDeclarationName(node));
76502                                 hasExportDefault = true;
76503                             }
76504                         }
76505                         else {
76506                             // export class x { }
76507                             var name = node.name;
76508                             if (name && !uniqueExports.get(ts.idText(name))) {
76509                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
76510                                 uniqueExports.set(ts.idText(name), true);
76511                                 exportedNames = ts.append(exportedNames, name);
76512                             }
76513                         }
76514                     }
76515                     break;
76516             }
76517         }
76518         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
76519         if (externalHelpersImportDeclaration) {
76520             externalImports.unshift(externalHelpersImportDeclaration);
76521         }
76522         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
76523     }
76524     ts.collectExternalModuleInfo = collectExternalModuleInfo;
76525     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
76526         if (ts.isBindingPattern(decl.name)) {
76527             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
76528                 var element = _a[_i];
76529                 if (!ts.isOmittedExpression(element)) {
76530                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
76531                 }
76532             }
76533         }
76534         else if (!ts.isGeneratedIdentifier(decl.name)) {
76535             var text = ts.idText(decl.name);
76536             if (!uniqueExports.get(text)) {
76537                 uniqueExports.set(text, true);
76538                 exportedNames = ts.append(exportedNames, decl.name);
76539             }
76540         }
76541         return exportedNames;
76542     }
76543     /** Use a sparse array as a multi-map. */
76544     function multiMapSparseArrayAdd(map, key, value) {
76545         var values = map[key];
76546         if (values) {
76547             values.push(value);
76548         }
76549         else {
76550             map[key] = values = [value];
76551         }
76552         return values;
76553     }
76554     /**
76555      * Used in the module transformer to check if an expression is reasonably without sideeffect,
76556      *  and thus better to copy into multiple places rather than to cache in a temporary variable
76557      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
76558      */
76559     function isSimpleCopiableExpression(expression) {
76560         return ts.isStringLiteralLike(expression) ||
76561             expression.kind === 8 /* NumericLiteral */ ||
76562             ts.isKeyword(expression.kind) ||
76563             ts.isIdentifier(expression);
76564     }
76565     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
76566     /**
76567      * A simple inlinable expression is an expression which can be copied into multiple locations
76568      * without risk of repeating any sideeffects and whose value could not possibly change between
76569      * any such locations
76570      */
76571     function isSimpleInlineableExpression(expression) {
76572         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
76573             ts.isWellKnownSymbolSyntactically(expression);
76574     }
76575     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
76576     function isCompoundAssignment(kind) {
76577         return kind >= 63 /* FirstCompoundAssignment */
76578             && kind <= 74 /* LastCompoundAssignment */;
76579     }
76580     ts.isCompoundAssignment = isCompoundAssignment;
76581     function getNonAssignmentOperatorForCompoundAssignment(kind) {
76582         switch (kind) {
76583             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
76584             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
76585             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
76586             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
76587             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
76588             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
76589             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
76590             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
76591             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
76592             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
76593             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
76594             case 74 /* CaretEqualsToken */: return 52 /* CaretToken */;
76595         }
76596     }
76597     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
76598     /**
76599      * Adds super call and preceding prologue directives into the list of statements.
76600      *
76601      * @param ctor The constructor node.
76602      * @param result The list of statements.
76603      * @param visitor The visitor to apply to each node added to the result array.
76604      * @returns index of the statement that follows super call
76605      */
76606     function addPrologueDirectivesAndInitialSuperCall(ctor, result, visitor) {
76607         if (ctor.body) {
76608             var statements = ctor.body.statements;
76609             // add prologue directives to the list (if any)
76610             var index = ts.addPrologue(result, statements, /*ensureUseStrict*/ false, visitor);
76611             if (index === statements.length) {
76612                 // list contains nothing but prologue directives (or empty) - exit
76613                 return index;
76614             }
76615             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
76616             if (superIndex > -1) {
76617                 for (var i = index; i <= superIndex; i++) {
76618                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
76619                 }
76620                 return superIndex + 1;
76621             }
76622             return index;
76623         }
76624         return 0;
76625     }
76626     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
76627     /**
76628      * @param input Template string input strings
76629      * @param args Names which need to be made file-level unique
76630      */
76631     function helperString(input) {
76632         var args = [];
76633         for (var _i = 1; _i < arguments.length; _i++) {
76634             args[_i - 1] = arguments[_i];
76635         }
76636         return function (uniqueName) {
76637             var result = "";
76638             for (var i = 0; i < args.length; i++) {
76639                 result += input[i];
76640                 result += uniqueName(args[i]);
76641             }
76642             result += input[input.length - 1];
76643             return result;
76644         };
76645     }
76646     ts.helperString = helperString;
76647     /**
76648      * Gets all the static or all the instance property declarations of a class
76649      *
76650      * @param node The class node.
76651      * @param isStatic A value indicating whether to get properties from the static or instance side of the class.
76652      */
76653     function getProperties(node, requireInitializer, isStatic) {
76654         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
76655     }
76656     ts.getProperties = getProperties;
76657     /**
76658      * Is a class element either a static or an instance property declaration with an initializer?
76659      *
76660      * @param member The class element node.
76661      * @param isStatic A value indicating whether the member should be a static or instance member.
76662      */
76663     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
76664         return ts.isPropertyDeclaration(member)
76665             && (!!member.initializer || !requireInitializer)
76666             && ts.hasStaticModifier(member) === isStatic;
76667     }
76668     /**
76669      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
76670      *
76671      * @param member The class element node.
76672      * @param isStatic A value indicating whether the member should be a static or instance member.
76673      */
76674     function isInitializedProperty(member) {
76675         return member.kind === 159 /* PropertyDeclaration */
76676             && member.initializer !== undefined;
76677     }
76678     ts.isInitializedProperty = isInitializedProperty;
76679 })(ts || (ts = {}));
76680 /*@internal*/
76681 var ts;
76682 (function (ts) {
76683     var FlattenLevel;
76684     (function (FlattenLevel) {
76685         FlattenLevel[FlattenLevel["All"] = 0] = "All";
76686         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
76687     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
76688     /**
76689      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
76690      *
76691      * @param node The node to flatten.
76692      * @param visitor An optional visitor used to visit initializers.
76693      * @param context The transformation context.
76694      * @param level Indicates the extent to which flattening should occur.
76695      * @param needsValue An optional value indicating whether the value from the right-hand-side of
76696      * the destructuring assignment is needed as part of a larger expression.
76697      * @param createAssignmentCallback An optional callback used to create the assignment expression.
76698      */
76699     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
76700         var location = node;
76701         var value;
76702         if (ts.isDestructuringAssignment(node)) {
76703             value = node.right;
76704             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
76705                 if (ts.isDestructuringAssignment(value)) {
76706                     location = node = value;
76707                     value = node.right;
76708                 }
76709                 else {
76710                     return ts.visitNode(value, visitor, ts.isExpression);
76711                 }
76712             }
76713         }
76714         var expressions;
76715         var flattenContext = {
76716             context: context,
76717             level: level,
76718             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76719             hoistTempVariables: true,
76720             emitExpression: emitExpression,
76721             emitBindingOrAssignment: emitBindingOrAssignment,
76722             createArrayBindingOrAssignmentPattern: makeArrayAssignmentPattern,
76723             createObjectBindingOrAssignmentPattern: makeObjectAssignmentPattern,
76724             createArrayBindingOrAssignmentElement: makeAssignmentElement,
76725             visitor: visitor
76726         };
76727         if (value) {
76728             value = ts.visitNode(value, visitor, ts.isExpression);
76729             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
76730                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
76731                 // If the right-hand value of the assignment is also an assignment target then
76732                 // we need to cache the right-hand value.
76733                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
76734             }
76735             else if (needsValue) {
76736                 // If the right-hand value of the destructuring assignment needs to be preserved (as
76737                 // is the case when the destructuring assignment is part of a larger expression),
76738                 // then we need to cache the right-hand value.
76739                 //
76740                 // The source map location for the assignment should point to the entire binary
76741                 // expression.
76742                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
76743             }
76744             else if (ts.nodeIsSynthesized(node)) {
76745                 // Generally, the source map location for a destructuring assignment is the root
76746                 // expression.
76747                 //
76748                 // However, if the root expression is synthesized (as in the case
76749                 // of the initializer when transforming a ForOfStatement), then the source map
76750                 // location should point to the right-hand value of the expression.
76751                 location = value;
76752             }
76753         }
76754         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
76755         if (value && needsValue) {
76756             if (!ts.some(expressions)) {
76757                 return value;
76758             }
76759             expressions.push(value);
76760         }
76761         return ts.aggregateTransformFlags(ts.inlineExpressions(expressions)) || ts.createOmittedExpression();
76762         function emitExpression(expression) {
76763             ts.aggregateTransformFlags(expression);
76764             expressions = ts.append(expressions, expression);
76765         }
76766         function emitBindingOrAssignment(target, value, location, original) {
76767             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
76768             var expression = createAssignmentCallback
76769                 ? createAssignmentCallback(target, value, location)
76770                 : ts.setTextRange(ts.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
76771             expression.original = original;
76772             emitExpression(expression);
76773         }
76774     }
76775     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
76776     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
76777         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76778         if (ts.isBindingOrAssignmentPattern(target)) {
76779             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
76780         }
76781         else if (ts.isIdentifier(target)) {
76782             return target.escapedText === escapedName;
76783         }
76784         return false;
76785     }
76786     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
76787         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76788         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
76789             var element = elements_3[_i];
76790             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
76791                 return true;
76792             }
76793         }
76794         return false;
76795     }
76796     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
76797         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
76798         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
76799             return true;
76800         }
76801         var target = ts.getTargetOfBindingOrAssignmentElement(element);
76802         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
76803     }
76804     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
76805         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
76806     }
76807     /**
76808      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
76809      *
76810      * @param node The node to flatten.
76811      * @param visitor An optional visitor used to visit initializers.
76812      * @param context The transformation context.
76813      * @param boundValue The value bound to the declaration.
76814      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
76815      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
76816      * @param level Indicates the extent to which flattening should occur.
76817      */
76818     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
76819         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
76820         var pendingExpressions;
76821         var pendingDeclarations = [];
76822         var declarations = [];
76823         var flattenContext = {
76824             context: context,
76825             level: level,
76826             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
76827             hoistTempVariables: hoistTempVariables,
76828             emitExpression: emitExpression,
76829             emitBindingOrAssignment: emitBindingOrAssignment,
76830             createArrayBindingOrAssignmentPattern: makeArrayBindingPattern,
76831             createObjectBindingOrAssignmentPattern: makeObjectBindingPattern,
76832             createArrayBindingOrAssignmentElement: makeBindingElement,
76833             visitor: visitor
76834         };
76835         if (ts.isVariableDeclaration(node)) {
76836             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
76837             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
76838                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
76839                 // If the right-hand value of the assignment is also an assignment target then
76840                 // we need to cache the right-hand value.
76841                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
76842                 node = ts.updateVariableDeclaration(node, node.name, node.type, initializer);
76843             }
76844         }
76845         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
76846         if (pendingExpressions) {
76847             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
76848             if (hoistTempVariables) {
76849                 var value = ts.inlineExpressions(pendingExpressions);
76850                 pendingExpressions = undefined;
76851                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
76852             }
76853             else {
76854                 context.hoistVariableDeclaration(temp);
76855                 var pendingDeclaration = ts.last(pendingDeclarations);
76856                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, ts.createAssignment(temp, pendingDeclaration.value));
76857                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
76858                 pendingDeclaration.value = temp;
76859             }
76860         }
76861         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
76862             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
76863             var variable = ts.createVariableDeclaration(name, 
76864             /*type*/ undefined, pendingExpressions_1 ? ts.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
76865             variable.original = original;
76866             ts.setTextRange(variable, location);
76867             ts.aggregateTransformFlags(variable);
76868             declarations.push(variable);
76869         }
76870         return declarations;
76871         function emitExpression(value) {
76872             pendingExpressions = ts.append(pendingExpressions, value);
76873         }
76874         function emitBindingOrAssignment(target, value, location, original) {
76875             ts.Debug.assertNode(target, ts.isBindingName);
76876             if (pendingExpressions) {
76877                 value = ts.inlineExpressions(ts.append(pendingExpressions, value));
76878                 pendingExpressions = undefined;
76879             }
76880             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
76881         }
76882     }
76883     ts.flattenDestructuringBinding = flattenDestructuringBinding;
76884     /**
76885      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
76886      *
76887      * @param flattenContext Options used to control flattening.
76888      * @param element The element to flatten.
76889      * @param value The current RHS value to assign to the element.
76890      * @param location The location to use for source maps and comments.
76891      * @param skipInitializer An optional value indicating whether to include the initializer
76892      * for the element.
76893      */
76894     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
76895         if (!skipInitializer) {
76896             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
76897             if (initializer) {
76898                 // Combine value and initializer
76899                 value = value ? createDefaultValueCheck(flattenContext, value, initializer, location) : initializer;
76900             }
76901             else if (!value) {
76902                 // Use 'void 0' in absence of value and initializer
76903                 value = ts.createVoidZero();
76904             }
76905         }
76906         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
76907         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
76908             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76909         }
76910         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
76911             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
76912         }
76913         else {
76914             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
76915         }
76916     }
76917     /**
76918      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
76919      *
76920      * @param flattenContext Options used to control flattening.
76921      * @param parent The parent element of the pattern.
76922      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
76923      * @param value The current RHS value to assign to the element.
76924      * @param location The location to use for source maps and comments.
76925      */
76926     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76927         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76928         var numElements = elements.length;
76929         if (numElements !== 1) {
76930             // For anything other than a single-element destructuring we need to generate a temporary
76931             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76932             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
76933             // so in that case, we'll intentionally create that temporary.
76934             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
76935             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
76936         }
76937         var bindingElements;
76938         var computedTempVariables;
76939         for (var i = 0; i < numElements; i++) {
76940             var element = elements[i];
76941             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
76942                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
76943                 if (flattenContext.level >= 1 /* ObjectRest */
76944                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76945                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
76946                     && !ts.isComputedPropertyName(propertyName)) {
76947                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
76948                 }
76949                 else {
76950                     if (bindingElements) {
76951                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76952                         bindingElements = undefined;
76953                     }
76954                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
76955                     if (ts.isComputedPropertyName(propertyName)) {
76956                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
76957                     }
76958                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
76959                 }
76960             }
76961             else if (i === numElements - 1) {
76962                 if (bindingElements) {
76963                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76964                     bindingElements = undefined;
76965                 }
76966                 var rhsValue = createRestCall(flattenContext.context, value, elements, computedTempVariables, pattern); // TODO: GH#18217
76967                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
76968             }
76969         }
76970         if (bindingElements) {
76971             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
76972         }
76973     }
76974     /**
76975      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
76976      *
76977      * @param flattenContext Options used to control flattening.
76978      * @param parent The parent element of the pattern.
76979      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
76980      * @param value The current RHS value to assign to the element.
76981      * @param location The location to use for source maps and comments.
76982      */
76983     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
76984         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
76985         var numElements = elements.length;
76986         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
76987             // Read the elements of the iterable into an array
76988             value = ensureIdentifier(flattenContext, ts.createReadHelper(flattenContext.context, value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
76989                 ? undefined
76990                 : numElements, location), 
76991             /*reuseIdentifierExpressions*/ false, location);
76992         }
76993         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
76994             || ts.every(elements, ts.isOmittedExpression)) {
76995             // For anything other than a single-element destructuring we need to generate a temporary
76996             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
76997             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
76998             // so in that case, we'll intentionally create that temporary.
76999             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
77000             // then we will create temporary variable.
77001             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
77002             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
77003         }
77004         var bindingElements;
77005         var restContainingElements;
77006         for (var i = 0; i < numElements; i++) {
77007             var element = elements[i];
77008             if (flattenContext.level >= 1 /* ObjectRest */) {
77009                 // If an array pattern contains an ObjectRest, we must cache the result so that we
77010                 // can perform the ObjectRest destructuring in a different declaration
77011                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
77012                     var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77013                     if (flattenContext.hoistTempVariables) {
77014                         flattenContext.context.hoistVariableDeclaration(temp);
77015                     }
77016                     restContainingElements = ts.append(restContainingElements, [temp, element]);
77017                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
77018                 }
77019                 else {
77020                     bindingElements = ts.append(bindingElements, element);
77021                 }
77022             }
77023             else if (ts.isOmittedExpression(element)) {
77024                 continue;
77025             }
77026             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
77027                 var rhsValue = ts.createElementAccess(value, i);
77028                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77029             }
77030             else if (i === numElements - 1) {
77031                 var rhsValue = ts.createArraySlice(value, i);
77032                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
77033             }
77034         }
77035         if (bindingElements) {
77036             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
77037         }
77038         if (restContainingElements) {
77039             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
77040                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
77041                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
77042             }
77043         }
77044     }
77045     /**
77046      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
77047      *
77048      * @param flattenContext Options used to control flattening.
77049      * @param value The RHS value to test.
77050      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
77051      * @param location The location to use for source maps and comments.
77052      */
77053     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
77054         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
77055         return ts.createConditional(ts.createTypeCheck(value, "undefined"), defaultValue, value);
77056     }
77057     /**
77058      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
77059      * right-hand side of a transformed destructuring assignment.
77060      *
77061      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
77062      *
77063      * @param flattenContext Options used to control flattening.
77064      * @param value The RHS value that is the source of the property.
77065      * @param propertyName The destructuring property name.
77066      */
77067     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
77068         if (ts.isComputedPropertyName(propertyName)) {
77069             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
77070             return ts.createElementAccess(value, argumentExpression);
77071         }
77072         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
77073             var argumentExpression = ts.getSynthesizedClone(propertyName);
77074             argumentExpression.text = argumentExpression.text;
77075             return ts.createElementAccess(value, argumentExpression);
77076         }
77077         else {
77078             var name = ts.createIdentifier(ts.idText(propertyName));
77079             return ts.createPropertyAccess(value, name);
77080         }
77081     }
77082     /**
77083      * Ensures that there exists a declared identifier whose value holds the given expression.
77084      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
77085      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
77086      *
77087      * @param flattenContext Options used to control flattening.
77088      * @param value the expression whose value needs to be bound.
77089      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
77090      * false if it is necessary to always emit an identifier.
77091      * @param location The location to use for source maps and comments.
77092      */
77093     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
77094         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
77095             return value;
77096         }
77097         else {
77098             var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
77099             if (flattenContext.hoistTempVariables) {
77100                 flattenContext.context.hoistVariableDeclaration(temp);
77101                 flattenContext.emitExpression(ts.setTextRange(ts.createAssignment(temp, value), location));
77102             }
77103             else {
77104                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
77105             }
77106             return temp;
77107         }
77108     }
77109     function makeArrayBindingPattern(elements) {
77110         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
77111         return ts.createArrayBindingPattern(elements);
77112     }
77113     function makeArrayAssignmentPattern(elements) {
77114         return ts.createArrayLiteral(ts.map(elements, ts.convertToArrayAssignmentElement));
77115     }
77116     function makeObjectBindingPattern(elements) {
77117         ts.Debug.assertEachNode(elements, ts.isBindingElement);
77118         return ts.createObjectBindingPattern(elements);
77119     }
77120     function makeObjectAssignmentPattern(elements) {
77121         return ts.createObjectLiteral(ts.map(elements, ts.convertToObjectAssignmentElement));
77122     }
77123     function makeBindingElement(name) {
77124         return ts.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
77125     }
77126     function makeAssignmentElement(name) {
77127         return name;
77128     }
77129     ts.restHelper = {
77130         name: "typescript:rest",
77131         importName: "__rest",
77132         scoped: false,
77133         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            };"
77134     };
77135     /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
77136      * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
77137      */
77138     function createRestCall(context, value, elements, computedTempVariables, location) {
77139         context.requestEmitHelper(ts.restHelper);
77140         var propertyNames = [];
77141         var computedTempVariableOffset = 0;
77142         for (var i = 0; i < elements.length - 1; i++) {
77143             var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
77144             if (propertyName) {
77145                 if (ts.isComputedPropertyName(propertyName)) {
77146                     var temp = computedTempVariables[computedTempVariableOffset];
77147                     computedTempVariableOffset++;
77148                     // typeof _tmp === "symbol" ? _tmp : _tmp + ""
77149                     propertyNames.push(ts.createConditional(ts.createTypeCheck(temp, "symbol"), temp, ts.createAdd(temp, ts.createLiteral(""))));
77150                 }
77151                 else {
77152                     propertyNames.push(ts.createLiteral(propertyName));
77153                 }
77154             }
77155         }
77156         return ts.createCall(ts.getUnscopedHelperName("__rest"), 
77157         /*typeArguments*/ undefined, [
77158             value,
77159             ts.setTextRange(ts.createArrayLiteral(propertyNames), location)
77160         ]);
77161     }
77162 })(ts || (ts = {}));
77163 /*@internal*/
77164 var ts;
77165 (function (ts) {
77166     var ProcessLevel;
77167     (function (ProcessLevel) {
77168         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
77169         ProcessLevel[ProcessLevel["All"] = 1] = "All";
77170     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
77171     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
77172         // Visit the tag expression
77173         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
77174         // Build up the template arguments and the raw and cooked strings for the template.
77175         // We start out with 'undefined' for the first argument and revisit later
77176         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
77177         var templateArguments = [undefined];
77178         var cookedStrings = [];
77179         var rawStrings = [];
77180         var template = node.template;
77181         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template))
77182             return node;
77183         if (ts.isNoSubstitutionTemplateLiteral(template)) {
77184             cookedStrings.push(createTemplateCooked(template));
77185             rawStrings.push(getRawLiteral(template, currentSourceFile));
77186         }
77187         else {
77188             cookedStrings.push(createTemplateCooked(template.head));
77189             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
77190             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
77191                 var templateSpan = _a[_i];
77192                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
77193                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
77194                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
77195             }
77196         }
77197         var helperCall = createTemplateObjectHelper(context, ts.createArrayLiteral(cookedStrings), ts.createArrayLiteral(rawStrings));
77198         // Create a variable to cache the template object if we're in a module.
77199         // Do not do this in the global scope, as any variable we currently generate could conflict with
77200         // variables from outside of the current compilation. In the future, we can revisit this behavior.
77201         if (ts.isExternalModule(currentSourceFile)) {
77202             var tempVar = ts.createUniqueName("templateObject");
77203             recordTaggedTemplateString(tempVar);
77204             templateArguments[0] = ts.createLogicalOr(tempVar, ts.createAssignment(tempVar, helperCall));
77205         }
77206         else {
77207             templateArguments[0] = helperCall;
77208         }
77209         return ts.createCall(tag, /*typeArguments*/ undefined, templateArguments);
77210     }
77211     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
77212     function createTemplateCooked(template) {
77213         return template.templateFlags ? ts.createIdentifier("undefined") : ts.createLiteral(template.text);
77214     }
77215     /**
77216      * Creates an ES5 compatible literal from an ES6 template literal.
77217      *
77218      * @param node The ES6 template literal.
77219      */
77220     function getRawLiteral(node, currentSourceFile) {
77221         // Find original source text, since we need to emit the raw strings of the tagged template.
77222         // The raw strings contain the (escaped) strings of what the user wrote.
77223         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
77224         var text = node.rawText;
77225         if (text === undefined) {
77226             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
77227             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
77228             // thus we need to remove those characters.
77229             // First template piece starts with "`", others with "}"
77230             // Last template piece ends with "`", others with "${"
77231             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
77232             text = text.substring(1, text.length - (isLast ? 1 : 2));
77233         }
77234         // Newline normalization:
77235         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
77236         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
77237         text = text.replace(/\r\n?/g, "\n");
77238         return ts.setTextRange(ts.createLiteral(text), node);
77239     }
77240     function createTemplateObjectHelper(context, cooked, raw) {
77241         context.requestEmitHelper(ts.templateObjectHelper);
77242         return ts.createCall(ts.getUnscopedHelperName("__makeTemplateObject"), 
77243         /*typeArguments*/ undefined, [
77244             cooked,
77245             raw
77246         ]);
77247     }
77248     ts.templateObjectHelper = {
77249         name: "typescript:makeTemplateObject",
77250         importName: "__makeTemplateObject",
77251         scoped: false,
77252         priority: 0,
77253         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            };"
77254     };
77255 })(ts || (ts = {}));
77256 /*@internal*/
77257 var ts;
77258 (function (ts) {
77259     /**
77260      * Indicates whether to emit type metadata in the new format.
77261      */
77262     var USE_NEW_TYPE_METADATA_FORMAT = false;
77263     var TypeScriptSubstitutionFlags;
77264     (function (TypeScriptSubstitutionFlags) {
77265         /** Enables substitutions for decorated classes. */
77266         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
77267         /** Enables substitutions for namespace exports. */
77268         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
77269         /* Enables substitutions for unqualified enum members */
77270         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
77271     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
77272     var ClassFacts;
77273     (function (ClassFacts) {
77274         ClassFacts[ClassFacts["None"] = 0] = "None";
77275         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
77276         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
77277         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
77278         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
77279         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
77280         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
77281         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
77282         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
77283         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
77284         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
77285         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
77286         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
77287     })(ClassFacts || (ClassFacts = {}));
77288     function transformTypeScript(context) {
77289         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
77290         var resolver = context.getEmitResolver();
77291         var compilerOptions = context.getCompilerOptions();
77292         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
77293         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
77294         var moduleKind = ts.getEmitModuleKind(compilerOptions);
77295         // Save the previous transformation hooks.
77296         var previousOnEmitNode = context.onEmitNode;
77297         var previousOnSubstituteNode = context.onSubstituteNode;
77298         // Set new transformation hooks.
77299         context.onEmitNode = onEmitNode;
77300         context.onSubstituteNode = onSubstituteNode;
77301         // Enable substitution for property/element access to emit const enum values.
77302         context.enableSubstitution(194 /* PropertyAccessExpression */);
77303         context.enableSubstitution(195 /* ElementAccessExpression */);
77304         // These variables contain state that changes as we descend into the tree.
77305         var currentSourceFile;
77306         var currentNamespace;
77307         var currentNamespaceContainerName;
77308         var currentLexicalScope;
77309         var currentNameScope;
77310         var currentScopeFirstDeclarationsOfName;
77311         var currentClassHasParameterProperties;
77312         /**
77313          * Keeps track of whether expression substitution has been enabled for specific edge cases.
77314          * They are persisted between each SourceFile transformation and should not be reset.
77315          */
77316         var enabledSubstitutions;
77317         /**
77318          * A map that keeps track of aliases created for classes with decorators to avoid issues
77319          * with the double-binding behavior of classes.
77320          */
77321         var classAliases;
77322         /**
77323          * Keeps track of whether we are within any containing namespaces when performing
77324          * just-in-time substitution while printing an expression identifier.
77325          */
77326         var applicableSubstitutions;
77327         return transformSourceFileOrBundle;
77328         function transformSourceFileOrBundle(node) {
77329             if (node.kind === 291 /* Bundle */) {
77330                 return transformBundle(node);
77331             }
77332             return transformSourceFile(node);
77333         }
77334         function transformBundle(node) {
77335             return ts.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
77336                 if (prepend.kind === 293 /* InputFiles */) {
77337                     return ts.createUnparsedSourceFile(prepend, "js");
77338                 }
77339                 return prepend;
77340             }));
77341         }
77342         /**
77343          * Transform TypeScript-specific syntax in a SourceFile.
77344          *
77345          * @param node A SourceFile node.
77346          */
77347         function transformSourceFile(node) {
77348             if (node.isDeclarationFile) {
77349                 return node;
77350             }
77351             currentSourceFile = node;
77352             var visited = saveStateAndInvoke(node, visitSourceFile);
77353             ts.addEmitHelpers(visited, context.readEmitHelpers());
77354             currentSourceFile = undefined;
77355             return visited;
77356         }
77357         /**
77358          * Visits a node, saving and restoring state variables on the stack.
77359          *
77360          * @param node The node to visit.
77361          */
77362         function saveStateAndInvoke(node, f) {
77363             // Save state
77364             var savedCurrentScope = currentLexicalScope;
77365             var savedCurrentNameScope = currentNameScope;
77366             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
77367             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
77368             // Handle state changes before visiting a node.
77369             onBeforeVisitNode(node);
77370             var visited = f(node);
77371             // Restore state
77372             if (currentLexicalScope !== savedCurrentScope) {
77373                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
77374             }
77375             currentLexicalScope = savedCurrentScope;
77376             currentNameScope = savedCurrentNameScope;
77377             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
77378             return visited;
77379         }
77380         /**
77381          * Performs actions that should always occur immediately before visiting a node.
77382          *
77383          * @param node The node to visit.
77384          */
77385         function onBeforeVisitNode(node) {
77386             switch (node.kind) {
77387                 case 290 /* SourceFile */:
77388                 case 251 /* CaseBlock */:
77389                 case 250 /* ModuleBlock */:
77390                 case 223 /* Block */:
77391                     currentLexicalScope = node;
77392                     currentNameScope = undefined;
77393                     currentScopeFirstDeclarationsOfName = undefined;
77394                     break;
77395                 case 245 /* ClassDeclaration */:
77396                 case 244 /* FunctionDeclaration */:
77397                     if (ts.hasModifier(node, 2 /* Ambient */)) {
77398                         break;
77399                     }
77400                     // Record these declarations provided that they have a name.
77401                     if (node.name) {
77402                         recordEmittedDeclarationInScope(node);
77403                     }
77404                     else {
77405                         // These nodes should always have names unless they are default-exports;
77406                         // however, class declaration parsing allows for undefined names, so syntactically invalid
77407                         // programs may also have an undefined name.
77408                         ts.Debug.assert(node.kind === 245 /* ClassDeclaration */ || ts.hasModifier(node, 512 /* Default */));
77409                     }
77410                     if (ts.isClassDeclaration(node)) {
77411                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
77412                         currentNameScope = node;
77413                     }
77414                     break;
77415             }
77416         }
77417         /**
77418          * General-purpose node visitor.
77419          *
77420          * @param node The node to visit.
77421          */
77422         function visitor(node) {
77423             return saveStateAndInvoke(node, visitorWorker);
77424         }
77425         /**
77426          * Visits and possibly transforms any node.
77427          *
77428          * @param node The node to visit.
77429          */
77430         function visitorWorker(node) {
77431             if (node.transformFlags & 1 /* ContainsTypeScript */) {
77432                 return visitTypeScript(node);
77433             }
77434             return node;
77435         }
77436         /**
77437          * Specialized visitor that visits the immediate children of a SourceFile.
77438          *
77439          * @param node The node to visit.
77440          */
77441         function sourceElementVisitor(node) {
77442             return saveStateAndInvoke(node, sourceElementVisitorWorker);
77443         }
77444         /**
77445          * Specialized visitor that visits the immediate children of a SourceFile.
77446          *
77447          * @param node The node to visit.
77448          */
77449         function sourceElementVisitorWorker(node) {
77450             switch (node.kind) {
77451                 case 254 /* ImportDeclaration */:
77452                 case 253 /* ImportEqualsDeclaration */:
77453                 case 259 /* ExportAssignment */:
77454                 case 260 /* ExportDeclaration */:
77455                     return visitEllidableStatement(node);
77456                 default:
77457                     return visitorWorker(node);
77458             }
77459         }
77460         function visitEllidableStatement(node) {
77461             var parsed = ts.getParseTreeNode(node);
77462             if (parsed !== node) {
77463                 // If the node has been transformed by a `before` transformer, perform no ellision on it
77464                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
77465                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
77466                 // and will trigger debug failures when debug verbosity is turned up
77467                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
77468                     // This node contains TypeScript, so we should visit its children.
77469                     return ts.visitEachChild(node, visitor, context);
77470                 }
77471                 // Otherwise, we can just return the node
77472                 return node;
77473             }
77474             switch (node.kind) {
77475                 case 254 /* ImportDeclaration */:
77476                     return visitImportDeclaration(node);
77477                 case 253 /* ImportEqualsDeclaration */:
77478                     return visitImportEqualsDeclaration(node);
77479                 case 259 /* ExportAssignment */:
77480                     return visitExportAssignment(node);
77481                 case 260 /* ExportDeclaration */:
77482                     return visitExportDeclaration(node);
77483                 default:
77484                     ts.Debug.fail("Unhandled ellided statement");
77485             }
77486         }
77487         /**
77488          * Specialized visitor that visits the immediate children of a namespace.
77489          *
77490          * @param node The node to visit.
77491          */
77492         function namespaceElementVisitor(node) {
77493             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
77494         }
77495         /**
77496          * Specialized visitor that visits the immediate children of a namespace.
77497          *
77498          * @param node The node to visit.
77499          */
77500         function namespaceElementVisitorWorker(node) {
77501             if (node.kind === 260 /* ExportDeclaration */ ||
77502                 node.kind === 254 /* ImportDeclaration */ ||
77503                 node.kind === 255 /* ImportClause */ ||
77504                 (node.kind === 253 /* ImportEqualsDeclaration */ &&
77505                     node.moduleReference.kind === 265 /* ExternalModuleReference */)) {
77506                 // do not emit ES6 imports and exports since they are illegal inside a namespace
77507                 return undefined;
77508             }
77509             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasModifier(node, 1 /* Export */)) {
77510                 return visitTypeScript(node);
77511             }
77512             return node;
77513         }
77514         /**
77515          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77516          *
77517          * @param node The node to visit.
77518          */
77519         function classElementVisitor(node) {
77520             return saveStateAndInvoke(node, classElementVisitorWorker);
77521         }
77522         /**
77523          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
77524          *
77525          * @param node The node to visit.
77526          */
77527         function classElementVisitorWorker(node) {
77528             switch (node.kind) {
77529                 case 162 /* Constructor */:
77530                     return visitConstructor(node);
77531                 case 159 /* PropertyDeclaration */:
77532                     // Property declarations are not TypeScript syntax, but they must be visited
77533                     // for the decorator transformation.
77534                     return visitPropertyDeclaration(node);
77535                 case 167 /* IndexSignature */:
77536                 case 163 /* GetAccessor */:
77537                 case 164 /* SetAccessor */:
77538                 case 161 /* MethodDeclaration */:
77539                     // Fallback to the default visit behavior.
77540                     return visitorWorker(node);
77541                 case 222 /* SemicolonClassElement */:
77542                     return node;
77543                 default:
77544                     return ts.Debug.failBadSyntaxKind(node);
77545             }
77546         }
77547         function modifierVisitor(node) {
77548             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
77549                 return undefined;
77550             }
77551             else if (currentNamespace && node.kind === 89 /* ExportKeyword */) {
77552                 return undefined;
77553             }
77554             return node;
77555         }
77556         /**
77557          * Branching visitor, visits a TypeScript syntax node.
77558          *
77559          * @param node The node to visit.
77560          */
77561         function visitTypeScript(node) {
77562             if (ts.isStatement(node) && ts.hasModifier(node, 2 /* Ambient */)) {
77563                 // TypeScript ambient declarations are elided, but some comments may be preserved.
77564                 // See the implementation of `getLeadingComments` in comments.ts for more details.
77565                 return ts.createNotEmittedStatement(node);
77566             }
77567             switch (node.kind) {
77568                 case 89 /* ExportKeyword */:
77569                 case 84 /* DefaultKeyword */:
77570                     // ES6 export and default modifiers are elided when inside a namespace.
77571                     return currentNamespace ? undefined : node;
77572                 case 119 /* PublicKeyword */:
77573                 case 117 /* PrivateKeyword */:
77574                 case 118 /* ProtectedKeyword */:
77575                 case 122 /* AbstractKeyword */:
77576                 case 81 /* ConstKeyword */:
77577                 case 130 /* DeclareKeyword */:
77578                 case 138 /* ReadonlyKeyword */:
77579                 // TypeScript accessibility and readonly modifiers are elided
77580                 // falls through
77581                 case 174 /* ArrayType */:
77582                 case 175 /* TupleType */:
77583                 case 176 /* OptionalType */:
77584                 case 177 /* RestType */:
77585                 case 173 /* TypeLiteral */:
77586                 case 168 /* TypePredicate */:
77587                 case 155 /* TypeParameter */:
77588                 case 125 /* AnyKeyword */:
77589                 case 148 /* UnknownKeyword */:
77590                 case 128 /* BooleanKeyword */:
77591                 case 143 /* StringKeyword */:
77592                 case 140 /* NumberKeyword */:
77593                 case 137 /* NeverKeyword */:
77594                 case 110 /* VoidKeyword */:
77595                 case 144 /* SymbolKeyword */:
77596                 case 171 /* ConstructorType */:
77597                 case 170 /* FunctionType */:
77598                 case 172 /* TypeQuery */:
77599                 case 169 /* TypeReference */:
77600                 case 178 /* UnionType */:
77601                 case 179 /* IntersectionType */:
77602                 case 180 /* ConditionalType */:
77603                 case 182 /* ParenthesizedType */:
77604                 case 183 /* ThisType */:
77605                 case 184 /* TypeOperator */:
77606                 case 185 /* IndexedAccessType */:
77607                 case 186 /* MappedType */:
77608                 case 187 /* LiteralType */:
77609                 // TypeScript type nodes are elided.
77610                 // falls through
77611                 case 167 /* IndexSignature */:
77612                 // TypeScript index signatures are elided.
77613                 // falls through
77614                 case 157 /* Decorator */:
77615                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
77616                 // falls through
77617                 case 247 /* TypeAliasDeclaration */:
77618                     // TypeScript type-only declarations are elided.
77619                     return undefined;
77620                 case 159 /* PropertyDeclaration */:
77621                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
77622                     return visitPropertyDeclaration(node);
77623                 case 252 /* NamespaceExportDeclaration */:
77624                     // TypeScript namespace export declarations are elided.
77625                     return undefined;
77626                 case 162 /* Constructor */:
77627                     return visitConstructor(node);
77628                 case 246 /* InterfaceDeclaration */:
77629                     // TypeScript interfaces are elided, but some comments may be preserved.
77630                     // See the implementation of `getLeadingComments` in comments.ts for more details.
77631                     return ts.createNotEmittedStatement(node);
77632                 case 245 /* ClassDeclaration */:
77633                     // This may be a class declaration with TypeScript syntax extensions.
77634                     //
77635                     // TypeScript class syntax extensions include:
77636                     // - decorators
77637                     // - optional `implements` heritage clause
77638                     // - parameter property assignments in the constructor
77639                     // - index signatures
77640                     // - method overload signatures
77641                     return visitClassDeclaration(node);
77642                 case 214 /* ClassExpression */:
77643                     // This may be a class expression with TypeScript syntax extensions.
77644                     //
77645                     // TypeScript class syntax extensions include:
77646                     // - decorators
77647                     // - optional `implements` heritage clause
77648                     // - parameter property assignments in the constructor
77649                     // - index signatures
77650                     // - method overload signatures
77651                     return visitClassExpression(node);
77652                 case 279 /* HeritageClause */:
77653                     // This may be a heritage clause with TypeScript syntax extensions.
77654                     //
77655                     // TypeScript heritage clause extensions include:
77656                     // - `implements` clause
77657                     return visitHeritageClause(node);
77658                 case 216 /* ExpressionWithTypeArguments */:
77659                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
77660                     return visitExpressionWithTypeArguments(node);
77661                 case 161 /* MethodDeclaration */:
77662                     // TypeScript method declarations may have decorators, modifiers
77663                     // or type annotations.
77664                     return visitMethodDeclaration(node);
77665                 case 163 /* GetAccessor */:
77666                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
77667                     return visitGetAccessor(node);
77668                 case 164 /* SetAccessor */:
77669                     // Set Accessors can have TypeScript modifiers and type annotations.
77670                     return visitSetAccessor(node);
77671                 case 244 /* FunctionDeclaration */:
77672                     // Typescript function declarations can have modifiers, decorators, and type annotations.
77673                     return visitFunctionDeclaration(node);
77674                 case 201 /* FunctionExpression */:
77675                     // TypeScript function expressions can have modifiers and type annotations.
77676                     return visitFunctionExpression(node);
77677                 case 202 /* ArrowFunction */:
77678                     // TypeScript arrow functions can have modifiers and type annotations.
77679                     return visitArrowFunction(node);
77680                 case 156 /* Parameter */:
77681                     // This may be a parameter declaration with TypeScript syntax extensions.
77682                     //
77683                     // TypeScript parameter declaration syntax extensions include:
77684                     // - decorators
77685                     // - accessibility modifiers
77686                     // - the question mark (?) token for optional parameters
77687                     // - type annotations
77688                     // - this parameters
77689                     return visitParameter(node);
77690                 case 200 /* ParenthesizedExpression */:
77691                     // ParenthesizedExpressions are TypeScript if their expression is a
77692                     // TypeAssertion or AsExpression
77693                     return visitParenthesizedExpression(node);
77694                 case 199 /* TypeAssertionExpression */:
77695                 case 217 /* AsExpression */:
77696                     // TypeScript type assertions are removed, but their subtrees are preserved.
77697                     return visitAssertionExpression(node);
77698                 case 196 /* CallExpression */:
77699                     return visitCallExpression(node);
77700                 case 197 /* NewExpression */:
77701                     return visitNewExpression(node);
77702                 case 198 /* TaggedTemplateExpression */:
77703                     return visitTaggedTemplateExpression(node);
77704                 case 218 /* NonNullExpression */:
77705                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
77706                     return visitNonNullExpression(node);
77707                 case 248 /* EnumDeclaration */:
77708                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
77709                     return visitEnumDeclaration(node);
77710                 case 225 /* VariableStatement */:
77711                     // TypeScript namespace exports for variable statements must be transformed.
77712                     return visitVariableStatement(node);
77713                 case 242 /* VariableDeclaration */:
77714                     return visitVariableDeclaration(node);
77715                 case 249 /* ModuleDeclaration */:
77716                     // TypeScript namespace declarations must be transformed.
77717                     return visitModuleDeclaration(node);
77718                 case 253 /* ImportEqualsDeclaration */:
77719                     // TypeScript namespace or external module import.
77720                     return visitImportEqualsDeclaration(node);
77721                 case 267 /* JsxSelfClosingElement */:
77722                     return visitJsxSelfClosingElement(node);
77723                 case 268 /* JsxOpeningElement */:
77724                     return visitJsxJsxOpeningElement(node);
77725                 default:
77726                     // node contains some other TypeScript syntax
77727                     return ts.visitEachChild(node, visitor, context);
77728             }
77729         }
77730         function visitSourceFile(node) {
77731             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
77732                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
77733                 !ts.isJsonSourceFile(node);
77734             return ts.updateSourceFileNode(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
77735         }
77736         /**
77737          * Tests whether we should emit a __decorate call for a class declaration.
77738          */
77739         function shouldEmitDecorateCallForClass(node) {
77740             if (node.decorators && node.decorators.length > 0) {
77741                 return true;
77742             }
77743             var constructor = ts.getFirstConstructorWithBody(node);
77744             if (constructor) {
77745                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
77746             }
77747             return false;
77748         }
77749         /**
77750          * Tests whether we should emit a __decorate call for a parameter declaration.
77751          */
77752         function shouldEmitDecorateCallForParameter(parameter) {
77753             return parameter.decorators !== undefined && parameter.decorators.length > 0;
77754         }
77755         function getClassFacts(node, staticProperties) {
77756             var facts = 0 /* None */;
77757             if (ts.some(staticProperties))
77758                 facts |= 1 /* HasStaticInitializedProperties */;
77759             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
77760             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */)
77761                 facts |= 64 /* IsDerivedClass */;
77762             if (shouldEmitDecorateCallForClass(node))
77763                 facts |= 2 /* HasConstructorDecorators */;
77764             if (ts.childIsDecorated(node))
77765                 facts |= 4 /* HasMemberDecorators */;
77766             if (isExportOfNamespace(node))
77767                 facts |= 8 /* IsExportOfNamespace */;
77768             else if (isDefaultExternalModuleExport(node))
77769                 facts |= 32 /* IsDefaultExternalExport */;
77770             else if (isNamedExternalModuleExport(node))
77771                 facts |= 16 /* IsNamedExternalExport */;
77772             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
77773                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
77774             return facts;
77775         }
77776         function hasTypeScriptClassSyntax(node) {
77777             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
77778         }
77779         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
77780             return ts.some(node.decorators)
77781                 || ts.some(node.typeParameters)
77782                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
77783                 || ts.some(node.members, hasTypeScriptClassSyntax);
77784         }
77785         function visitClassDeclaration(node) {
77786             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasModifier(node, 1 /* Export */))) {
77787                 return ts.visitEachChild(node, visitor, context);
77788             }
77789             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
77790             var facts = getClassFacts(node, staticProperties);
77791             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77792                 context.startLexicalEnvironment();
77793             }
77794             var name = node.name || (facts & 5 /* NeedsName */ ? ts.getGeneratedNameForNode(node) : undefined);
77795             var classStatement = facts & 2 /* HasConstructorDecorators */
77796                 ? createClassDeclarationHeadWithDecorators(node, name)
77797                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
77798             var statements = [classStatement];
77799             // Write any decorators of the node.
77800             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
77801             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
77802             addConstructorDecorationStatement(statements, node);
77803             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
77804                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
77805                 // 'es2015' transformer can properly nest static initializers and decorators. The result
77806                 // looks something like:
77807                 //
77808                 //  var C = function () {
77809                 //      class C {
77810                 //      }
77811                 //      C.static_prop = 1;
77812                 //      return C;
77813                 //  }();
77814                 //
77815                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
77816                 var localName = ts.getInternalName(node);
77817                 // The following partially-emitted expression exists purely to align our sourcemap
77818                 // emit with the original emitter.
77819                 var outer = ts.createPartiallyEmittedExpression(localName);
77820                 outer.end = closingBraceLocation.end;
77821                 ts.setEmitFlags(outer, 1536 /* NoComments */);
77822                 var statement = ts.createReturn(outer);
77823                 statement.pos = closingBraceLocation.pos;
77824                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
77825                 statements.push(statement);
77826                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
77827                 var iife = ts.createImmediatelyInvokedArrowFunction(statements);
77828                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
77829                 var varStatement = ts.createVariableStatement(
77830                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
77831                     ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
77832                     /*type*/ undefined, iife)
77833                 ]));
77834                 ts.setOriginalNode(varStatement, node);
77835                 ts.setCommentRange(varStatement, node);
77836                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
77837                 ts.startOnNewLine(varStatement);
77838                 statements = [varStatement];
77839             }
77840             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
77841             // Otherwise, if the class was exported at the top level and was decorated, emit an export
77842             // declaration or export default for the class.
77843             if (facts & 8 /* IsExportOfNamespace */) {
77844                 addExportMemberAssignment(statements, node);
77845             }
77846             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
77847                 if (facts & 32 /* IsDefaultExternalExport */) {
77848                     statements.push(ts.createExportDefault(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77849                 }
77850                 else if (facts & 16 /* IsNamedExternalExport */) {
77851                     statements.push(ts.createExternalModuleExport(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
77852                 }
77853             }
77854             if (statements.length > 1) {
77855                 // Add a DeclarationMarker as a marker for the end of the declaration
77856                 statements.push(ts.createEndOfDeclarationMarker(node));
77857                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
77858             }
77859             return ts.singleOrMany(statements);
77860         }
77861         /**
77862          * Transforms a non-decorated class declaration and appends the resulting statements.
77863          *
77864          * @param node A ClassDeclaration node.
77865          * @param name The name of the class.
77866          * @param facts Precomputed facts about the class.
77867          */
77868         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
77869             //  ${modifiers} class ${name} ${heritageClauses} {
77870             //      ${members}
77871             //  }
77872             // we do not emit modifiers on the declaration if we are emitting an IIFE
77873             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
77874                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
77875                 : undefined;
77876             var classDeclaration = ts.createClassDeclaration(
77877             /*decorators*/ undefined, modifiers, name, 
77878             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
77879             // To better align with the old emitter, we should not emit a trailing source map
77880             // entry if the class has static properties.
77881             var emitFlags = ts.getEmitFlags(node);
77882             if (facts & 1 /* HasStaticInitializedProperties */) {
77883                 emitFlags |= 32 /* NoTrailingSourceMap */;
77884             }
77885             ts.aggregateTransformFlags(classDeclaration);
77886             ts.setTextRange(classDeclaration, node);
77887             ts.setOriginalNode(classDeclaration, node);
77888             ts.setEmitFlags(classDeclaration, emitFlags);
77889             return classDeclaration;
77890         }
77891         /**
77892          * Transforms a decorated class declaration and appends the resulting statements. If
77893          * the class requires an alias to avoid issues with double-binding, the alias is returned.
77894          */
77895         function createClassDeclarationHeadWithDecorators(node, name) {
77896             // When we emit an ES6 class that has a class decorator, we must tailor the
77897             // emit to certain specific cases.
77898             //
77899             // In the simplest case, we emit the class declaration as a let declaration, and
77900             // evaluate decorators after the close of the class body:
77901             //
77902             //  [Example 1]
77903             //  ---------------------------------------------------------------------
77904             //  TypeScript                      | Javascript
77905             //  ---------------------------------------------------------------------
77906             //  @dec                            | let C = class C {
77907             //  class C {                       | }
77908             //  }                               | C = __decorate([dec], C);
77909             //  ---------------------------------------------------------------------
77910             //  @dec                            | let C = class C {
77911             //  export class C {                | }
77912             //  }                               | C = __decorate([dec], C);
77913             //                                  | export { C };
77914             //  ---------------------------------------------------------------------
77915             //
77916             // If a class declaration contains a reference to itself *inside* of the class body,
77917             // this introduces two bindings to the class: One outside of the class body, and one
77918             // inside of the class body. If we apply decorators as in [Example 1] above, there
77919             // is the possibility that the decorator `dec` will return a new value for the
77920             // constructor, which would result in the binding inside of the class no longer
77921             // pointing to the same reference as the binding outside of the class.
77922             //
77923             // As a result, we must instead rewrite all references to the class *inside* of the
77924             // class body to instead point to a local temporary alias for the class:
77925             //
77926             //  [Example 2]
77927             //  ---------------------------------------------------------------------
77928             //  TypeScript                      | Javascript
77929             //  ---------------------------------------------------------------------
77930             //  @dec                            | let C = C_1 = class C {
77931             //  class C {                       |   static x() { return C_1.y; }
77932             //    static x() { return C.y; }    | }
77933             //    static y = 1;                 | C.y = 1;
77934             //  }                               | C = C_1 = __decorate([dec], C);
77935             //                                  | var C_1;
77936             //  ---------------------------------------------------------------------
77937             //  @dec                            | let C = class C {
77938             //  export class C {                |   static x() { return C_1.y; }
77939             //    static x() { return C.y; }    | }
77940             //    static y = 1;                 | C.y = 1;
77941             //  }                               | C = C_1 = __decorate([dec], C);
77942             //                                  | export { C };
77943             //                                  | var C_1;
77944             //  ---------------------------------------------------------------------
77945             //
77946             // If a class declaration is the default export of a module, we instead emit
77947             // the export after the decorated declaration:
77948             //
77949             //  [Example 3]
77950             //  ---------------------------------------------------------------------
77951             //  TypeScript                      | Javascript
77952             //  ---------------------------------------------------------------------
77953             //  @dec                            | let default_1 = class {
77954             //  export default class {          | }
77955             //  }                               | default_1 = __decorate([dec], default_1);
77956             //                                  | export default default_1;
77957             //  ---------------------------------------------------------------------
77958             //  @dec                            | let C = class C {
77959             //  export default class C {        | }
77960             //  }                               | C = __decorate([dec], C);
77961             //                                  | export default C;
77962             //  ---------------------------------------------------------------------
77963             //
77964             // If the class declaration is the default export and a reference to itself
77965             // inside of the class body, we must emit both an alias for the class *and*
77966             // move the export after the declaration:
77967             //
77968             //  [Example 4]
77969             //  ---------------------------------------------------------------------
77970             //  TypeScript                      | Javascript
77971             //  ---------------------------------------------------------------------
77972             //  @dec                            | let C = class C {
77973             //  export default class C {        |   static x() { return C_1.y; }
77974             //    static x() { return C.y; }    | }
77975             //    static y = 1;                 | C.y = 1;
77976             //  }                               | C = C_1 = __decorate([dec], C);
77977             //                                  | export default C;
77978             //                                  | var C_1;
77979             //  ---------------------------------------------------------------------
77980             //
77981             var location = ts.moveRangePastDecorators(node);
77982             var classAlias = getClassAliasIfNeeded(node);
77983             var declName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
77984             //  ... = class ${name} ${heritageClauses} {
77985             //      ${members}
77986             //  }
77987             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
77988             var members = transformClassMembers(node);
77989             var classExpression = ts.createClassExpression(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
77990             ts.aggregateTransformFlags(classExpression);
77991             ts.setOriginalNode(classExpression, node);
77992             ts.setTextRange(classExpression, location);
77993             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
77994             //                                         or decoratedClassAlias if the class contain self-reference.
77995             var statement = ts.createVariableStatement(
77996             /*modifiers*/ undefined, ts.createVariableDeclarationList([
77997                 ts.createVariableDeclaration(declName, 
77998                 /*type*/ undefined, classAlias ? ts.createAssignment(classAlias, classExpression) : classExpression)
77999             ], 1 /* Let */));
78000             ts.setOriginalNode(statement, node);
78001             ts.setTextRange(statement, location);
78002             ts.setCommentRange(statement, node);
78003             return statement;
78004         }
78005         function visitClassExpression(node) {
78006             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
78007                 return ts.visitEachChild(node, visitor, context);
78008             }
78009             var classExpression = ts.createClassExpression(
78010             /*modifiers*/ undefined, node.name, 
78011             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
78012             ts.aggregateTransformFlags(classExpression);
78013             ts.setOriginalNode(classExpression, node);
78014             ts.setTextRange(classExpression, node);
78015             return classExpression;
78016         }
78017         /**
78018          * Transforms the members of a class.
78019          *
78020          * @param node The current class.
78021          */
78022         function transformClassMembers(node) {
78023             var members = [];
78024             var constructor = ts.getFirstConstructorWithBody(node);
78025             var parametersWithPropertyAssignments = constructor &&
78026                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78027             if (parametersWithPropertyAssignments) {
78028                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
78029                     var parameter = parametersWithPropertyAssignments_1[_i];
78030                     if (ts.isIdentifier(parameter.name)) {
78031                         members.push(ts.setOriginalNode(ts.aggregateTransformFlags(ts.createProperty(
78032                         /*decorators*/ undefined, 
78033                         /*modifiers*/ undefined, parameter.name, 
78034                         /*questionOrExclamationToken*/ undefined, 
78035                         /*type*/ undefined, 
78036                         /*initializer*/ undefined)), parameter));
78037                     }
78038                 }
78039             }
78040             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
78041             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
78042         }
78043         /**
78044          * Gets either the static or instance members of a class that are decorated, or have
78045          * parameters that are decorated.
78046          *
78047          * @param node The class containing the member.
78048          * @param isStatic A value indicating whether to retrieve static or instance members of
78049          *                 the class.
78050          */
78051         function getDecoratedClassElements(node, isStatic) {
78052             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
78053         }
78054         /**
78055          * Determines whether a class member is a static member of a class that is decorated, or
78056          * has parameters that are decorated.
78057          *
78058          * @param member The class member.
78059          */
78060         function isStaticDecoratedClassElement(member, parent) {
78061             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
78062         }
78063         /**
78064          * Determines whether a class member is an instance member of a class that is decorated,
78065          * or has parameters that are decorated.
78066          *
78067          * @param member The class member.
78068          */
78069         function isInstanceDecoratedClassElement(member, parent) {
78070             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
78071         }
78072         /**
78073          * Determines whether a class member is either a static or an instance member of a class
78074          * that is decorated, or has parameters that are decorated.
78075          *
78076          * @param member The class member.
78077          */
78078         function isDecoratedClassElement(member, isStatic, parent) {
78079             return ts.nodeOrChildIsDecorated(member, parent)
78080                 && isStatic === ts.hasModifier(member, 32 /* Static */);
78081         }
78082         /**
78083          * Gets an array of arrays of decorators for the parameters of a function-like node.
78084          * The offset into the result array should correspond to the offset of the parameter.
78085          *
78086          * @param node The function-like node.
78087          */
78088         function getDecoratorsOfParameters(node) {
78089             var decorators;
78090             if (node) {
78091                 var parameters = node.parameters;
78092                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
78093                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
78094                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
78095                 for (var i = 0; i < numParameters; i++) {
78096                     var parameter = parameters[i + firstParameterOffset];
78097                     if (decorators || parameter.decorators) {
78098                         if (!decorators) {
78099                             decorators = new Array(numParameters);
78100                         }
78101                         decorators[i] = parameter.decorators;
78102                     }
78103                 }
78104             }
78105             return decorators;
78106         }
78107         /**
78108          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
78109          * parameters of the constructor of the class.
78110          *
78111          * @param node The class node.
78112          */
78113         function getAllDecoratorsOfConstructor(node) {
78114             var decorators = node.decorators;
78115             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
78116             if (!decorators && !parameters) {
78117                 return undefined;
78118             }
78119             return {
78120                 decorators: decorators,
78121                 parameters: parameters
78122             };
78123         }
78124         /**
78125          * Gets an AllDecorators object containing the decorators for the member and its parameters.
78126          *
78127          * @param node The class node that contains the member.
78128          * @param member The class member.
78129          */
78130         function getAllDecoratorsOfClassElement(node, member) {
78131             switch (member.kind) {
78132                 case 163 /* GetAccessor */:
78133                 case 164 /* SetAccessor */:
78134                     return getAllDecoratorsOfAccessors(node, member);
78135                 case 161 /* MethodDeclaration */:
78136                     return getAllDecoratorsOfMethod(member);
78137                 case 159 /* PropertyDeclaration */:
78138                     return getAllDecoratorsOfProperty(member);
78139                 default:
78140                     return undefined;
78141             }
78142         }
78143         /**
78144          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
78145          *
78146          * @param node The class node that contains the accessor.
78147          * @param accessor The class accessor member.
78148          */
78149         function getAllDecoratorsOfAccessors(node, accessor) {
78150             if (!accessor.body) {
78151                 return undefined;
78152             }
78153             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
78154             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
78155             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
78156                 return undefined;
78157             }
78158             var decorators = firstAccessorWithDecorators.decorators;
78159             var parameters = getDecoratorsOfParameters(setAccessor);
78160             if (!decorators && !parameters) {
78161                 return undefined;
78162             }
78163             return { decorators: decorators, parameters: parameters };
78164         }
78165         /**
78166          * Gets an AllDecorators object containing the decorators for the method and its parameters.
78167          *
78168          * @param method The class method member.
78169          */
78170         function getAllDecoratorsOfMethod(method) {
78171             if (!method.body) {
78172                 return undefined;
78173             }
78174             var decorators = method.decorators;
78175             var parameters = getDecoratorsOfParameters(method);
78176             if (!decorators && !parameters) {
78177                 return undefined;
78178             }
78179             return { decorators: decorators, parameters: parameters };
78180         }
78181         /**
78182          * Gets an AllDecorators object containing the decorators for the property.
78183          *
78184          * @param property The class property member.
78185          */
78186         function getAllDecoratorsOfProperty(property) {
78187             var decorators = property.decorators;
78188             if (!decorators) {
78189                 return undefined;
78190             }
78191             return { decorators: decorators };
78192         }
78193         /**
78194          * Transforms all of the decorators for a declaration into an array of expressions.
78195          *
78196          * @param node The declaration node.
78197          * @param allDecorators An object containing all of the decorators for the declaration.
78198          */
78199         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
78200             if (!allDecorators) {
78201                 return undefined;
78202             }
78203             var decoratorExpressions = [];
78204             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
78205             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
78206             addTypeMetadata(node, container, decoratorExpressions);
78207             return decoratorExpressions;
78208         }
78209         /**
78210          * Generates statements used to apply decorators to either the static or instance members
78211          * of a class.
78212          *
78213          * @param node The class node.
78214          * @param isStatic A value indicating whether to generate statements for static or
78215          *                 instance members.
78216          */
78217         function addClassElementDecorationStatements(statements, node, isStatic) {
78218             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
78219         }
78220         /**
78221          * Generates expressions used to apply decorators to either the static or instance members
78222          * of a class.
78223          *
78224          * @param node The class node.
78225          * @param isStatic A value indicating whether to generate expressions for static or
78226          *                 instance members.
78227          */
78228         function generateClassElementDecorationExpressions(node, isStatic) {
78229             var members = getDecoratedClassElements(node, isStatic);
78230             var expressions;
78231             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
78232                 var member = members_6[_i];
78233                 var expression = generateClassElementDecorationExpression(node, member);
78234                 if (expression) {
78235                     if (!expressions) {
78236                         expressions = [expression];
78237                     }
78238                     else {
78239                         expressions.push(expression);
78240                     }
78241                 }
78242             }
78243             return expressions;
78244         }
78245         /**
78246          * Generates an expression used to evaluate class element decorators at runtime.
78247          *
78248          * @param node The class node that contains the member.
78249          * @param member The class member.
78250          */
78251         function generateClassElementDecorationExpression(node, member) {
78252             var allDecorators = getAllDecoratorsOfClassElement(node, member);
78253             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
78254             if (!decoratorExpressions) {
78255                 return undefined;
78256             }
78257             // Emit the call to __decorate. Given the following:
78258             //
78259             //   class C {
78260             //     @dec method(@dec2 x) {}
78261             //     @dec get accessor() {}
78262             //     @dec prop;
78263             //   }
78264             //
78265             // The emit for a method is:
78266             //
78267             //   __decorate([
78268             //       dec,
78269             //       __param(0, dec2),
78270             //       __metadata("design:type", Function),
78271             //       __metadata("design:paramtypes", [Object]),
78272             //       __metadata("design:returntype", void 0)
78273             //   ], C.prototype, "method", null);
78274             //
78275             // The emit for an accessor is:
78276             //
78277             //   __decorate([
78278             //       dec
78279             //   ], C.prototype, "accessor", null);
78280             //
78281             // The emit for a property is:
78282             //
78283             //   __decorate([
78284             //       dec
78285             //   ], C.prototype, "prop");
78286             //
78287             var prefix = getClassMemberPrefix(node, member);
78288             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
78289             var descriptor = languageVersion > 0 /* ES3 */
78290                 ? member.kind === 159 /* PropertyDeclaration */
78291                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
78292                     // should not invoke `Object.getOwnPropertyDescriptor`.
78293                     ? ts.createVoidZero()
78294                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
78295                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
78296                     : ts.createNull()
78297                 : undefined;
78298             var helper = createDecorateHelper(context, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member));
78299             ts.setEmitFlags(helper, 1536 /* NoComments */);
78300             return helper;
78301         }
78302         /**
78303          * Generates a __decorate helper call for a class constructor.
78304          *
78305          * @param node The class node.
78306          */
78307         function addConstructorDecorationStatement(statements, node) {
78308             var expression = generateConstructorDecorationExpression(node);
78309             if (expression) {
78310                 statements.push(ts.setOriginalNode(ts.createExpressionStatement(expression), node));
78311             }
78312         }
78313         /**
78314          * Generates a __decorate helper call for a class constructor.
78315          *
78316          * @param node The class node.
78317          */
78318         function generateConstructorDecorationExpression(node) {
78319             var allDecorators = getAllDecoratorsOfConstructor(node);
78320             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
78321             if (!decoratorExpressions) {
78322                 return undefined;
78323             }
78324             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
78325             var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
78326             var decorate = createDecorateHelper(context, decoratorExpressions, localName);
78327             var expression = ts.createAssignment(localName, classAlias ? ts.createAssignment(classAlias, decorate) : decorate);
78328             ts.setEmitFlags(expression, 1536 /* NoComments */);
78329             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
78330             return expression;
78331         }
78332         /**
78333          * Transforms a decorator into an expression.
78334          *
78335          * @param decorator The decorator node.
78336          */
78337         function transformDecorator(decorator) {
78338             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
78339         }
78340         /**
78341          * Transforms the decorators of a parameter.
78342          *
78343          * @param decorators The decorators for the parameter at the provided offset.
78344          * @param parameterOffset The offset of the parameter.
78345          */
78346         function transformDecoratorsOfParameter(decorators, parameterOffset) {
78347             var expressions;
78348             if (decorators) {
78349                 expressions = [];
78350                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
78351                     var decorator = decorators_1[_i];
78352                     var helper = createParamHelper(context, transformDecorator(decorator), parameterOffset, 
78353                     /*location*/ decorator.expression);
78354                     ts.setEmitFlags(helper, 1536 /* NoComments */);
78355                     expressions.push(helper);
78356                 }
78357             }
78358             return expressions;
78359         }
78360         /**
78361          * Adds optional type metadata for a declaration.
78362          *
78363          * @param node The declaration node.
78364          * @param decoratorExpressions The destination array to which to add new decorator expressions.
78365          */
78366         function addTypeMetadata(node, container, decoratorExpressions) {
78367             if (USE_NEW_TYPE_METADATA_FORMAT) {
78368                 addNewTypeMetadata(node, container, decoratorExpressions);
78369             }
78370             else {
78371                 addOldTypeMetadata(node, container, decoratorExpressions);
78372             }
78373         }
78374         function addOldTypeMetadata(node, container, decoratorExpressions) {
78375             if (compilerOptions.emitDecoratorMetadata) {
78376                 if (shouldAddTypeMetadata(node)) {
78377                     decoratorExpressions.push(createMetadataHelper(context, "design:type", serializeTypeOfNode(node)));
78378                 }
78379                 if (shouldAddParamTypesMetadata(node)) {
78380                     decoratorExpressions.push(createMetadataHelper(context, "design:paramtypes", serializeParameterTypesOfNode(node, container)));
78381                 }
78382                 if (shouldAddReturnTypeMetadata(node)) {
78383                     decoratorExpressions.push(createMetadataHelper(context, "design:returntype", serializeReturnTypeOfNode(node)));
78384                 }
78385             }
78386         }
78387         function addNewTypeMetadata(node, container, decoratorExpressions) {
78388             if (compilerOptions.emitDecoratorMetadata) {
78389                 var properties = void 0;
78390                 if (shouldAddTypeMetadata(node)) {
78391                     (properties || (properties = [])).push(ts.createPropertyAssignment("type", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
78392                 }
78393                 if (shouldAddParamTypesMetadata(node)) {
78394                     (properties || (properties = [])).push(ts.createPropertyAssignment("paramTypes", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
78395                 }
78396                 if (shouldAddReturnTypeMetadata(node)) {
78397                     (properties || (properties = [])).push(ts.createPropertyAssignment("returnType", ts.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, ts.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
78398                 }
78399                 if (properties) {
78400                     decoratorExpressions.push(createMetadataHelper(context, "design:typeinfo", ts.createObjectLiteral(properties, /*multiLine*/ true)));
78401                 }
78402             }
78403         }
78404         /**
78405          * Determines whether to emit the "design:type" metadata based on the node's kind.
78406          * The caller should have already tested whether the node has decorators and whether the
78407          * emitDecoratorMetadata compiler option is set.
78408          *
78409          * @param node The node to test.
78410          */
78411         function shouldAddTypeMetadata(node) {
78412             var kind = node.kind;
78413             return kind === 161 /* MethodDeclaration */
78414                 || kind === 163 /* GetAccessor */
78415                 || kind === 164 /* SetAccessor */
78416                 || kind === 159 /* PropertyDeclaration */;
78417         }
78418         /**
78419          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
78420          * The caller should have already tested whether the node has decorators and whether the
78421          * emitDecoratorMetadata compiler option is set.
78422          *
78423          * @param node The node to test.
78424          */
78425         function shouldAddReturnTypeMetadata(node) {
78426             return node.kind === 161 /* MethodDeclaration */;
78427         }
78428         /**
78429          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
78430          * The caller should have already tested whether the node has decorators and whether the
78431          * emitDecoratorMetadata compiler option is set.
78432          *
78433          * @param node The node to test.
78434          */
78435         function shouldAddParamTypesMetadata(node) {
78436             switch (node.kind) {
78437                 case 245 /* ClassDeclaration */:
78438                 case 214 /* ClassExpression */:
78439                     return ts.getFirstConstructorWithBody(node) !== undefined;
78440                 case 161 /* MethodDeclaration */:
78441                 case 163 /* GetAccessor */:
78442                 case 164 /* SetAccessor */:
78443                     return true;
78444             }
78445             return false;
78446         }
78447         function getAccessorTypeNode(node) {
78448             var accessors = resolver.getAllAccessorDeclarations(node);
78449             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
78450                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
78451         }
78452         /**
78453          * Serializes the type of a node for use with decorator type metadata.
78454          *
78455          * @param node The node that should have its type serialized.
78456          */
78457         function serializeTypeOfNode(node) {
78458             switch (node.kind) {
78459                 case 159 /* PropertyDeclaration */:
78460                 case 156 /* Parameter */:
78461                     return serializeTypeNode(node.type);
78462                 case 164 /* SetAccessor */:
78463                 case 163 /* GetAccessor */:
78464                     return serializeTypeNode(getAccessorTypeNode(node));
78465                 case 245 /* ClassDeclaration */:
78466                 case 214 /* ClassExpression */:
78467                 case 161 /* MethodDeclaration */:
78468                     return ts.createIdentifier("Function");
78469                 default:
78470                     return ts.createVoidZero();
78471             }
78472         }
78473         /**
78474          * Serializes the types of the parameters of a node for use with decorator type metadata.
78475          *
78476          * @param node The node that should have its parameter types serialized.
78477          */
78478         function serializeParameterTypesOfNode(node, container) {
78479             var valueDeclaration = ts.isClassLike(node)
78480                 ? ts.getFirstConstructorWithBody(node)
78481                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
78482                     ? node
78483                     : undefined;
78484             var expressions = [];
78485             if (valueDeclaration) {
78486                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
78487                 var numParameters = parameters.length;
78488                 for (var i = 0; i < numParameters; i++) {
78489                     var parameter = parameters[i];
78490                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
78491                         continue;
78492                     }
78493                     if (parameter.dotDotDotToken) {
78494                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
78495                     }
78496                     else {
78497                         expressions.push(serializeTypeOfNode(parameter));
78498                     }
78499                 }
78500             }
78501             return ts.createArrayLiteral(expressions);
78502         }
78503         function getParametersOfDecoratedDeclaration(node, container) {
78504             if (container && node.kind === 163 /* GetAccessor */) {
78505                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
78506                 if (setAccessor) {
78507                     return setAccessor.parameters;
78508                 }
78509             }
78510             return node.parameters;
78511         }
78512         /**
78513          * Serializes the return type of a node for use with decorator type metadata.
78514          *
78515          * @param node The node that should have its return type serialized.
78516          */
78517         function serializeReturnTypeOfNode(node) {
78518             if (ts.isFunctionLike(node) && node.type) {
78519                 return serializeTypeNode(node.type);
78520             }
78521             else if (ts.isAsyncFunction(node)) {
78522                 return ts.createIdentifier("Promise");
78523             }
78524             return ts.createVoidZero();
78525         }
78526         /**
78527          * Serializes a type node for use with decorator type metadata.
78528          *
78529          * Types are serialized in the following fashion:
78530          * - Void types point to "undefined" (e.g. "void 0")
78531          * - Function and Constructor types point to the global "Function" constructor.
78532          * - Interface types with a call or construct signature types point to the global
78533          *   "Function" constructor.
78534          * - Array and Tuple types point to the global "Array" constructor.
78535          * - Type predicates and booleans point to the global "Boolean" constructor.
78536          * - String literal types and strings point to the global "String" constructor.
78537          * - Enum and number types point to the global "Number" constructor.
78538          * - Symbol types point to the global "Symbol" constructor.
78539          * - Type references to classes (or class-like variables) point to the constructor for the class.
78540          * - Anything else points to the global "Object" constructor.
78541          *
78542          * @param node The type node to serialize.
78543          */
78544         function serializeTypeNode(node) {
78545             if (node === undefined) {
78546                 return ts.createIdentifier("Object");
78547             }
78548             switch (node.kind) {
78549                 case 110 /* VoidKeyword */:
78550                 case 146 /* UndefinedKeyword */:
78551                 case 100 /* NullKeyword */:
78552                 case 137 /* NeverKeyword */:
78553                     return ts.createVoidZero();
78554                 case 182 /* ParenthesizedType */:
78555                     return serializeTypeNode(node.type);
78556                 case 170 /* FunctionType */:
78557                 case 171 /* ConstructorType */:
78558                     return ts.createIdentifier("Function");
78559                 case 174 /* ArrayType */:
78560                 case 175 /* TupleType */:
78561                     return ts.createIdentifier("Array");
78562                 case 168 /* TypePredicate */:
78563                 case 128 /* BooleanKeyword */:
78564                     return ts.createIdentifier("Boolean");
78565                 case 143 /* StringKeyword */:
78566                     return ts.createIdentifier("String");
78567                 case 141 /* ObjectKeyword */:
78568                     return ts.createIdentifier("Object");
78569                 case 187 /* LiteralType */:
78570                     switch (node.literal.kind) {
78571                         case 10 /* StringLiteral */:
78572                             return ts.createIdentifier("String");
78573                         case 207 /* PrefixUnaryExpression */:
78574                         case 8 /* NumericLiteral */:
78575                             return ts.createIdentifier("Number");
78576                         case 9 /* BigIntLiteral */:
78577                             return getGlobalBigIntNameWithFallback();
78578                         case 106 /* TrueKeyword */:
78579                         case 91 /* FalseKeyword */:
78580                             return ts.createIdentifier("Boolean");
78581                         default:
78582                             return ts.Debug.failBadSyntaxKind(node.literal);
78583                     }
78584                 case 140 /* NumberKeyword */:
78585                     return ts.createIdentifier("Number");
78586                 case 151 /* BigIntKeyword */:
78587                     return getGlobalBigIntNameWithFallback();
78588                 case 144 /* SymbolKeyword */:
78589                     return languageVersion < 2 /* ES2015 */
78590                         ? getGlobalSymbolNameWithFallback()
78591                         : ts.createIdentifier("Symbol");
78592                 case 169 /* TypeReference */:
78593                     return serializeTypeReferenceNode(node);
78594                 case 179 /* IntersectionType */:
78595                 case 178 /* UnionType */:
78596                     return serializeTypeList(node.types);
78597                 case 180 /* ConditionalType */:
78598                     return serializeTypeList([node.trueType, node.falseType]);
78599                 case 184 /* TypeOperator */:
78600                     if (node.operator === 138 /* ReadonlyKeyword */) {
78601                         return serializeTypeNode(node.type);
78602                     }
78603                     break;
78604                 case 172 /* TypeQuery */:
78605                 case 185 /* IndexedAccessType */:
78606                 case 186 /* MappedType */:
78607                 case 173 /* TypeLiteral */:
78608                 case 125 /* AnyKeyword */:
78609                 case 148 /* UnknownKeyword */:
78610                 case 183 /* ThisType */:
78611                 case 188 /* ImportType */:
78612                     break;
78613                 // handle JSDoc types from an invalid parse
78614                 case 295 /* JSDocAllType */:
78615                 case 296 /* JSDocUnknownType */:
78616                 case 300 /* JSDocFunctionType */:
78617                 case 301 /* JSDocVariadicType */:
78618                 case 302 /* JSDocNamepathType */:
78619                     break;
78620                 case 297 /* JSDocNullableType */:
78621                 case 298 /* JSDocNonNullableType */:
78622                 case 299 /* JSDocOptionalType */:
78623                     return serializeTypeNode(node.type);
78624                 default:
78625                     return ts.Debug.failBadSyntaxKind(node);
78626             }
78627             return ts.createIdentifier("Object");
78628         }
78629         function serializeTypeList(types) {
78630             // Note when updating logic here also update getEntityNameForDecoratorMetadata
78631             // so that aliases can be marked as referenced
78632             var serializedUnion;
78633             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
78634                 var typeNode = types_21[_i];
78635                 while (typeNode.kind === 182 /* ParenthesizedType */) {
78636                     typeNode = typeNode.type; // Skip parens if need be
78637                 }
78638                 if (typeNode.kind === 137 /* NeverKeyword */) {
78639                     continue; // Always elide `never` from the union/intersection if possible
78640                 }
78641                 if (!strictNullChecks && (typeNode.kind === 100 /* NullKeyword */ || typeNode.kind === 146 /* UndefinedKeyword */)) {
78642                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
78643                 }
78644                 var serializedIndividual = serializeTypeNode(typeNode);
78645                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
78646                     // One of the individual is global object, return immediately
78647                     return serializedIndividual;
78648                 }
78649                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
78650                 // anything more complex and we will just default to Object
78651                 else if (serializedUnion) {
78652                     // Different types
78653                     if (!ts.isIdentifier(serializedUnion) ||
78654                         !ts.isIdentifier(serializedIndividual) ||
78655                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
78656                         return ts.createIdentifier("Object");
78657                     }
78658                 }
78659                 else {
78660                     // Initialize the union type
78661                     serializedUnion = serializedIndividual;
78662                 }
78663             }
78664             // If we were able to find common type, use it
78665             return serializedUnion || ts.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
78666         }
78667         /**
78668          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
78669          * decorator type metadata.
78670          *
78671          * @param node The type reference node.
78672          */
78673         function serializeTypeReferenceNode(node) {
78674             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
78675             switch (kind) {
78676                 case ts.TypeReferenceSerializationKind.Unknown:
78677                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
78678                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
78679                         return ts.createIdentifier("Object");
78680                     }
78681                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
78682                     var temp = ts.createTempVariable(hoistVariableDeclaration);
78683                     return ts.createConditional(ts.createTypeCheck(ts.createAssignment(temp, serialized), "function"), temp, ts.createIdentifier("Object"));
78684                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
78685                     return serializeEntityNameAsExpression(node.typeName);
78686                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
78687                     return ts.createVoidZero();
78688                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
78689                     return getGlobalBigIntNameWithFallback();
78690                 case ts.TypeReferenceSerializationKind.BooleanType:
78691                     return ts.createIdentifier("Boolean");
78692                 case ts.TypeReferenceSerializationKind.NumberLikeType:
78693                     return ts.createIdentifier("Number");
78694                 case ts.TypeReferenceSerializationKind.StringLikeType:
78695                     return ts.createIdentifier("String");
78696                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
78697                     return ts.createIdentifier("Array");
78698                 case ts.TypeReferenceSerializationKind.ESSymbolType:
78699                     return languageVersion < 2 /* ES2015 */
78700                         ? getGlobalSymbolNameWithFallback()
78701                         : ts.createIdentifier("Symbol");
78702                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
78703                     return ts.createIdentifier("Function");
78704                 case ts.TypeReferenceSerializationKind.Promise:
78705                     return ts.createIdentifier("Promise");
78706                 case ts.TypeReferenceSerializationKind.ObjectType:
78707                     return ts.createIdentifier("Object");
78708                 default:
78709                     return ts.Debug.assertNever(kind);
78710             }
78711         }
78712         function createCheckedValue(left, right) {
78713             return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(left), ts.createLiteral("undefined")), right);
78714         }
78715         /**
78716          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
78717          *
78718          * @param node The entity name to serialize.
78719          */
78720         function serializeEntityNameAsExpressionFallback(node) {
78721             if (node.kind === 75 /* Identifier */) {
78722                 // A -> typeof A !== undefined && A
78723                 var copied = serializeEntityNameAsExpression(node);
78724                 return createCheckedValue(copied, copied);
78725             }
78726             if (node.left.kind === 75 /* Identifier */) {
78727                 // A.B -> typeof A !== undefined && A.B
78728                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
78729             }
78730             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
78731             var left = serializeEntityNameAsExpressionFallback(node.left);
78732             var temp = ts.createTempVariable(hoistVariableDeclaration);
78733             return ts.createLogicalAnd(ts.createLogicalAnd(left.left, ts.createStrictInequality(ts.createAssignment(temp, left.right), ts.createVoidZero())), ts.createPropertyAccess(temp, node.right));
78734         }
78735         /**
78736          * Serializes an entity name as an expression for decorator type metadata.
78737          *
78738          * @param node The entity name to serialize.
78739          */
78740         function serializeEntityNameAsExpression(node) {
78741             switch (node.kind) {
78742                 case 75 /* Identifier */:
78743                     // Create a clone of the name with a new parent, and treat it as if it were
78744                     // a source tree node for the purposes of the checker.
78745                     var name = ts.getMutableClone(node);
78746                     name.flags &= ~8 /* Synthesized */;
78747                     name.original = undefined;
78748                     name.parent = ts.getParseTreeNode(currentLexicalScope); // ensure the parent is set to a parse tree node.
78749                     return name;
78750                 case 153 /* QualifiedName */:
78751                     return serializeQualifiedNameAsExpression(node);
78752             }
78753         }
78754         /**
78755          * Serializes an qualified name as an expression for decorator type metadata.
78756          *
78757          * @param node The qualified name to serialize.
78758          * @param useFallback A value indicating whether to use logical operators to test for the
78759          *                    qualified name at runtime.
78760          */
78761         function serializeQualifiedNameAsExpression(node) {
78762             return ts.createPropertyAccess(serializeEntityNameAsExpression(node.left), node.right);
78763         }
78764         /**
78765          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
78766          * available.
78767          */
78768         function getGlobalSymbolNameWithFallback() {
78769             return ts.createConditional(ts.createTypeCheck(ts.createIdentifier("Symbol"), "function"), ts.createIdentifier("Symbol"), ts.createIdentifier("Object"));
78770         }
78771         /**
78772          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
78773          * available.
78774          */
78775         function getGlobalBigIntNameWithFallback() {
78776             return languageVersion < 99 /* ESNext */
78777                 ? ts.createConditional(ts.createTypeCheck(ts.createIdentifier("BigInt"), "function"), ts.createIdentifier("BigInt"), ts.createIdentifier("Object"))
78778                 : ts.createIdentifier("BigInt");
78779         }
78780         /**
78781          * Gets an expression that represents a property name (for decorated properties or enums).
78782          * For a computed property, a name is generated for the node.
78783          *
78784          * @param member The member whose name should be converted into an expression.
78785          */
78786         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
78787             var name = member.name;
78788             if (ts.isPrivateIdentifier(name)) {
78789                 return ts.createIdentifier("");
78790             }
78791             else if (ts.isComputedPropertyName(name)) {
78792                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
78793                     ? ts.getGeneratedNameForNode(name)
78794                     : name.expression;
78795             }
78796             else if (ts.isIdentifier(name)) {
78797                 return ts.createLiteral(ts.idText(name));
78798             }
78799             else {
78800                 return ts.getSynthesizedClone(name);
78801             }
78802         }
78803         /**
78804          * Visits the property name of a class element, for use when emitting property
78805          * initializers. For a computed property on a node with decorators, a temporary
78806          * value is stored for later use.
78807          *
78808          * @param member The member whose name should be visited.
78809          */
78810         function visitPropertyNameOfClassElement(member) {
78811             var name = member.name;
78812             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
78813             // The names are used more than once when:
78814             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
78815             //   - the property has a decorator.
78816             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
78817                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
78818                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
78819                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
78820                     var generatedName = ts.getGeneratedNameForNode(name);
78821                     hoistVariableDeclaration(generatedName);
78822                     return ts.updateComputedPropertyName(name, ts.createAssignment(generatedName, expression));
78823                 }
78824             }
78825             return ts.visitNode(name, visitor, ts.isPropertyName);
78826         }
78827         /**
78828          * Transforms a HeritageClause with TypeScript syntax.
78829          *
78830          * This function will only be called when one of the following conditions are met:
78831          * - The node is a non-`extends` heritage clause that should be elided.
78832          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
78833          *
78834          * @param node The HeritageClause to transform.
78835          */
78836         function visitHeritageClause(node) {
78837             if (node.token === 113 /* ImplementsKeyword */) {
78838                 // implements clauses are elided
78839                 return undefined;
78840             }
78841             return ts.visitEachChild(node, visitor, context);
78842         }
78843         /**
78844          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
78845          *
78846          * This function will only be called when one of the following conditions are met:
78847          * - The node contains type arguments that should be elided.
78848          *
78849          * @param node The ExpressionWithTypeArguments to transform.
78850          */
78851         function visitExpressionWithTypeArguments(node) {
78852             return ts.updateExpressionWithTypeArguments(node, 
78853             /*typeArguments*/ undefined, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
78854         }
78855         /**
78856          * Determines whether to emit a function-like declaration. We should not emit the
78857          * declaration if it does not have a body.
78858          *
78859          * @param node The declaration node.
78860          */
78861         function shouldEmitFunctionLikeDeclaration(node) {
78862             return !ts.nodeIsMissing(node.body);
78863         }
78864         function visitPropertyDeclaration(node) {
78865             if (node.flags & 8388608 /* Ambient */) {
78866                 return undefined;
78867             }
78868             var updated = ts.updateProperty(node, 
78869             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
78870             /*questionOrExclamationToken*/ undefined, 
78871             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
78872             if (updated !== node) {
78873                 // While we emit the source map for the node after skipping decorators and modifiers,
78874                 // we need to emit the comments for the original range.
78875                 ts.setCommentRange(updated, node);
78876                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78877             }
78878             return updated;
78879         }
78880         function visitConstructor(node) {
78881             if (!shouldEmitFunctionLikeDeclaration(node)) {
78882                 return undefined;
78883             }
78884             return ts.updateConstructor(node, 
78885             /*decorators*/ undefined, 
78886             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
78887         }
78888         function transformConstructorBody(body, constructor) {
78889             var parametersWithPropertyAssignments = constructor &&
78890                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
78891             if (!ts.some(parametersWithPropertyAssignments)) {
78892                 return ts.visitFunctionBody(body, visitor, context);
78893             }
78894             var statements = [];
78895             var indexOfFirstStatement = 0;
78896             resumeLexicalEnvironment();
78897             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
78898             // Add parameters with property assignments. Transforms this:
78899             //
78900             //  constructor (public x, public y) {
78901             //  }
78902             //
78903             // Into this:
78904             //
78905             //  constructor (x, y) {
78906             //      this.x = x;
78907             //      this.y = y;
78908             //  }
78909             //
78910             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
78911             // Add the existing statements, skipping the initial super call.
78912             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
78913             // End the lexical environment.
78914             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
78915             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), body.statements), /*multiLine*/ true);
78916             ts.setTextRange(block, /*location*/ body);
78917             ts.setOriginalNode(block, body);
78918             return block;
78919         }
78920         /**
78921          * Transforms a parameter into a property assignment statement.
78922          *
78923          * @param node The parameter declaration.
78924          */
78925         function transformParameterWithPropertyAssignment(node) {
78926             var name = node.name;
78927             if (!ts.isIdentifier(name)) {
78928                 return undefined;
78929             }
78930             var propertyName = ts.getMutableClone(name);
78931             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
78932             var localName = ts.getMutableClone(name);
78933             ts.setEmitFlags(localName, 1536 /* NoComments */);
78934             return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(ts.createExpressionStatement(ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1))));
78935         }
78936         function visitMethodDeclaration(node) {
78937             if (!shouldEmitFunctionLikeDeclaration(node)) {
78938                 return undefined;
78939             }
78940             var updated = ts.updateMethod(node, 
78941             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
78942             /*questionToken*/ undefined, 
78943             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78944             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
78945             if (updated !== node) {
78946                 // While we emit the source map for the node after skipping decorators and modifiers,
78947                 // we need to emit the comments for the original range.
78948                 ts.setCommentRange(updated, node);
78949                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78950             }
78951             return updated;
78952         }
78953         /**
78954          * Determines whether to emit an accessor declaration. We should not emit the
78955          * declaration if it does not have a body and is abstract.
78956          *
78957          * @param node The declaration node.
78958          */
78959         function shouldEmitAccessorDeclaration(node) {
78960             return !(ts.nodeIsMissing(node.body) && ts.hasModifier(node, 128 /* Abstract */));
78961         }
78962         function visitGetAccessor(node) {
78963             if (!shouldEmitAccessorDeclaration(node)) {
78964                 return undefined;
78965             }
78966             var updated = ts.updateGetAccessor(node, 
78967             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
78968             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78969             if (updated !== node) {
78970                 // While we emit the source map for the node after skipping decorators and modifiers,
78971                 // we need to emit the comments for the original range.
78972                 ts.setCommentRange(updated, node);
78973                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78974             }
78975             return updated;
78976         }
78977         function visitSetAccessor(node) {
78978             if (!shouldEmitAccessorDeclaration(node)) {
78979                 return undefined;
78980             }
78981             var updated = ts.updateSetAccessor(node, 
78982             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78983             if (updated !== node) {
78984                 // While we emit the source map for the node after skipping decorators and modifiers,
78985                 // we need to emit the comments for the original range.
78986                 ts.setCommentRange(updated, node);
78987                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
78988             }
78989             return updated;
78990         }
78991         function visitFunctionDeclaration(node) {
78992             if (!shouldEmitFunctionLikeDeclaration(node)) {
78993                 return ts.createNotEmittedStatement(node);
78994             }
78995             var updated = ts.updateFunctionDeclaration(node, 
78996             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
78997             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
78998             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
78999             if (isExportOfNamespace(node)) {
79000                 var statements = [updated];
79001                 addExportMemberAssignment(statements, node);
79002                 return statements;
79003             }
79004             return updated;
79005         }
79006         function visitFunctionExpression(node) {
79007             if (!shouldEmitFunctionLikeDeclaration(node)) {
79008                 return ts.createOmittedExpression();
79009             }
79010             var updated = ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
79011             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79012             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || ts.createBlock([]));
79013             return updated;
79014         }
79015         function visitArrowFunction(node) {
79016             var updated = ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
79017             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
79018             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
79019             return updated;
79020         }
79021         function visitParameter(node) {
79022             if (ts.parameterIsThisKeyword(node)) {
79023                 return undefined;
79024             }
79025             var updated = ts.updateParameter(node, 
79026             /*decorators*/ undefined, 
79027             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
79028             /*questionToken*/ undefined, 
79029             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79030             if (updated !== node) {
79031                 // While we emit the source map for the node after skipping decorators and modifiers,
79032                 // we need to emit the comments for the original range.
79033                 ts.setCommentRange(updated, node);
79034                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
79035                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
79036                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
79037             }
79038             return updated;
79039         }
79040         function visitVariableStatement(node) {
79041             if (isExportOfNamespace(node)) {
79042                 var variables = ts.getInitializedVariables(node.declarationList);
79043                 if (variables.length === 0) {
79044                     // elide statement if there are no initialized variables.
79045                     return undefined;
79046                 }
79047                 return ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
79048             }
79049             else {
79050                 return ts.visitEachChild(node, visitor, context);
79051             }
79052         }
79053         function transformInitializedVariable(node) {
79054             var name = node.name;
79055             if (ts.isBindingPattern(name)) {
79056                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
79057                 /*needsValue*/ false, createNamespaceExportExpression);
79058             }
79059             else {
79060                 return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
79061                 /*location*/ node);
79062             }
79063         }
79064         function visitVariableDeclaration(node) {
79065             return ts.updateTypeScriptVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
79066             /*exclaimationToken*/ undefined, 
79067             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
79068         }
79069         function visitParenthesizedExpression(node) {
79070             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
79071             if (ts.isAssertionExpression(innerExpression)) {
79072                 // Make sure we consider all nested cast expressions, e.g.:
79073                 // (<any><number><any>-A).x;
79074                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79075                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
79076                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
79077                 // the parentheses, however, could cause change in the semantics of the generated
79078                 // code if the casted expression has a lower precedence than the rest of the
79079                 // expression.
79080                 //
79081                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
79082                 // preserve the position information of the original expression.
79083                 //
79084                 // Due to the auto-parenthesization rules used by the visitor and factory functions
79085                 // we can safely elide the parentheses here, as a new synthetic
79086                 // ParenthesizedExpression will be inserted if we remove parentheses too
79087                 // aggressively.
79088                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
79089                 // correctly for return and throw, we must keep the parenthesis
79090                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
79091                     return ts.updateParen(node, expression);
79092                 }
79093                 return ts.createPartiallyEmittedExpression(expression, node);
79094             }
79095             return ts.visitEachChild(node, visitor, context);
79096         }
79097         function visitAssertionExpression(node) {
79098             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
79099             return ts.createPartiallyEmittedExpression(expression, node);
79100         }
79101         function visitNonNullExpression(node) {
79102             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
79103             return ts.createPartiallyEmittedExpression(expression, node);
79104         }
79105         function visitCallExpression(node) {
79106             return ts.updateCall(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79107             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79108         }
79109         function visitNewExpression(node) {
79110             return ts.updateNew(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
79111             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
79112         }
79113         function visitTaggedTemplateExpression(node) {
79114             return ts.updateTaggedTemplate(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
79115             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
79116         }
79117         function visitJsxSelfClosingElement(node) {
79118             return ts.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79119             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79120         }
79121         function visitJsxJsxOpeningElement(node) {
79122             return ts.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
79123             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
79124         }
79125         /**
79126          * Determines whether to emit an enum declaration.
79127          *
79128          * @param node The enum declaration node.
79129          */
79130         function shouldEmitEnumDeclaration(node) {
79131             return !ts.isEnumConst(node)
79132                 || compilerOptions.preserveConstEnums
79133                 || compilerOptions.isolatedModules;
79134         }
79135         /**
79136          * Visits an enum declaration.
79137          *
79138          * This function will be called any time a TypeScript enum is encountered.
79139          *
79140          * @param node The enum declaration node.
79141          */
79142         function visitEnumDeclaration(node) {
79143             if (!shouldEmitEnumDeclaration(node)) {
79144                 return ts.createNotEmittedStatement(node);
79145             }
79146             var statements = [];
79147             // We request to be advised when the printer is about to print this node. This allows
79148             // us to set up the correct state for later substitutions.
79149             var emitFlags = 2 /* AdviseOnEmitNode */;
79150             // If needed, we should emit a variable declaration for the enum. If we emit
79151             // a leading variable declaration, we should not emit leading comments for the
79152             // enum body.
79153             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79154             if (varAdded) {
79155                 // We should still emit the comments if we are emitting a system module.
79156                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79157                     emitFlags |= 512 /* NoLeadingComments */;
79158                 }
79159             }
79160             // `parameterName` is the declaration name used inside of the enum.
79161             var parameterName = getNamespaceParameterName(node);
79162             // `containerName` is the expression used inside of the enum for assignments.
79163             var containerName = getNamespaceContainerName(node);
79164             // `exportName` is the expression used within this node's container for any exported references.
79165             var exportName = ts.hasModifier(node, 1 /* Export */)
79166                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79167                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79168             //  x || (x = {})
79169             //  exports.x || (exports.x = {})
79170             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79171             if (hasNamespaceQualifiedExportName(node)) {
79172                 // `localName` is the expression used within this node's containing scope for any local references.
79173                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79174                 //  x = (exports.x || (exports.x = {}))
79175                 moduleArg = ts.createAssignment(localName, moduleArg);
79176             }
79177             //  (function (x) {
79178             //      x[x["y"] = 0] = "y";
79179             //      ...
79180             //  })(x || (x = {}));
79181             var enumStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79182             /*modifiers*/ undefined, 
79183             /*asteriskToken*/ undefined, 
79184             /*name*/ undefined, 
79185             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79186             /*type*/ undefined, transformEnumBody(node, containerName)), 
79187             /*typeArguments*/ undefined, [moduleArg]));
79188             ts.setOriginalNode(enumStatement, node);
79189             if (varAdded) {
79190                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79191                 ts.setSyntheticLeadingComments(enumStatement, undefined);
79192                 ts.setSyntheticTrailingComments(enumStatement, undefined);
79193             }
79194             ts.setTextRange(enumStatement, node);
79195             ts.addEmitFlags(enumStatement, emitFlags);
79196             statements.push(enumStatement);
79197             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
79198             // the end of the declaration.
79199             statements.push(ts.createEndOfDeclarationMarker(node));
79200             return statements;
79201         }
79202         /**
79203          * Transforms the body of an enum declaration.
79204          *
79205          * @param node The enum declaration node.
79206          */
79207         function transformEnumBody(node, localName) {
79208             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
79209             currentNamespaceContainerName = localName;
79210             var statements = [];
79211             startLexicalEnvironment();
79212             var members = ts.map(node.members, transformEnumMember);
79213             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79214             ts.addRange(statements, members);
79215             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
79216             return ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), 
79217             /*multiLine*/ true);
79218         }
79219         /**
79220          * Transforms an enum member into a statement.
79221          *
79222          * @param member The enum member node.
79223          */
79224         function transformEnumMember(member) {
79225             // enums don't support computed properties
79226             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
79227             // old emitter always generate 'expression' part of the name as-is.
79228             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
79229             var valueExpression = transformEnumMemberDeclarationValue(member);
79230             var innerAssignment = ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, name), valueExpression);
79231             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
79232                 innerAssignment :
79233                 ts.createAssignment(ts.createElementAccess(currentNamespaceContainerName, innerAssignment), name);
79234             return ts.setTextRange(ts.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
79235         }
79236         /**
79237          * Transforms the value of an enum member.
79238          *
79239          * @param member The enum member node.
79240          */
79241         function transformEnumMemberDeclarationValue(member) {
79242             var value = resolver.getConstantValue(member);
79243             if (value !== undefined) {
79244                 return ts.createLiteral(value);
79245             }
79246             else {
79247                 enableSubstitutionForNonQualifiedEnumMembers();
79248                 if (member.initializer) {
79249                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
79250                 }
79251                 else {
79252                     return ts.createVoidZero();
79253                 }
79254             }
79255         }
79256         /**
79257          * Determines whether to elide a module declaration.
79258          *
79259          * @param node The module declaration node.
79260          */
79261         function shouldEmitModuleDeclaration(nodeIn) {
79262             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
79263             if (!node) {
79264                 // If we can't find a parse tree node, assume the node is instantiated.
79265                 return true;
79266             }
79267             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
79268         }
79269         /**
79270          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
79271          * or `exports.x`).
79272          */
79273         function hasNamespaceQualifiedExportName(node) {
79274             return isExportOfNamespace(node)
79275                 || (isExternalModuleExport(node)
79276                     && moduleKind !== ts.ModuleKind.ES2015
79277                     && moduleKind !== ts.ModuleKind.ES2020
79278                     && moduleKind !== ts.ModuleKind.ESNext
79279                     && moduleKind !== ts.ModuleKind.System);
79280         }
79281         /**
79282          * Records that a declaration was emitted in the current scope, if it was the first
79283          * declaration for the provided symbol.
79284          */
79285         function recordEmittedDeclarationInScope(node) {
79286             if (!currentScopeFirstDeclarationsOfName) {
79287                 currentScopeFirstDeclarationsOfName = ts.createUnderscoreEscapedMap();
79288             }
79289             var name = declaredNameInScope(node);
79290             if (!currentScopeFirstDeclarationsOfName.has(name)) {
79291                 currentScopeFirstDeclarationsOfName.set(name, node);
79292             }
79293         }
79294         /**
79295          * Determines whether a declaration is the first declaration with
79296          * the same name emitted in the current scope.
79297          */
79298         function isFirstEmittedDeclarationInScope(node) {
79299             if (currentScopeFirstDeclarationsOfName) {
79300                 var name = declaredNameInScope(node);
79301                 return currentScopeFirstDeclarationsOfName.get(name) === node;
79302             }
79303             return true;
79304         }
79305         function declaredNameInScope(node) {
79306             ts.Debug.assertNode(node.name, ts.isIdentifier);
79307             return node.name.escapedText;
79308         }
79309         /**
79310          * Adds a leading VariableStatement for a enum or module declaration.
79311          */
79312         function addVarForEnumOrModuleDeclaration(statements, node) {
79313             // Emit a variable statement for the module. We emit top-level enums as a `var`
79314             // declaration to avoid static errors in global scripts scripts due to redeclaration.
79315             // enums in any other scope are emitted as a `let` declaration.
79316             var statement = ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79317                 ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
79318             ], currentLexicalScope.kind === 290 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
79319             ts.setOriginalNode(statement, node);
79320             recordEmittedDeclarationInScope(node);
79321             if (isFirstEmittedDeclarationInScope(node)) {
79322                 // Adjust the source map emit to match the old emitter.
79323                 if (node.kind === 248 /* EnumDeclaration */) {
79324                     ts.setSourceMapRange(statement.declarationList, node);
79325                 }
79326                 else {
79327                     ts.setSourceMapRange(statement, node);
79328                 }
79329                 // Trailing comments for module declaration should be emitted after the function closure
79330                 // instead of the variable statement:
79331                 //
79332                 //     /** Module comment*/
79333                 //     module m1 {
79334                 //         function foo4Export() {
79335                 //         }
79336                 //     } // trailing comment module
79337                 //
79338                 // Should emit:
79339                 //
79340                 //     /** Module comment*/
79341                 //     var m1;
79342                 //     (function (m1) {
79343                 //         function foo4Export() {
79344                 //         }
79345                 //     })(m1 || (m1 = {})); // trailing comment module
79346                 //
79347                 ts.setCommentRange(statement, node);
79348                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79349                 statements.push(statement);
79350                 return true;
79351             }
79352             else {
79353                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
79354                 // declaration we do not emit a leading variable declaration. To preserve the
79355                 // begin/end semantics of the declararation and to properly handle exports
79356                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
79357                 var mergeMarker = ts.createMergeDeclarationMarker(statement);
79358                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
79359                 statements.push(mergeMarker);
79360                 return false;
79361             }
79362         }
79363         /**
79364          * Visits a module declaration node.
79365          *
79366          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
79367          *
79368          * @param node The module declaration node.
79369          */
79370         function visitModuleDeclaration(node) {
79371             if (!shouldEmitModuleDeclaration(node)) {
79372                 return ts.createNotEmittedStatement(node);
79373             }
79374             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
79375             enableSubstitutionForNamespaceExports();
79376             var statements = [];
79377             // We request to be advised when the printer is about to print this node. This allows
79378             // us to set up the correct state for later substitutions.
79379             var emitFlags = 2 /* AdviseOnEmitNode */;
79380             // If needed, we should emit a variable declaration for the module. If we emit
79381             // a leading variable declaration, we should not emit leading comments for the
79382             // module body.
79383             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
79384             if (varAdded) {
79385                 // We should still emit the comments if we are emitting a system module.
79386                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
79387                     emitFlags |= 512 /* NoLeadingComments */;
79388                 }
79389             }
79390             // `parameterName` is the declaration name used inside of the namespace.
79391             var parameterName = getNamespaceParameterName(node);
79392             // `containerName` is the expression used inside of the namespace for exports.
79393             var containerName = getNamespaceContainerName(node);
79394             // `exportName` is the expression used within this node's container for any exported references.
79395             var exportName = ts.hasModifier(node, 1 /* Export */)
79396                 ? ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
79397                 : ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79398             //  x || (x = {})
79399             //  exports.x || (exports.x = {})
79400             var moduleArg = ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()));
79401             if (hasNamespaceQualifiedExportName(node)) {
79402                 // `localName` is the expression used within this node's containing scope for any local references.
79403                 var localName = ts.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
79404                 //  x = (exports.x || (exports.x = {}))
79405                 moduleArg = ts.createAssignment(localName, moduleArg);
79406             }
79407             //  (function (x_1) {
79408             //      x_1.y = ...;
79409             //  })(x || (x = {}));
79410             var moduleStatement = ts.createExpressionStatement(ts.createCall(ts.createFunctionExpression(
79411             /*modifiers*/ undefined, 
79412             /*asteriskToken*/ undefined, 
79413             /*name*/ undefined, 
79414             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
79415             /*type*/ undefined, transformModuleBody(node, containerName)), 
79416             /*typeArguments*/ undefined, [moduleArg]));
79417             ts.setOriginalNode(moduleStatement, node);
79418             if (varAdded) {
79419                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
79420                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
79421                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
79422             }
79423             ts.setTextRange(moduleStatement, node);
79424             ts.addEmitFlags(moduleStatement, emitFlags);
79425             statements.push(moduleStatement);
79426             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
79427             // the end of the declaration.
79428             statements.push(ts.createEndOfDeclarationMarker(node));
79429             return statements;
79430         }
79431         /**
79432          * Transforms the body of a module declaration.
79433          *
79434          * @param node The module declaration node.
79435          */
79436         function transformModuleBody(node, namespaceLocalName) {
79437             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
79438             var savedCurrentNamespace = currentNamespace;
79439             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
79440             currentNamespaceContainerName = namespaceLocalName;
79441             currentNamespace = node;
79442             currentScopeFirstDeclarationsOfName = undefined;
79443             var statements = [];
79444             startLexicalEnvironment();
79445             var statementsLocation;
79446             var blockLocation;
79447             if (node.body) {
79448                 if (node.body.kind === 250 /* ModuleBlock */) {
79449                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
79450                     statementsLocation = node.body.statements;
79451                     blockLocation = node.body;
79452                 }
79453                 else {
79454                     var result = visitModuleDeclaration(node.body);
79455                     if (result) {
79456                         if (ts.isArray(result)) {
79457                             ts.addRange(statements, result);
79458                         }
79459                         else {
79460                             statements.push(result);
79461                         }
79462                     }
79463                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
79464                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
79465                 }
79466             }
79467             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
79468             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
79469             currentNamespace = savedCurrentNamespace;
79470             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
79471             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
79472             /*location*/ statementsLocation), 
79473             /*multiLine*/ true);
79474             ts.setTextRange(block, blockLocation);
79475             // namespace hello.hi.world {
79476             //      function foo() {}
79477             //
79478             //      // TODO, blah
79479             // }
79480             //
79481             // should be emitted as
79482             //
79483             // var hello;
79484             // (function (hello) {
79485             //     var hi;
79486             //     (function (hi) {
79487             //         var world;
79488             //         (function (world) {
79489             //             function foo() { }
79490             //             // TODO, blah
79491             //         })(world = hi.world || (hi.world = {}));
79492             //     })(hi = hello.hi || (hello.hi = {}));
79493             // })(hello || (hello = {}));
79494             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
79495             if (!node.body || node.body.kind !== 250 /* ModuleBlock */) {
79496                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
79497             }
79498             return block;
79499         }
79500         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
79501             if (moduleDeclaration.body.kind === 249 /* ModuleDeclaration */) {
79502                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
79503                 return recursiveInnerModule || moduleDeclaration.body;
79504             }
79505         }
79506         /**
79507          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
79508          *
79509          * @param node The import declaration node.
79510          */
79511         function visitImportDeclaration(node) {
79512             if (!node.importClause) {
79513                 // Do not elide a side-effect only import declaration.
79514                 //  import "foo";
79515                 return node;
79516             }
79517             if (node.importClause.isTypeOnly) {
79518                 // Always elide type-only imports
79519                 return undefined;
79520             }
79521             // Elide the declaration if the import clause was elided.
79522             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
79523             return importClause ||
79524                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
79525                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
79526                 ? ts.updateImportDeclaration(node, 
79527                 /*decorators*/ undefined, 
79528                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
79529                 : undefined;
79530         }
79531         /**
79532          * Visits an import clause, eliding it if it is not referenced.
79533          *
79534          * @param node The import clause node.
79535          */
79536         function visitImportClause(node) {
79537             if (node.isTypeOnly) {
79538                 return undefined;
79539             }
79540             // Elide the import clause if we elide both its name and its named bindings.
79541             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
79542             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
79543             return (name || namedBindings) ? ts.updateImportClause(node, name, namedBindings, /*isTypeOnly*/ false) : undefined;
79544         }
79545         /**
79546          * Visits named import bindings, eliding it if it is not referenced.
79547          *
79548          * @param node The named import bindings node.
79549          */
79550         function visitNamedImportBindings(node) {
79551             if (node.kind === 256 /* NamespaceImport */) {
79552                 // Elide a namespace import if it is not referenced.
79553                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79554             }
79555             else {
79556                 // Elide named imports if all of its import specifiers are elided.
79557                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
79558                 return ts.some(elements) ? ts.updateNamedImports(node, elements) : undefined;
79559             }
79560         }
79561         /**
79562          * Visits an import specifier, eliding it if it is not referenced.
79563          *
79564          * @param node The import specifier node.
79565          */
79566         function visitImportSpecifier(node) {
79567             // Elide an import specifier if it is not referenced.
79568             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
79569         }
79570         /**
79571          * Visits an export assignment, eliding it if it does not contain a clause that resolves
79572          * to a value.
79573          *
79574          * @param node The export assignment node.
79575          */
79576         function visitExportAssignment(node) {
79577             // Elide the export assignment if it does not reference a value.
79578             return resolver.isValueAliasDeclaration(node)
79579                 ? ts.visitEachChild(node, visitor, context)
79580                 : undefined;
79581         }
79582         /**
79583          * Visits an export declaration, eliding it if it does not contain a clause that resolves
79584          * to a value.
79585          *
79586          * @param node The export declaration node.
79587          */
79588         function visitExportDeclaration(node) {
79589             if (node.isTypeOnly) {
79590                 return undefined;
79591             }
79592             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
79593                 // never elide `export <whatever> from <whereever>` declarations -
79594                 // they should be kept for sideffects/untyped exports, even when the
79595                 // type checker doesn't know about any exports
79596                 return node;
79597             }
79598             if (!resolver.isValueAliasDeclaration(node)) {
79599                 // Elide the export declaration if it does not export a value.
79600                 return undefined;
79601             }
79602             // Elide the export declaration if all of its named exports are elided.
79603             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
79604             return exportClause
79605                 ? ts.updateExportDeclaration(node, 
79606                 /*decorators*/ undefined, 
79607                 /*modifiers*/ undefined, exportClause, node.moduleSpecifier, node.isTypeOnly)
79608                 : undefined;
79609         }
79610         /**
79611          * Visits named exports, eliding it if it does not contain an export specifier that
79612          * resolves to a value.
79613          *
79614          * @param node The named exports node.
79615          */
79616         function visitNamedExports(node) {
79617             // Elide the named exports if all of its export specifiers were elided.
79618             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
79619             return ts.some(elements) ? ts.updateNamedExports(node, elements) : undefined;
79620         }
79621         function visitNamespaceExports(node) {
79622             return ts.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
79623         }
79624         function visitNamedExportBindings(node) {
79625             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
79626         }
79627         /**
79628          * Visits an export specifier, eliding it if it does not resolve to a value.
79629          *
79630          * @param node The export specifier node.
79631          */
79632         function visitExportSpecifier(node) {
79633             // Elide an export specifier if it does not reference a value.
79634             return resolver.isValueAliasDeclaration(node) ? node : undefined;
79635         }
79636         /**
79637          * Determines whether to emit an import equals declaration.
79638          *
79639          * @param node The import equals declaration node.
79640          */
79641         function shouldEmitImportEqualsDeclaration(node) {
79642             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
79643             // - current file is not external module
79644             // - import declaration is top level and target is value imported by entity name
79645             return resolver.isReferencedAliasDeclaration(node)
79646                 || (!ts.isExternalModule(currentSourceFile)
79647                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
79648         }
79649         /**
79650          * Visits an import equals declaration.
79651          *
79652          * @param node The import equals declaration node.
79653          */
79654         function visitImportEqualsDeclaration(node) {
79655             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
79656                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
79657                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
79658                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
79659                     return ts.setOriginalNode(ts.setTextRange(ts.createImportDeclaration(
79660                     /*decorators*/ undefined, 
79661                     /*modifiers*/ undefined, 
79662                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
79663                 }
79664                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
79665             }
79666             if (!shouldEmitImportEqualsDeclaration(node)) {
79667                 return undefined;
79668             }
79669             var moduleReference = ts.createExpressionFromEntityName(node.moduleReference);
79670             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
79671             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
79672                 //  export var ${name} = ${moduleReference};
79673                 //  var ${name} = ${moduleReference};
79674                 return ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.createVariableDeclarationList([
79675                     ts.setOriginalNode(ts.createVariableDeclaration(node.name, 
79676                     /*type*/ undefined, moduleReference), node)
79677                 ])), node), node);
79678             }
79679             else {
79680                 // exports.${name} = ${moduleReference};
79681                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
79682             }
79683         }
79684         /**
79685          * Gets a value indicating whether the node is exported from a namespace.
79686          *
79687          * @param node The node to test.
79688          */
79689         function isExportOfNamespace(node) {
79690             return currentNamespace !== undefined && ts.hasModifier(node, 1 /* Export */);
79691         }
79692         /**
79693          * Gets a value indicating whether the node is exported from an external module.
79694          *
79695          * @param node The node to test.
79696          */
79697         function isExternalModuleExport(node) {
79698             return currentNamespace === undefined && ts.hasModifier(node, 1 /* Export */);
79699         }
79700         /**
79701          * Gets a value indicating whether the node is a named export from an external module.
79702          *
79703          * @param node The node to test.
79704          */
79705         function isNamedExternalModuleExport(node) {
79706             return isExternalModuleExport(node)
79707                 && !ts.hasModifier(node, 512 /* Default */);
79708         }
79709         /**
79710          * Gets a value indicating whether the node is the default export of an external module.
79711          *
79712          * @param node The node to test.
79713          */
79714         function isDefaultExternalModuleExport(node) {
79715             return isExternalModuleExport(node)
79716                 && ts.hasModifier(node, 512 /* Default */);
79717         }
79718         /**
79719          * Creates a statement for the provided expression. This is used in calls to `map`.
79720          */
79721         function expressionToStatement(expression) {
79722             return ts.createExpressionStatement(expression);
79723         }
79724         function addExportMemberAssignment(statements, node) {
79725             var expression = ts.createAssignment(ts.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), ts.getLocalName(node));
79726             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
79727             var statement = ts.createExpressionStatement(expression);
79728             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
79729             statements.push(statement);
79730         }
79731         function createNamespaceExport(exportName, exportValue, location) {
79732             return ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
79733         }
79734         function createNamespaceExportExpression(exportName, exportValue, location) {
79735             return ts.setTextRange(ts.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
79736         }
79737         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
79738             return ts.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
79739         }
79740         /**
79741          * Gets the declaration name used inside of a namespace or enum.
79742          */
79743         function getNamespaceParameterName(node) {
79744             var name = ts.getGeneratedNameForNode(node);
79745             ts.setSourceMapRange(name, node.name);
79746             return name;
79747         }
79748         /**
79749          * Gets the expression used to refer to a namespace or enum within the body
79750          * of its declaration.
79751          */
79752         function getNamespaceContainerName(node) {
79753             return ts.getGeneratedNameForNode(node);
79754         }
79755         /**
79756          * Gets a local alias for a class declaration if it is a decorated class with an internal
79757          * reference to the static side of the class. This is necessary to avoid issues with
79758          * double-binding semantics for the class name.
79759          */
79760         function getClassAliasIfNeeded(node) {
79761             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
79762                 enableSubstitutionForClassAliases();
79763                 var classAlias = ts.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
79764                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
79765                 hoistVariableDeclaration(classAlias);
79766                 return classAlias;
79767             }
79768         }
79769         function getClassPrototype(node) {
79770             return ts.createPropertyAccess(ts.getDeclarationName(node), "prototype");
79771         }
79772         function getClassMemberPrefix(node, member) {
79773             return ts.hasModifier(member, 32 /* Static */)
79774                 ? ts.getDeclarationName(node)
79775                 : getClassPrototype(node);
79776         }
79777         function enableSubstitutionForNonQualifiedEnumMembers() {
79778             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
79779                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79780                 context.enableSubstitution(75 /* Identifier */);
79781             }
79782         }
79783         function enableSubstitutionForClassAliases() {
79784             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
79785                 enabledSubstitutions |= 1 /* ClassAliases */;
79786                 // We need to enable substitutions for identifiers. This allows us to
79787                 // substitute class names inside of a class declaration.
79788                 context.enableSubstitution(75 /* Identifier */);
79789                 // Keep track of class aliases.
79790                 classAliases = [];
79791             }
79792         }
79793         function enableSubstitutionForNamespaceExports() {
79794             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
79795                 enabledSubstitutions |= 2 /* NamespaceExports */;
79796                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
79797                 // substitute the names of exported members of a namespace.
79798                 context.enableSubstitution(75 /* Identifier */);
79799                 context.enableSubstitution(282 /* ShorthandPropertyAssignment */);
79800                 // We need to be notified when entering and exiting namespaces.
79801                 context.enableEmitNotification(249 /* ModuleDeclaration */);
79802             }
79803         }
79804         function isTransformedModuleDeclaration(node) {
79805             return ts.getOriginalNode(node).kind === 249 /* ModuleDeclaration */;
79806         }
79807         function isTransformedEnumDeclaration(node) {
79808             return ts.getOriginalNode(node).kind === 248 /* EnumDeclaration */;
79809         }
79810         /**
79811          * Hook for node emit.
79812          *
79813          * @param hint A hint as to the intended usage of the node.
79814          * @param node The node to emit.
79815          * @param emit A callback used to emit the node in the printer.
79816          */
79817         function onEmitNode(hint, node, emitCallback) {
79818             var savedApplicableSubstitutions = applicableSubstitutions;
79819             var savedCurrentSourceFile = currentSourceFile;
79820             if (ts.isSourceFile(node)) {
79821                 currentSourceFile = node;
79822             }
79823             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
79824                 applicableSubstitutions |= 2 /* NamespaceExports */;
79825             }
79826             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
79827                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
79828             }
79829             previousOnEmitNode(hint, node, emitCallback);
79830             applicableSubstitutions = savedApplicableSubstitutions;
79831             currentSourceFile = savedCurrentSourceFile;
79832         }
79833         /**
79834          * Hooks node substitutions.
79835          *
79836          * @param hint A hint as to the intended usage of the node.
79837          * @param node The node to substitute.
79838          */
79839         function onSubstituteNode(hint, node) {
79840             node = previousOnSubstituteNode(hint, node);
79841             if (hint === 1 /* Expression */) {
79842                 return substituteExpression(node);
79843             }
79844             else if (ts.isShorthandPropertyAssignment(node)) {
79845                 return substituteShorthandPropertyAssignment(node);
79846             }
79847             return node;
79848         }
79849         function substituteShorthandPropertyAssignment(node) {
79850             if (enabledSubstitutions & 2 /* NamespaceExports */) {
79851                 var name = node.name;
79852                 var exportedName = trySubstituteNamespaceExportedName(name);
79853                 if (exportedName) {
79854                     // A shorthand property with an assignment initializer is probably part of a
79855                     // destructuring assignment
79856                     if (node.objectAssignmentInitializer) {
79857                         var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer);
79858                         return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
79859                     }
79860                     return ts.setTextRange(ts.createPropertyAssignment(name, exportedName), node);
79861                 }
79862             }
79863             return node;
79864         }
79865         function substituteExpression(node) {
79866             switch (node.kind) {
79867                 case 75 /* Identifier */:
79868                     return substituteExpressionIdentifier(node);
79869                 case 194 /* PropertyAccessExpression */:
79870                     return substitutePropertyAccessExpression(node);
79871                 case 195 /* ElementAccessExpression */:
79872                     return substituteElementAccessExpression(node);
79873             }
79874             return node;
79875         }
79876         function substituteExpressionIdentifier(node) {
79877             return trySubstituteClassAlias(node)
79878                 || trySubstituteNamespaceExportedName(node)
79879                 || node;
79880         }
79881         function trySubstituteClassAlias(node) {
79882             if (enabledSubstitutions & 1 /* ClassAliases */) {
79883                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
79884                     // Due to the emit for class decorators, any reference to the class from inside of the class body
79885                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
79886                     // behavior of class names in ES6.
79887                     // Also, when emitting statics for class expressions, we must substitute a class alias for
79888                     // constructor references in static property initializers.
79889                     var declaration = resolver.getReferencedValueDeclaration(node);
79890                     if (declaration) {
79891                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
79892                         if (classAlias) {
79893                             var clone_1 = ts.getSynthesizedClone(classAlias);
79894                             ts.setSourceMapRange(clone_1, node);
79895                             ts.setCommentRange(clone_1, node);
79896                             return clone_1;
79897                         }
79898                     }
79899                 }
79900             }
79901             return undefined;
79902         }
79903         function trySubstituteNamespaceExportedName(node) {
79904             // If this is explicitly a local name, do not substitute.
79905             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
79906                 // If we are nested within a namespace declaration, we may need to qualifiy
79907                 // an identifier that is exported from a merged namespace.
79908                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
79909                 if (container && container.kind !== 290 /* SourceFile */) {
79910                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 249 /* ModuleDeclaration */) ||
79911                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 248 /* EnumDeclaration */);
79912                     if (substitute) {
79913                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(container), node), 
79914                         /*location*/ node);
79915                     }
79916                 }
79917             }
79918             return undefined;
79919         }
79920         function substitutePropertyAccessExpression(node) {
79921             return substituteConstantValue(node);
79922         }
79923         function substituteElementAccessExpression(node) {
79924             return substituteConstantValue(node);
79925         }
79926         function substituteConstantValue(node) {
79927             var constantValue = tryGetConstEnumValue(node);
79928             if (constantValue !== undefined) {
79929                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
79930                 ts.setConstantValue(node, constantValue);
79931                 var substitute = ts.createLiteral(constantValue);
79932                 if (!compilerOptions.removeComments) {
79933                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
79934                     var propertyName = ts.isPropertyAccessExpression(originalNode)
79935                         ? ts.declarationNameToString(originalNode.name)
79936                         : ts.getTextOfNode(originalNode.argumentExpression);
79937                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
79938                 }
79939                 return substitute;
79940             }
79941             return node;
79942         }
79943         function tryGetConstEnumValue(node) {
79944             if (compilerOptions.isolatedModules) {
79945                 return undefined;
79946             }
79947             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
79948         }
79949     }
79950     ts.transformTypeScript = transformTypeScript;
79951     function createDecorateHelper(context, decoratorExpressions, target, memberName, descriptor, location) {
79952         var argumentsArray = [];
79953         argumentsArray.push(ts.createArrayLiteral(decoratorExpressions, /*multiLine*/ true));
79954         argumentsArray.push(target);
79955         if (memberName) {
79956             argumentsArray.push(memberName);
79957             if (descriptor) {
79958                 argumentsArray.push(descriptor);
79959             }
79960         }
79961         context.requestEmitHelper(ts.decorateHelper);
79962         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__decorate"), 
79963         /*typeArguments*/ undefined, argumentsArray), location);
79964     }
79965     ts.decorateHelper = {
79966         name: "typescript:decorate",
79967         importName: "__decorate",
79968         scoped: false,
79969         priority: 2,
79970         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            };"
79971     };
79972     function createMetadataHelper(context, metadataKey, metadataValue) {
79973         context.requestEmitHelper(ts.metadataHelper);
79974         return ts.createCall(ts.getUnscopedHelperName("__metadata"), 
79975         /*typeArguments*/ undefined, [
79976             ts.createLiteral(metadataKey),
79977             metadataValue
79978         ]);
79979     }
79980     ts.metadataHelper = {
79981         name: "typescript:metadata",
79982         importName: "__metadata",
79983         scoped: false,
79984         priority: 3,
79985         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            };"
79986     };
79987     function createParamHelper(context, expression, parameterOffset, location) {
79988         context.requestEmitHelper(ts.paramHelper);
79989         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__param"), 
79990         /*typeArguments*/ undefined, [
79991             ts.createLiteral(parameterOffset),
79992             expression
79993         ]), location);
79994     }
79995     ts.paramHelper = {
79996         name: "typescript:param",
79997         importName: "__param",
79998         scoped: false,
79999         priority: 4,
80000         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
80001     };
80002 })(ts || (ts = {}));
80003 /*@internal*/
80004 var ts;
80005 (function (ts) {
80006     var ClassPropertySubstitutionFlags;
80007     (function (ClassPropertySubstitutionFlags) {
80008         /**
80009          * Enables substitutions for class expressions with static fields
80010          * which have initializers that reference the class name.
80011          */
80012         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
80013     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
80014     var PrivateIdentifierPlacement;
80015     (function (PrivateIdentifierPlacement) {
80016         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
80017     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
80018     /**
80019      * Transforms ECMAScript Class Syntax.
80020      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
80021      * For now, this transforms public field declarations using TypeScript class semantics,
80022      * where declarations are elided and initializers are transformed as assignments in the constructor.
80023      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
80024      */
80025     function transformClassFields(context) {
80026         var hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
80027         var resolver = context.getEmitResolver();
80028         var compilerOptions = context.getCompilerOptions();
80029         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80030         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
80031         var previousOnSubstituteNode = context.onSubstituteNode;
80032         context.onSubstituteNode = onSubstituteNode;
80033         var enabledSubstitutions;
80034         var classAliases;
80035         /**
80036          * Tracks what computed name expressions originating from elided names must be inlined
80037          * at the next execution site, in document order
80038          */
80039         var pendingExpressions;
80040         /**
80041          * Tracks what computed name expression statements and static property initializers must be
80042          * emitted at the next execution site, in document order (for decorated classes).
80043          */
80044         var pendingStatements;
80045         var privateIdentifierEnvironmentStack = [];
80046         var currentPrivateIdentifierEnvironment;
80047         return ts.chainBundle(transformSourceFile);
80048         function transformSourceFile(node) {
80049             var options = context.getCompilerOptions();
80050             if (node.isDeclarationFile
80051                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
80052                 return node;
80053             }
80054             var visited = ts.visitEachChild(node, visitor, context);
80055             ts.addEmitHelpers(visited, context.readEmitHelpers());
80056             return visited;
80057         }
80058         function visitor(node) {
80059             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
80060                 return node;
80061             switch (node.kind) {
80062                 case 214 /* ClassExpression */:
80063                 case 245 /* ClassDeclaration */:
80064                     return visitClassLike(node);
80065                 case 159 /* PropertyDeclaration */:
80066                     return visitPropertyDeclaration(node);
80067                 case 225 /* VariableStatement */:
80068                     return visitVariableStatement(node);
80069                 case 154 /* ComputedPropertyName */:
80070                     return visitComputedPropertyName(node);
80071                 case 194 /* PropertyAccessExpression */:
80072                     return visitPropertyAccessExpression(node);
80073                 case 207 /* PrefixUnaryExpression */:
80074                     return visitPrefixUnaryExpression(node);
80075                 case 208 /* PostfixUnaryExpression */:
80076                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
80077                 case 196 /* CallExpression */:
80078                     return visitCallExpression(node);
80079                 case 209 /* BinaryExpression */:
80080                     return visitBinaryExpression(node);
80081                 case 76 /* PrivateIdentifier */:
80082                     return visitPrivateIdentifier(node);
80083                 case 226 /* ExpressionStatement */:
80084                     return visitExpressionStatement(node);
80085                 case 230 /* ForStatement */:
80086                     return visitForStatement(node);
80087                 case 198 /* TaggedTemplateExpression */:
80088                     return visitTaggedTemplateExpression(node);
80089             }
80090             return ts.visitEachChild(node, visitor, context);
80091         }
80092         function visitorDestructuringTarget(node) {
80093             switch (node.kind) {
80094                 case 193 /* ObjectLiteralExpression */:
80095                 case 192 /* ArrayLiteralExpression */:
80096                     return visitAssignmentPattern(node);
80097                 default:
80098                     return visitor(node);
80099             }
80100         }
80101         /**
80102          * If we visit a private name, this means it is an undeclared private name.
80103          * Replace it with an empty identifier to indicate a problem with the code.
80104          */
80105         function visitPrivateIdentifier(node) {
80106             if (!shouldTransformPrivateFields) {
80107                 return node;
80108             }
80109             return ts.setOriginalNode(ts.createIdentifier(""), node);
80110         }
80111         /**
80112          * Visits the members of a class that has fields.
80113          *
80114          * @param node The node to visit.
80115          */
80116         function classElementVisitor(node) {
80117             switch (node.kind) {
80118                 case 162 /* Constructor */:
80119                     // Constructors for classes using class fields are transformed in
80120                     // `visitClassDeclaration` or `visitClassExpression`.
80121                     return undefined;
80122                 case 163 /* GetAccessor */:
80123                 case 164 /* SetAccessor */:
80124                 case 161 /* MethodDeclaration */:
80125                     // Visit the name of the member (if it's a computed property name).
80126                     return ts.visitEachChild(node, classElementVisitor, context);
80127                 case 159 /* PropertyDeclaration */:
80128                     return visitPropertyDeclaration(node);
80129                 case 154 /* ComputedPropertyName */:
80130                     return visitComputedPropertyName(node);
80131                 case 222 /* SemicolonClassElement */:
80132                     return node;
80133                 default:
80134                     return visitor(node);
80135             }
80136         }
80137         function visitVariableStatement(node) {
80138             var savedPendingStatements = pendingStatements;
80139             pendingStatements = [];
80140             var visitedNode = ts.visitEachChild(node, visitor, context);
80141             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
80142                 visitedNode;
80143             pendingStatements = savedPendingStatements;
80144             return statement;
80145         }
80146         function visitComputedPropertyName(name) {
80147             var node = ts.visitEachChild(name, visitor, context);
80148             if (ts.some(pendingExpressions)) {
80149                 var expressions = pendingExpressions;
80150                 expressions.push(name.expression);
80151                 pendingExpressions = [];
80152                 node = ts.updateComputedPropertyName(node, ts.inlineExpressions(expressions));
80153             }
80154             return node;
80155         }
80156         function visitPropertyDeclaration(node) {
80157             ts.Debug.assert(!ts.some(node.decorators));
80158             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80159                 // Initializer is elided as the field is initialized in transformConstructor.
80160                 return ts.updateProperty(node, 
80161                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
80162                 /*questionOrExclamationToken*/ undefined, 
80163                 /*type*/ undefined, 
80164                 /*initializer*/ undefined);
80165             }
80166             // Create a temporary variable to store a computed property name (if necessary).
80167             // If it's not inlineable, then we emit an expression after the class which assigns
80168             // the property name to the temporary variable.
80169             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
80170             if (expr && !ts.isSimpleInlineableExpression(expr)) {
80171                 (pendingExpressions || (pendingExpressions = [])).push(expr);
80172             }
80173             return undefined;
80174         }
80175         function createPrivateIdentifierAccess(info, receiver) {
80176             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80177             switch (info.placement) {
80178                 case 0 /* InstanceField */:
80179                     return createClassPrivateFieldGetHelper(context, ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver), info.weakMapName);
80180                 default: return ts.Debug.fail("Unexpected private identifier placement");
80181             }
80182         }
80183         function visitPropertyAccessExpression(node) {
80184             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
80185                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
80186                 if (privateIdentifierInfo) {
80187                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
80188                 }
80189             }
80190             return ts.visitEachChild(node, visitor, context);
80191         }
80192         function visitPrefixUnaryExpression(node) {
80193             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80194                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80195                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80196                     40 /* MinusToken */ : undefined;
80197                 var info = void 0;
80198                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80199                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80200                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80201                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80202                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */), node);
80203                 }
80204             }
80205             return ts.visitEachChild(node, visitor, context);
80206         }
80207         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
80208             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
80209                 var operator = node.operator === 45 /* PlusPlusToken */ ?
80210                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
80211                     40 /* MinusToken */ : undefined;
80212                 var info = void 0;
80213                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
80214                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
80215                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80216                     var existingValue = ts.createPrefix(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
80217                     // Create a temporary variable to store the value returned by the expression.
80218                     var returnValue = valueIsDiscarded ? undefined : ts.createTempVariable(hoistVariableDeclaration);
80219                     return ts.setOriginalNode(ts.inlineExpressions(ts.compact([
80220                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, ts.createBinary(returnValue ? ts.createAssignment(returnValue, existingValue) : existingValue, operator, ts.createLiteral(1)), 62 /* EqualsToken */),
80221                         returnValue
80222                     ])), node);
80223                 }
80224             }
80225             return ts.visitEachChild(node, visitor, context);
80226         }
80227         function visitForStatement(node) {
80228             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
80229                 return ts.updateFor(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));
80230             }
80231             return ts.visitEachChild(node, visitor, context);
80232         }
80233         function visitExpressionStatement(node) {
80234             if (ts.isPostfixUnaryExpression(node.expression)) {
80235                 return ts.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
80236             }
80237             return ts.visitEachChild(node, visitor, context);
80238         }
80239         function createCopiableReceiverExpr(receiver) {
80240             var clone = ts.nodeIsSynthesized(receiver) ? receiver : ts.getSynthesizedClone(receiver);
80241             if (ts.isSimpleInlineableExpression(receiver)) {
80242                 return { readExpression: clone, initializeExpression: undefined };
80243             }
80244             var readExpression = ts.createTempVariable(hoistVariableDeclaration);
80245             var initializeExpression = ts.createAssignment(readExpression, clone);
80246             return { readExpression: readExpression, initializeExpression: initializeExpression };
80247         }
80248         function visitCallExpression(node) {
80249             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
80250                 // Transform call expressions of private names to properly bind the `this` parameter.
80251                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80252                 return ts.updateCall(node, ts.createPropertyAccess(ts.visitNode(target, visitor), "call"), 
80253                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
80254             }
80255             return ts.visitEachChild(node, visitor, context);
80256         }
80257         function visitTaggedTemplateExpression(node) {
80258             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
80259                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
80260                 var _a = ts.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
80261                 return ts.updateTaggedTemplate(node, ts.createCall(ts.createPropertyAccess(ts.visitNode(target, visitor), "bind"), 
80262                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
80263             }
80264             return ts.visitEachChild(node, visitor, context);
80265         }
80266         function visitBinaryExpression(node) {
80267             if (shouldTransformPrivateFields) {
80268                 if (ts.isDestructuringAssignment(node)) {
80269                     var savedPendingExpressions = pendingExpressions;
80270                     pendingExpressions = undefined;
80271                     node = ts.updateBinary(node, ts.visitNode(node.left, visitorDestructuringTarget), ts.visitNode(node.right, visitor), node.operatorToken);
80272                     var expr = ts.some(pendingExpressions) ?
80273                         ts.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
80274                         node;
80275                     pendingExpressions = savedPendingExpressions;
80276                     return expr;
80277                 }
80278                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
80279                     var info = accessPrivateIdentifier(node.left.name);
80280                     if (info) {
80281                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
80282                     }
80283                 }
80284             }
80285             return ts.visitEachChild(node, visitor, context);
80286         }
80287         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
80288             switch (info.placement) {
80289                 case 0 /* InstanceField */: {
80290                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
80291                 }
80292                 default: return ts.Debug.fail("Unexpected private identifier placement");
80293             }
80294         }
80295         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
80296             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
80297             right = ts.visitNode(right, visitor, ts.isExpression);
80298             if (ts.isCompoundAssignment(operator)) {
80299                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
80300                 return createClassPrivateFieldSetHelper(context, initializeExpression || readExpression, info.weakMapName, ts.createBinary(createClassPrivateFieldGetHelper(context, readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
80301             }
80302             else {
80303                 return createClassPrivateFieldSetHelper(context, receiver, info.weakMapName, right);
80304             }
80305         }
80306         /**
80307          * Set up the environment for a class.
80308          */
80309         function visitClassLike(node) {
80310             var savedPendingExpressions = pendingExpressions;
80311             pendingExpressions = undefined;
80312             if (shouldTransformPrivateFields) {
80313                 startPrivateIdentifierEnvironment();
80314             }
80315             var result = ts.isClassDeclaration(node) ?
80316                 visitClassDeclaration(node) :
80317                 visitClassExpression(node);
80318             if (shouldTransformPrivateFields) {
80319                 endPrivateIdentifierEnvironment();
80320             }
80321             pendingExpressions = savedPendingExpressions;
80322             return result;
80323         }
80324         function doesClassElementNeedTransform(node) {
80325             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
80326         }
80327         function visitClassDeclaration(node) {
80328             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80329                 return ts.visitEachChild(node, visitor, context);
80330             }
80331             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80332             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80333             var statements = [
80334                 ts.updateClassDeclaration(node, 
80335                 /*decorators*/ undefined, node.modifiers, node.name, 
80336                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
80337             ];
80338             // Write any pending expressions from elided or moved computed property names
80339             if (ts.some(pendingExpressions)) {
80340                 statements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80341             }
80342             // Emit static property assignment. Because classDeclaration is lexically evaluated,
80343             // it is safe to emit static property assignment after classDeclaration
80344             // From ES6 specification:
80345             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
80346             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
80347             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80348             if (ts.some(staticProperties)) {
80349                 addPropertyStatements(statements, staticProperties, ts.getInternalName(node));
80350             }
80351             return statements;
80352         }
80353         function visitClassExpression(node) {
80354             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
80355                 return ts.visitEachChild(node, visitor, context);
80356             }
80357             // If this class expression is a transformation of a decorated class declaration,
80358             // then we want to output the pendingExpressions as statements, not as inlined
80359             // expressions with the class statement.
80360             //
80361             // In this case, we use pendingStatements to produce the same output as the
80362             // class declaration transformation. The VariableStatement visitor will insert
80363             // these statements after the class expression variable statement.
80364             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
80365             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
80366             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
80367             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */);
80368             var classExpression = ts.updateClassExpression(node, node.modifiers, node.name, 
80369             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
80370             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
80371                 if (isDecoratedClassDeclaration) {
80372                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
80373                     // Write any pending expressions from elided or moved computed property names
80374                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
80375                         pendingStatements.push(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
80376                     }
80377                     if (pendingStatements && ts.some(staticProperties)) {
80378                         addPropertyStatements(pendingStatements, staticProperties, ts.getInternalName(node));
80379                     }
80380                     return classExpression;
80381                 }
80382                 else {
80383                     var expressions = [];
80384                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
80385                     var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
80386                     if (isClassWithConstructorReference) {
80387                         // record an alias as the class name is not in scope for statics.
80388                         enableSubstitutionForClassAliases();
80389                         var alias = ts.getSynthesizedClone(temp);
80390                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
80391                         classAliases[ts.getOriginalNodeId(node)] = alias;
80392                     }
80393                     // To preserve the behavior of the old emitter, we explicitly indent
80394                     // the body of a class with static initializers.
80395                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
80396                     expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression)));
80397                     // Add any pending expressions leftover from elided or relocated computed property names
80398                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
80399                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
80400                     expressions.push(ts.startOnNewLine(temp));
80401                     return ts.inlineExpressions(expressions);
80402                 }
80403             }
80404             return classExpression;
80405         }
80406         function transformClassMembers(node, isDerivedClass) {
80407             if (shouldTransformPrivateFields) {
80408                 // Declare private names.
80409                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
80410                     var member = _a[_i];
80411                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
80412                         addPrivateIdentifierToEnvironment(member.name);
80413                     }
80414                 }
80415             }
80416             var members = [];
80417             var constructor = transformConstructor(node, isDerivedClass);
80418             if (constructor) {
80419                 members.push(constructor);
80420             }
80421             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
80422             return ts.setTextRange(ts.createNodeArray(members), /*location*/ node.members);
80423         }
80424         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
80425             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
80426                 return false;
80427             }
80428             if (context.getCompilerOptions().useDefineForClassFields) {
80429                 // If we are using define semantics and targeting ESNext or higher,
80430                 // then we don't need to transform any class properties.
80431                 return languageVersion < 99 /* ESNext */;
80432             }
80433             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
80434         }
80435         function transformConstructor(node, isDerivedClass) {
80436             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
80437             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
80438             if (!ts.some(properties)) {
80439                 return constructor;
80440             }
80441             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
80442             var body = transformConstructorBody(node, constructor, isDerivedClass);
80443             if (!body) {
80444                 return undefined;
80445             }
80446             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(ts.createConstructor(
80447             /*decorators*/ undefined, 
80448             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
80449         }
80450         function transformConstructorBody(node, constructor, isDerivedClass) {
80451             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
80452             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
80453             if (!useDefineForClassFields) {
80454                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
80455             }
80456             // Only generate synthetic constructor when there are property initializers to move.
80457             if (!constructor && !ts.some(properties)) {
80458                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
80459             }
80460             resumeLexicalEnvironment();
80461             var indexOfFirstStatement = 0;
80462             var statements = [];
80463             if (!constructor && isDerivedClass) {
80464                 // Add a synthetic `super` call:
80465                 //
80466                 //  super(...arguments);
80467                 //
80468                 statements.push(ts.createExpressionStatement(ts.createCall(ts.createSuper(), 
80469                 /*typeArguments*/ undefined, [ts.createSpread(ts.createIdentifier("arguments"))])));
80470             }
80471             if (constructor) {
80472                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(constructor, statements, visitor);
80473             }
80474             // Add the property initializers. Transforms this:
80475             //
80476             //  public x = 1;
80477             //
80478             // Into this:
80479             //
80480             //  constructor() {
80481             //      this.x = 1;
80482             //  }
80483             //
80484             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
80485                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
80486                 if (afterParameterProperties === -1) {
80487                     afterParameterProperties = constructor.body.statements.length;
80488                 }
80489                 if (afterParameterProperties > indexOfFirstStatement) {
80490                     if (!useDefineForClassFields) {
80491                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
80492                     }
80493                     indexOfFirstStatement = afterParameterProperties;
80494                 }
80495             }
80496             addPropertyStatements(statements, properties, ts.createThis());
80497             // Add existing statements, skipping the initial super call.
80498             if (constructor) {
80499                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
80500             }
80501             statements = ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
80502             return ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), 
80503             /*location*/ constructor ? constructor.body.statements : node.members), 
80504             /*multiLine*/ true), 
80505             /*location*/ constructor ? constructor.body : undefined);
80506         }
80507         /**
80508          * Generates assignment statements for property initializers.
80509          *
80510          * @param properties An array of property declarations to transform.
80511          * @param receiver The receiver on which each property should be assigned.
80512          */
80513         function addPropertyStatements(statements, properties, receiver) {
80514             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
80515                 var property = properties_8[_i];
80516                 var expression = transformProperty(property, receiver);
80517                 if (!expression) {
80518                     continue;
80519                 }
80520                 var statement = ts.createExpressionStatement(expression);
80521                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
80522                 ts.setCommentRange(statement, property);
80523                 ts.setOriginalNode(statement, property);
80524                 statements.push(statement);
80525             }
80526         }
80527         /**
80528          * Generates assignment expressions for property initializers.
80529          *
80530          * @param properties An array of property declarations to transform.
80531          * @param receiver The receiver on which each property should be assigned.
80532          */
80533         function generateInitializedPropertyExpressions(properties, receiver) {
80534             var expressions = [];
80535             for (var _i = 0, properties_9 = properties; _i < properties_9.length; _i++) {
80536                 var property = properties_9[_i];
80537                 var expression = transformProperty(property, receiver);
80538                 if (!expression) {
80539                     continue;
80540                 }
80541                 ts.startOnNewLine(expression);
80542                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
80543                 ts.setCommentRange(expression, property);
80544                 ts.setOriginalNode(expression, property);
80545                 expressions.push(expression);
80546             }
80547             return expressions;
80548         }
80549         /**
80550          * Transforms a property initializer into an assignment statement.
80551          *
80552          * @param property The property declaration.
80553          * @param receiver The object receiving the property assignment.
80554          */
80555         function transformProperty(property, receiver) {
80556             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
80557             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
80558             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
80559                 ? ts.updateComputedPropertyName(property.name, ts.getGeneratedNameForNode(property.name))
80560                 : property.name;
80561             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
80562                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
80563                 if (privateIdentifierInfo) {
80564                     switch (privateIdentifierInfo.placement) {
80565                         case 0 /* InstanceField */: {
80566                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
80567                         }
80568                     }
80569                 }
80570                 else {
80571                     ts.Debug.fail("Undeclared private name for property declaration.");
80572                 }
80573             }
80574             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80575                 return undefined;
80576             }
80577             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
80578                 return undefined;
80579             }
80580             var propertyOriginalNode = ts.getOriginalNode(property);
80581             var initializer = property.initializer || emitAssignment ? ts.visitNode(property.initializer, visitor, ts.isExpression)
80582                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
80583                     : ts.createVoidZero();
80584             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
80585                 var memberAccess = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ propertyName);
80586                 return ts.createAssignment(memberAccess, initializer);
80587             }
80588             else {
80589                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
80590                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
80591                         : propertyName;
80592                 var descriptor = ts.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
80593                 return ts.createObjectDefinePropertyCall(receiver, name, descriptor);
80594             }
80595         }
80596         function enableSubstitutionForClassAliases() {
80597             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
80598                 enabledSubstitutions |= 1 /* ClassAliases */;
80599                 // We need to enable substitutions for identifiers. This allows us to
80600                 // substitute class names inside of a class declaration.
80601                 context.enableSubstitution(75 /* Identifier */);
80602                 // Keep track of class aliases.
80603                 classAliases = [];
80604             }
80605         }
80606         /**
80607          * Hooks node substitutions.
80608          *
80609          * @param hint The context for the emitter.
80610          * @param node The node to substitute.
80611          */
80612         function onSubstituteNode(hint, node) {
80613             node = previousOnSubstituteNode(hint, node);
80614             if (hint === 1 /* Expression */) {
80615                 return substituteExpression(node);
80616             }
80617             return node;
80618         }
80619         function substituteExpression(node) {
80620             switch (node.kind) {
80621                 case 75 /* Identifier */:
80622                     return substituteExpressionIdentifier(node);
80623             }
80624             return node;
80625         }
80626         function substituteExpressionIdentifier(node) {
80627             return trySubstituteClassAlias(node) || node;
80628         }
80629         function trySubstituteClassAlias(node) {
80630             if (enabledSubstitutions & 1 /* ClassAliases */) {
80631                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
80632                     // Due to the emit for class decorators, any reference to the class from inside of the class body
80633                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
80634                     // behavior of class names in ES6.
80635                     // Also, when emitting statics for class expressions, we must substitute a class alias for
80636                     // constructor references in static property initializers.
80637                     var declaration = resolver.getReferencedValueDeclaration(node);
80638                     if (declaration) {
80639                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
80640                         if (classAlias) {
80641                             var clone_2 = ts.getSynthesizedClone(classAlias);
80642                             ts.setSourceMapRange(clone_2, node);
80643                             ts.setCommentRange(clone_2, node);
80644                             return clone_2;
80645                         }
80646                     }
80647                 }
80648             }
80649             return undefined;
80650         }
80651         /**
80652          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
80653          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
80654          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
80655          */
80656         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
80657             if (ts.isComputedPropertyName(name)) {
80658                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
80659                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
80660                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
80661                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
80662                 if (!alreadyTransformed && !inlinable && shouldHoist) {
80663                     var generatedName = ts.getGeneratedNameForNode(name);
80664                     hoistVariableDeclaration(generatedName);
80665                     return ts.createAssignment(generatedName, expression);
80666                 }
80667                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
80668             }
80669         }
80670         function startPrivateIdentifierEnvironment() {
80671             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
80672             currentPrivateIdentifierEnvironment = undefined;
80673         }
80674         function endPrivateIdentifierEnvironment() {
80675             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
80676         }
80677         function addPrivateIdentifierToEnvironment(name) {
80678             var text = ts.getTextOfPropertyName(name);
80679             var weakMapName = ts.createOptimisticUniqueName("_" + text.substring(1));
80680             weakMapName.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80681             hoistVariableDeclaration(weakMapName);
80682             (currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = ts.createUnderscoreEscapedMap()))
80683                 .set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
80684             (pendingExpressions || (pendingExpressions = [])).push(ts.createAssignment(weakMapName, ts.createNew(ts.createIdentifier("WeakMap"), 
80685             /*typeArguments*/ undefined, [])));
80686         }
80687         function accessPrivateIdentifier(name) {
80688             if (currentPrivateIdentifierEnvironment) {
80689                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
80690                 if (info) {
80691                     return info;
80692                 }
80693             }
80694             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
80695                 var env = privateIdentifierEnvironmentStack[i];
80696                 if (!env) {
80697                     continue;
80698                 }
80699                 var info = env.get(name.escapedText);
80700                 if (info) {
80701                     return info;
80702                 }
80703             }
80704             return undefined;
80705         }
80706         function wrapPrivateIdentifierForDestructuringTarget(node) {
80707             var parameter = ts.getGeneratedNameForNode(node);
80708             var info = accessPrivateIdentifier(node.name);
80709             if (!info) {
80710                 return ts.visitEachChild(node, visitor, context);
80711             }
80712             var receiver = node.expression;
80713             // We cannot copy `this` or `super` into the function because they will be bound
80714             // differently inside the function.
80715             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
80716                 receiver = ts.createTempVariable(hoistVariableDeclaration);
80717                 receiver.autoGenerateFlags |= 8 /* ReservedInNestedScopes */;
80718                 (pendingExpressions || (pendingExpressions = [])).push(ts.createBinary(receiver, 62 /* EqualsToken */, node.expression));
80719             }
80720             return ts.createPropertyAccess(
80721             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
80722             ts.createParen(ts.createObjectLiteral([
80723                 ts.createSetAccessor(
80724                 /*decorators*/ undefined, 
80725                 /*modifiers*/ undefined, "value", [ts.createParameter(
80726                     /*decorators*/ undefined, 
80727                     /*modifiers*/ undefined, 
80728                     /*dotDotDotToken*/ undefined, parameter, 
80729                     /*questionToken*/ undefined, 
80730                     /*type*/ undefined, 
80731                     /*initializer*/ undefined)], ts.createBlock([ts.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
80732             ])), "value");
80733         }
80734         function visitArrayAssignmentTarget(node) {
80735             var target = ts.getTargetOfBindingOrAssignmentElement(node);
80736             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80737                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80738                 if (ts.isAssignmentExpression(node)) {
80739                     return ts.updateBinary(node, wrapped, ts.visitNode(node.right, visitor, ts.isExpression), node.operatorToken);
80740                 }
80741                 else if (ts.isSpreadElement(node)) {
80742                     return ts.updateSpread(node, wrapped);
80743                 }
80744                 else {
80745                     return wrapped;
80746                 }
80747             }
80748             return ts.visitNode(node, visitorDestructuringTarget);
80749         }
80750         function visitObjectAssignmentTarget(node) {
80751             if (ts.isPropertyAssignment(node)) {
80752                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
80753                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
80754                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
80755                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
80756                     return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? ts.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
80757                 }
80758                 return ts.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
80759             }
80760             return ts.visitNode(node, visitor);
80761         }
80762         function visitAssignmentPattern(node) {
80763             if (ts.isArrayLiteralExpression(node)) {
80764                 // Transforms private names in destructuring assignment array bindings.
80765                 //
80766                 // Source:
80767                 // ([ this.#myProp ] = [ "hello" ]);
80768                 //
80769                 // Transformation:
80770                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
80771                 return ts.updateArrayLiteral(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
80772             }
80773             else {
80774                 // Transforms private names in destructuring assignment object bindings.
80775                 //
80776                 // Source:
80777                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
80778                 //
80779                 // Transformation:
80780                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
80781                 return ts.updateObjectLiteral(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
80782             }
80783         }
80784     }
80785     ts.transformClassFields = transformClassFields;
80786     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
80787         return ts.createCall(ts.createPropertyAccess(weakMapName, "set"), 
80788         /*typeArguments*/ undefined, [receiver, initializer || ts.createVoidZero()]);
80789     }
80790     ts.classPrivateFieldGetHelper = {
80791         name: "typescript:classPrivateFieldGet",
80792         scoped: false,
80793         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            };"
80794     };
80795     function createClassPrivateFieldGetHelper(context, receiver, privateField) {
80796         context.requestEmitHelper(ts.classPrivateFieldGetHelper);
80797         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldGet"), /* typeArguments */ undefined, [receiver, privateField]);
80798     }
80799     ts.classPrivateFieldSetHelper = {
80800         name: "typescript:classPrivateFieldSet",
80801         scoped: false,
80802         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            };"
80803     };
80804     function createClassPrivateFieldSetHelper(context, receiver, privateField, value) {
80805         context.requestEmitHelper(ts.classPrivateFieldSetHelper);
80806         return ts.createCall(ts.getUnscopedHelperName("__classPrivateFieldSet"), /* typeArguments */ undefined, [receiver, privateField, value]);
80807     }
80808 })(ts || (ts = {}));
80809 /*@internal*/
80810 var ts;
80811 (function (ts) {
80812     var ES2017SubstitutionFlags;
80813     (function (ES2017SubstitutionFlags) {
80814         /** Enables substitutions for async methods with `super` calls. */
80815         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
80816     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
80817     var ContextFlags;
80818     (function (ContextFlags) {
80819         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
80820         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
80821     })(ContextFlags || (ContextFlags = {}));
80822     function transformES2017(context) {
80823         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
80824         var resolver = context.getEmitResolver();
80825         var compilerOptions = context.getCompilerOptions();
80826         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
80827         /**
80828          * Keeps track of whether expression substitution has been enabled for specific edge cases.
80829          * They are persisted between each SourceFile transformation and should not be reset.
80830          */
80831         var enabledSubstitutions;
80832         /**
80833          * This keeps track of containers where `super` is valid, for use with
80834          * just-in-time substitution for `super` expressions inside of async methods.
80835          */
80836         var enclosingSuperContainerFlags = 0;
80837         var enclosingFunctionParameterNames;
80838         /**
80839          * Keeps track of property names accessed on super (`super.x`) within async functions.
80840          */
80841         var capturedSuperProperties;
80842         /** Whether the async function contains an element access on super (`super[x]`). */
80843         var hasSuperElementAccess;
80844         /** A set of node IDs for generated super accessors (variable statements). */
80845         var substitutedSuperAccessors = [];
80846         var contextFlags = 0;
80847         // Save the previous transformation hooks.
80848         var previousOnEmitNode = context.onEmitNode;
80849         var previousOnSubstituteNode = context.onSubstituteNode;
80850         // Set new transformation hooks.
80851         context.onEmitNode = onEmitNode;
80852         context.onSubstituteNode = onSubstituteNode;
80853         return ts.chainBundle(transformSourceFile);
80854         function transformSourceFile(node) {
80855             if (node.isDeclarationFile) {
80856                 return node;
80857             }
80858             setContextFlag(1 /* NonTopLevel */, false);
80859             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
80860             var visited = ts.visitEachChild(node, visitor, context);
80861             ts.addEmitHelpers(visited, context.readEmitHelpers());
80862             return visited;
80863         }
80864         function setContextFlag(flag, val) {
80865             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
80866         }
80867         function inContext(flags) {
80868             return (contextFlags & flags) !== 0;
80869         }
80870         function inTopLevelContext() {
80871             return !inContext(1 /* NonTopLevel */);
80872         }
80873         function inHasLexicalThisContext() {
80874             return inContext(2 /* HasLexicalThis */);
80875         }
80876         function doWithContext(flags, cb, value) {
80877             var contextFlagsToSet = flags & ~contextFlags;
80878             if (contextFlagsToSet) {
80879                 setContextFlag(contextFlagsToSet, /*val*/ true);
80880                 var result = cb(value);
80881                 setContextFlag(contextFlagsToSet, /*val*/ false);
80882                 return result;
80883             }
80884             return cb(value);
80885         }
80886         function visitDefault(node) {
80887             return ts.visitEachChild(node, visitor, context);
80888         }
80889         function visitor(node) {
80890             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
80891                 return node;
80892             }
80893             switch (node.kind) {
80894                 case 126 /* AsyncKeyword */:
80895                     // ES2017 async modifier should be elided for targets < ES2017
80896                     return undefined;
80897                 case 206 /* AwaitExpression */:
80898                     return visitAwaitExpression(node);
80899                 case 161 /* MethodDeclaration */:
80900                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
80901                 case 244 /* FunctionDeclaration */:
80902                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
80903                 case 201 /* FunctionExpression */:
80904                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
80905                 case 202 /* ArrowFunction */:
80906                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
80907                 case 194 /* PropertyAccessExpression */:
80908                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
80909                         capturedSuperProperties.set(node.name.escapedText, true);
80910                     }
80911                     return ts.visitEachChild(node, visitor, context);
80912                 case 195 /* ElementAccessExpression */:
80913                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
80914                         hasSuperElementAccess = true;
80915                     }
80916                     return ts.visitEachChild(node, visitor, context);
80917                 case 163 /* GetAccessor */:
80918                 case 164 /* SetAccessor */:
80919                 case 162 /* Constructor */:
80920                 case 245 /* ClassDeclaration */:
80921                 case 214 /* ClassExpression */:
80922                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
80923                 default:
80924                     return ts.visitEachChild(node, visitor, context);
80925             }
80926         }
80927         function asyncBodyVisitor(node) {
80928             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
80929                 switch (node.kind) {
80930                     case 225 /* VariableStatement */:
80931                         return visitVariableStatementInAsyncBody(node);
80932                     case 230 /* ForStatement */:
80933                         return visitForStatementInAsyncBody(node);
80934                     case 231 /* ForInStatement */:
80935                         return visitForInStatementInAsyncBody(node);
80936                     case 232 /* ForOfStatement */:
80937                         return visitForOfStatementInAsyncBody(node);
80938                     case 280 /* CatchClause */:
80939                         return visitCatchClauseInAsyncBody(node);
80940                     case 223 /* Block */:
80941                     case 237 /* SwitchStatement */:
80942                     case 251 /* CaseBlock */:
80943                     case 277 /* CaseClause */:
80944                     case 278 /* DefaultClause */:
80945                     case 240 /* TryStatement */:
80946                     case 228 /* DoStatement */:
80947                     case 229 /* WhileStatement */:
80948                     case 227 /* IfStatement */:
80949                     case 236 /* WithStatement */:
80950                     case 238 /* LabeledStatement */:
80951                         return ts.visitEachChild(node, asyncBodyVisitor, context);
80952                     default:
80953                         return ts.Debug.assertNever(node, "Unhandled node.");
80954                 }
80955             }
80956             return visitor(node);
80957         }
80958         function visitCatchClauseInAsyncBody(node) {
80959             var catchClauseNames = ts.createUnderscoreEscapedMap();
80960             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
80961             // names declared in a catch variable are block scoped
80962             var catchClauseUnshadowedNames;
80963             catchClauseNames.forEach(function (_, escapedName) {
80964                 if (enclosingFunctionParameterNames.has(escapedName)) {
80965                     if (!catchClauseUnshadowedNames) {
80966                         catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames);
80967                     }
80968                     catchClauseUnshadowedNames.delete(escapedName);
80969                 }
80970             });
80971             if (catchClauseUnshadowedNames) {
80972                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
80973                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
80974                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
80975                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
80976                 return result;
80977             }
80978             else {
80979                 return ts.visitEachChild(node, asyncBodyVisitor, context);
80980             }
80981         }
80982         function visitVariableStatementInAsyncBody(node) {
80983             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
80984                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
80985                 return expression ? ts.createExpressionStatement(expression) : undefined;
80986             }
80987             return ts.visitEachChild(node, visitor, context);
80988         }
80989         function visitForInStatementInAsyncBody(node) {
80990             return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer)
80991                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
80992                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
80993         }
80994         function visitForOfStatementInAsyncBody(node) {
80995             return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
80996                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
80997                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
80998         }
80999         function visitForStatementInAsyncBody(node) {
81000             var initializer = node.initializer; // TODO: GH#18217
81001             return ts.updateFor(node, isVariableDeclarationListWithCollidingName(initializer)
81002                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
81003                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock));
81004         }
81005         /**
81006          * Visits an AwaitExpression node.
81007          *
81008          * This function will be called any time a ES2017 await expression is encountered.
81009          *
81010          * @param node The node to visit.
81011          */
81012         function visitAwaitExpression(node) {
81013             // do not downlevel a top-level await as it is module syntax...
81014             if (inTopLevelContext()) {
81015                 return ts.visitEachChild(node, visitor, context);
81016             }
81017             return ts.setOriginalNode(ts.setTextRange(ts.createYield(
81018             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
81019         }
81020         /**
81021          * Visits a MethodDeclaration node.
81022          *
81023          * This function will be called when one of the following conditions are met:
81024          * - The node is marked as async
81025          *
81026          * @param node The node to visit.
81027          */
81028         function visitMethodDeclaration(node) {
81029             return ts.updateMethod(node, 
81030             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81031             /*questionToken*/ undefined, 
81032             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81033             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81034                 ? transformAsyncFunctionBody(node)
81035                 : ts.visitFunctionBody(node.body, visitor, context));
81036         }
81037         /**
81038          * Visits a FunctionDeclaration node.
81039          *
81040          * This function will be called when one of the following conditions are met:
81041          * - The node is marked async
81042          *
81043          * @param node The node to visit.
81044          */
81045         function visitFunctionDeclaration(node) {
81046             return ts.updateFunctionDeclaration(node, 
81047             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81048             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81049             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81050                 ? transformAsyncFunctionBody(node)
81051                 : ts.visitFunctionBody(node.body, visitor, context));
81052         }
81053         /**
81054          * Visits a FunctionExpression node.
81055          *
81056          * This function will be called when one of the following conditions are met:
81057          * - The node is marked async
81058          *
81059          * @param node The node to visit.
81060          */
81061         function visitFunctionExpression(node) {
81062             return ts.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
81063             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81064             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
81065                 ? transformAsyncFunctionBody(node)
81066                 : ts.visitFunctionBody(node.body, visitor, context));
81067         }
81068         /**
81069          * Visits an ArrowFunction.
81070          *
81071          * This function will be called when one of the following conditions are met:
81072          * - The node is marked async
81073          *
81074          * @param node The node to visit.
81075          */
81076         function visitArrowFunction(node) {
81077             return ts.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
81078             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81079             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
81080                 ? transformAsyncFunctionBody(node)
81081                 : ts.visitFunctionBody(node.body, visitor, context));
81082         }
81083         function recordDeclarationName(_a, names) {
81084             var name = _a.name;
81085             if (ts.isIdentifier(name)) {
81086                 names.set(name.escapedText, true);
81087             }
81088             else {
81089                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81090                     var element = _b[_i];
81091                     if (!ts.isOmittedExpression(element)) {
81092                         recordDeclarationName(element, names);
81093                     }
81094                 }
81095             }
81096         }
81097         function isVariableDeclarationListWithCollidingName(node) {
81098             return !!node
81099                 && ts.isVariableDeclarationList(node)
81100                 && !(node.flags & 3 /* BlockScoped */)
81101                 && node.declarations.some(collidesWithParameterName);
81102         }
81103         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
81104             hoistVariableDeclarationList(node);
81105             var variables = ts.getInitializedVariables(node);
81106             if (variables.length === 0) {
81107                 if (hasReceiver) {
81108                     return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
81109                 }
81110                 return undefined;
81111             }
81112             return ts.inlineExpressions(ts.map(variables, transformInitializedVariable));
81113         }
81114         function hoistVariableDeclarationList(node) {
81115             ts.forEach(node.declarations, hoistVariable);
81116         }
81117         function hoistVariable(_a) {
81118             var name = _a.name;
81119             if (ts.isIdentifier(name)) {
81120                 hoistVariableDeclaration(name);
81121             }
81122             else {
81123                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81124                     var element = _b[_i];
81125                     if (!ts.isOmittedExpression(element)) {
81126                         hoistVariable(element);
81127                     }
81128                 }
81129             }
81130         }
81131         function transformInitializedVariable(node) {
81132             var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node);
81133             return ts.visitNode(converted, visitor, ts.isExpression);
81134         }
81135         function collidesWithParameterName(_a) {
81136             var name = _a.name;
81137             if (ts.isIdentifier(name)) {
81138                 return enclosingFunctionParameterNames.has(name.escapedText);
81139             }
81140             else {
81141                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
81142                     var element = _b[_i];
81143                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
81144                         return true;
81145                     }
81146                 }
81147             }
81148             return false;
81149         }
81150         function transformAsyncFunctionBody(node) {
81151             resumeLexicalEnvironment();
81152             var original = ts.getOriginalNode(node, ts.isFunctionLike);
81153             var nodeType = original.type;
81154             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
81155             var isArrowFunction = node.kind === 202 /* ArrowFunction */;
81156             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
81157             // An async function is emit as an outer function that calls an inner
81158             // generator function. To preserve lexical bindings, we pass the current
81159             // `this` and `arguments` objects to `__awaiter`. The generator function
81160             // passed to `__awaiter` is executed inside of the callback to the
81161             // promise constructor.
81162             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
81163             enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap();
81164             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
81165                 var parameter = _a[_i];
81166                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
81167             }
81168             var savedCapturedSuperProperties = capturedSuperProperties;
81169             var savedHasSuperElementAccess = hasSuperElementAccess;
81170             if (!isArrowFunction) {
81171                 capturedSuperProperties = ts.createUnderscoreEscapedMap();
81172                 hasSuperElementAccess = false;
81173             }
81174             var result;
81175             if (!isArrowFunction) {
81176                 var statements = [];
81177                 var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
81178                 statements.push(ts.createReturn(createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
81179                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
81180                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
81181                 // This step isn't needed if we eventually transform this to ES5.
81182                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
81183                 if (emitSuperHelpers) {
81184                     enableSubstitutionForAsyncMethodsWithSuper();
81185                     if (ts.hasEntries(capturedSuperProperties)) {
81186                         var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
81187                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
81188                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
81189                     }
81190                 }
81191                 var block = ts.createBlock(statements, /*multiLine*/ true);
81192                 ts.setTextRange(block, node.body);
81193                 if (emitSuperHelpers && hasSuperElementAccess) {
81194                     // Emit helpers for super element access expressions (`super[x]`).
81195                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
81196                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
81197                     }
81198                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
81199                         ts.addEmitHelper(block, ts.asyncSuperHelper);
81200                     }
81201                 }
81202                 result = block;
81203             }
81204             else {
81205                 var expression = createAwaiterHelper(context, inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
81206                 var declarations = endLexicalEnvironment();
81207                 if (ts.some(declarations)) {
81208                     var block = ts.convertToFunctionBody(expression);
81209                     result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
81210                 }
81211                 else {
81212                     result = expression;
81213                 }
81214             }
81215             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
81216             if (!isArrowFunction) {
81217                 capturedSuperProperties = savedCapturedSuperProperties;
81218                 hasSuperElementAccess = savedHasSuperElementAccess;
81219             }
81220             return result;
81221         }
81222         function transformAsyncFunctionBodyWorker(body, start) {
81223             if (ts.isBlock(body)) {
81224                 return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
81225             }
81226             else {
81227                 return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
81228             }
81229         }
81230         function getPromiseConstructor(type) {
81231             var typeName = type && ts.getEntityNameFromTypeNode(type);
81232             if (typeName && ts.isEntityName(typeName)) {
81233                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
81234                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
81235                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
81236                     return typeName;
81237                 }
81238             }
81239             return undefined;
81240         }
81241         function enableSubstitutionForAsyncMethodsWithSuper() {
81242             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
81243                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
81244                 // We need to enable substitutions for call, property access, and element access
81245                 // if we need to rewrite super calls.
81246                 context.enableSubstitution(196 /* CallExpression */);
81247                 context.enableSubstitution(194 /* PropertyAccessExpression */);
81248                 context.enableSubstitution(195 /* ElementAccessExpression */);
81249                 // We need to be notified when entering and exiting declarations that bind super.
81250                 context.enableEmitNotification(245 /* ClassDeclaration */);
81251                 context.enableEmitNotification(161 /* MethodDeclaration */);
81252                 context.enableEmitNotification(163 /* GetAccessor */);
81253                 context.enableEmitNotification(164 /* SetAccessor */);
81254                 context.enableEmitNotification(162 /* Constructor */);
81255                 // We need to be notified when entering the generated accessor arrow functions.
81256                 context.enableEmitNotification(225 /* VariableStatement */);
81257             }
81258         }
81259         /**
81260          * Hook for node emit.
81261          *
81262          * @param hint A hint as to the intended usage of the node.
81263          * @param node The node to emit.
81264          * @param emit A callback used to emit the node in the printer.
81265          */
81266         function onEmitNode(hint, node, emitCallback) {
81267             // If we need to support substitutions for `super` in an async method,
81268             // we should track it here.
81269             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
81270                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
81271                 if (superContainerFlags !== enclosingSuperContainerFlags) {
81272                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81273                     enclosingSuperContainerFlags = superContainerFlags;
81274                     previousOnEmitNode(hint, node, emitCallback);
81275                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81276                     return;
81277                 }
81278             }
81279             // Disable substitution in the generated super accessor itself.
81280             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
81281                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
81282                 enclosingSuperContainerFlags = 0;
81283                 previousOnEmitNode(hint, node, emitCallback);
81284                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
81285                 return;
81286             }
81287             previousOnEmitNode(hint, node, emitCallback);
81288         }
81289         /**
81290          * Hooks node substitutions.
81291          *
81292          * @param hint A hint as to the intended usage of the node.
81293          * @param node The node to substitute.
81294          */
81295         function onSubstituteNode(hint, node) {
81296             node = previousOnSubstituteNode(hint, node);
81297             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
81298                 return substituteExpression(node);
81299             }
81300             return node;
81301         }
81302         function substituteExpression(node) {
81303             switch (node.kind) {
81304                 case 194 /* PropertyAccessExpression */:
81305                     return substitutePropertyAccessExpression(node);
81306                 case 195 /* ElementAccessExpression */:
81307                     return substituteElementAccessExpression(node);
81308                 case 196 /* CallExpression */:
81309                     return substituteCallExpression(node);
81310             }
81311             return node;
81312         }
81313         function substitutePropertyAccessExpression(node) {
81314             if (node.expression.kind === 102 /* SuperKeyword */) {
81315                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
81316             }
81317             return node;
81318         }
81319         function substituteElementAccessExpression(node) {
81320             if (node.expression.kind === 102 /* SuperKeyword */) {
81321                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
81322             }
81323             return node;
81324         }
81325         function substituteCallExpression(node) {
81326             var expression = node.expression;
81327             if (ts.isSuperProperty(expression)) {
81328                 var argumentExpression = ts.isPropertyAccessExpression(expression)
81329                     ? substitutePropertyAccessExpression(expression)
81330                     : substituteElementAccessExpression(expression);
81331                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
81332                 /*typeArguments*/ undefined, __spreadArrays([
81333                     ts.createThis()
81334                 ], node.arguments));
81335             }
81336             return node;
81337         }
81338         function isSuperContainer(node) {
81339             var kind = node.kind;
81340             return kind === 245 /* ClassDeclaration */
81341                 || kind === 162 /* Constructor */
81342                 || kind === 161 /* MethodDeclaration */
81343                 || kind === 163 /* GetAccessor */
81344                 || kind === 164 /* SetAccessor */;
81345         }
81346         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
81347             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
81348                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81349                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
81350             }
81351             else {
81352                 return ts.setTextRange(ts.createCall(ts.createFileLevelUniqueName("_superIndex"), 
81353                 /*typeArguments*/ undefined, [argumentExpression]), location);
81354             }
81355         }
81356     }
81357     ts.transformES2017 = transformES2017;
81358     /** Creates a variable named `_super` with accessor properties for the given property names. */
81359     function createSuperAccessVariableStatement(resolver, node, names) {
81360         // Create a variable declaration with a getter/setter (if binding) definition for each name:
81361         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
81362         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
81363         var accessors = [];
81364         names.forEach(function (_, key) {
81365             var name = ts.unescapeLeadingUnderscores(key);
81366             var getterAndSetter = [];
81367             getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(
81368             /* modifiers */ undefined, 
81369             /* typeParameters */ undefined, 
81370             /* parameters */ [], 
81371             /* type */ undefined, 
81372             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
81373             if (hasBinding) {
81374                 getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(
81375                 /* modifiers */ undefined, 
81376                 /* typeParameters */ undefined, 
81377                 /* parameters */ [
81378                     ts.createParameter(
81379                     /* decorators */ undefined, 
81380                     /* modifiers */ undefined, 
81381                     /* dotDotDotToken */ undefined, "v", 
81382                     /* questionToken */ undefined, 
81383                     /* type */ undefined, 
81384                     /* initializer */ undefined)
81385                 ], 
81386                 /* type */ undefined, 
81387                 /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v")))));
81388             }
81389             accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter)));
81390         });
81391         return ts.createVariableStatement(
81392         /* modifiers */ undefined, ts.createVariableDeclarationList([
81393             ts.createVariableDeclaration(ts.createFileLevelUniqueName("_super"), 
81394             /* type */ undefined, ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "create"), 
81395             /* typeArguments */ undefined, [
81396                 ts.createNull(),
81397                 ts.createObjectLiteral(accessors, /* multiline */ true)
81398             ]))
81399         ], 2 /* Const */));
81400     }
81401     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
81402     ts.awaiterHelper = {
81403         name: "typescript:awaiter",
81404         importName: "__awaiter",
81405         scoped: false,
81406         priority: 5,
81407         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            };"
81408     };
81409     function createAwaiterHelper(context, hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
81410         context.requestEmitHelper(ts.awaiterHelper);
81411         var generatorFunc = ts.createFunctionExpression(
81412         /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), 
81413         /*name*/ undefined, 
81414         /*typeParameters*/ undefined, 
81415         /*parameters*/ [], 
81416         /*type*/ undefined, body);
81417         // Mark this node as originally an async function
81418         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
81419         return ts.createCall(ts.getUnscopedHelperName("__awaiter"), 
81420         /*typeArguments*/ undefined, [
81421             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
81422             hasLexicalArguments ? ts.createIdentifier("arguments") : ts.createVoidZero(),
81423             promiseConstructor ? ts.createExpressionFromEntityName(promiseConstructor) : ts.createVoidZero(),
81424             generatorFunc
81425         ]);
81426     }
81427     ts.asyncSuperHelper = {
81428         name: "typescript:async-super",
81429         scoped: true,
81430         text: ts.helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
81431     };
81432     ts.advancedAsyncSuperHelper = {
81433         name: "typescript:advanced-async-super",
81434         scoped: true,
81435         text: ts.helperString(__makeTemplateObject(["\n            const ", " = (function (geti, seti) {\n                const cache = Object.create(null);\n                return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n            })(name => super[name], (name, value) => super[name] = value);"], ["\n            const ", " = (function (geti, seti) {\n                const cache = Object.create(null);\n                return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } });\n            })(name => super[name], (name, value) => super[name] = value);"]), "_superIndex")
81436     };
81437 })(ts || (ts = {}));
81438 /*@internal*/
81439 var ts;
81440 (function (ts) {
81441     var ESNextSubstitutionFlags;
81442     (function (ESNextSubstitutionFlags) {
81443         /** Enables substitutions for async methods with `super` calls. */
81444         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
81445     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
81446     // Facts we track as we traverse the tree
81447     var HierarchyFacts;
81448     (function (HierarchyFacts) {
81449         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
81450         //
81451         // Ancestor facts
81452         //
81453         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
81454         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
81455         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
81456         //
81457         // Ancestor masks
81458         //
81459         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
81460         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
81461         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
81462         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
81463         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
81464         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
81465         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
81466         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
81467         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
81468         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
81469     })(HierarchyFacts || (HierarchyFacts = {}));
81470     function transformES2018(context) {
81471         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
81472         var resolver = context.getEmitResolver();
81473         var compilerOptions = context.getCompilerOptions();
81474         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
81475         var previousOnEmitNode = context.onEmitNode;
81476         context.onEmitNode = onEmitNode;
81477         var previousOnSubstituteNode = context.onSubstituteNode;
81478         context.onSubstituteNode = onSubstituteNode;
81479         var exportedVariableStatement = false;
81480         var enabledSubstitutions;
81481         var enclosingFunctionFlags;
81482         var enclosingSuperContainerFlags = 0;
81483         var hierarchyFacts = 0;
81484         var currentSourceFile;
81485         var taggedTemplateStringDeclarations;
81486         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
81487         var capturedSuperProperties;
81488         /** Whether the async function contains an element access on super (`super[x]`). */
81489         var hasSuperElementAccess;
81490         /** A set of node IDs for generated super accessors. */
81491         var substitutedSuperAccessors = [];
81492         return ts.chainBundle(transformSourceFile);
81493         function affectsSubtree(excludeFacts, includeFacts) {
81494             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
81495         }
81496         /**
81497          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
81498          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
81499          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
81500          */
81501         function enterSubtree(excludeFacts, includeFacts) {
81502             var ancestorFacts = hierarchyFacts;
81503             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
81504             return ancestorFacts;
81505         }
81506         /**
81507          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
81508          * subtree.
81509          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
81510          */
81511         function exitSubtree(ancestorFacts) {
81512             hierarchyFacts = ancestorFacts;
81513         }
81514         function recordTaggedTemplateString(temp) {
81515             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
81516         }
81517         function transformSourceFile(node) {
81518             if (node.isDeclarationFile) {
81519                 return node;
81520             }
81521             currentSourceFile = node;
81522             var visited = visitSourceFile(node);
81523             ts.addEmitHelpers(visited, context.readEmitHelpers());
81524             currentSourceFile = undefined;
81525             taggedTemplateStringDeclarations = undefined;
81526             return visited;
81527         }
81528         function visitor(node) {
81529             return visitorWorker(node, /*noDestructuringValue*/ false);
81530         }
81531         function visitorNoDestructuringValue(node) {
81532             return visitorWorker(node, /*noDestructuringValue*/ true);
81533         }
81534         function visitorNoAsyncModifier(node) {
81535             if (node.kind === 126 /* AsyncKeyword */) {
81536                 return undefined;
81537             }
81538             return node;
81539         }
81540         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
81541             if (affectsSubtree(excludeFacts, includeFacts)) {
81542                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
81543                 var result = cb(value);
81544                 exitSubtree(ancestorFacts);
81545                 return result;
81546             }
81547             return cb(value);
81548         }
81549         function visitDefault(node) {
81550             return ts.visitEachChild(node, visitor, context);
81551         }
81552         function visitorWorker(node, noDestructuringValue) {
81553             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
81554                 return node;
81555             }
81556             switch (node.kind) {
81557                 case 206 /* AwaitExpression */:
81558                     return visitAwaitExpression(node);
81559                 case 212 /* YieldExpression */:
81560                     return visitYieldExpression(node);
81561                 case 235 /* ReturnStatement */:
81562                     return visitReturnStatement(node);
81563                 case 238 /* LabeledStatement */:
81564                     return visitLabeledStatement(node);
81565                 case 193 /* ObjectLiteralExpression */:
81566                     return visitObjectLiteralExpression(node);
81567                 case 209 /* BinaryExpression */:
81568                     return visitBinaryExpression(node, noDestructuringValue);
81569                 case 280 /* CatchClause */:
81570                     return visitCatchClause(node);
81571                 case 225 /* VariableStatement */:
81572                     return visitVariableStatement(node);
81573                 case 242 /* VariableDeclaration */:
81574                     return visitVariableDeclaration(node);
81575                 case 228 /* DoStatement */:
81576                 case 229 /* WhileStatement */:
81577                 case 231 /* ForInStatement */:
81578                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81579                 case 232 /* ForOfStatement */:
81580                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
81581                 case 230 /* ForStatement */:
81582                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81583                 case 205 /* VoidExpression */:
81584                     return visitVoidExpression(node);
81585                 case 162 /* Constructor */:
81586                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81587                 case 161 /* MethodDeclaration */:
81588                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81589                 case 163 /* GetAccessor */:
81590                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81591                 case 164 /* SetAccessor */:
81592                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81593                 case 244 /* FunctionDeclaration */:
81594                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81595                 case 201 /* FunctionExpression */:
81596                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81597                 case 202 /* ArrowFunction */:
81598                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
81599                 case 156 /* Parameter */:
81600                     return visitParameter(node);
81601                 case 226 /* ExpressionStatement */:
81602                     return visitExpressionStatement(node);
81603                 case 200 /* ParenthesizedExpression */:
81604                     return visitParenthesizedExpression(node, noDestructuringValue);
81605                 case 198 /* TaggedTemplateExpression */:
81606                     return visitTaggedTemplateExpression(node);
81607                 case 194 /* PropertyAccessExpression */:
81608                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 102 /* SuperKeyword */) {
81609                         capturedSuperProperties.set(node.name.escapedText, true);
81610                     }
81611                     return ts.visitEachChild(node, visitor, context);
81612                 case 195 /* ElementAccessExpression */:
81613                     if (capturedSuperProperties && node.expression.kind === 102 /* SuperKeyword */) {
81614                         hasSuperElementAccess = true;
81615                     }
81616                     return ts.visitEachChild(node, visitor, context);
81617                 case 245 /* ClassDeclaration */:
81618                 case 214 /* ClassExpression */:
81619                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
81620                 default:
81621                     return ts.visitEachChild(node, visitor, context);
81622             }
81623         }
81624         function visitAwaitExpression(node) {
81625             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81626                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.visitNode(node.expression, visitor, ts.isExpression))), 
81627                 /*location*/ node), node);
81628             }
81629             return ts.visitEachChild(node, visitor, context);
81630         }
81631         function visitYieldExpression(node) {
81632             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81633                 if (node.asteriskToken) {
81634                     var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81635                     return ts.setOriginalNode(ts.setTextRange(ts.createYield(createAwaitHelper(context, ts.updateYield(node, node.asteriskToken, createAsyncDelegatorHelper(context, createAsyncValuesHelper(context, expression, expression), expression)))), node), node);
81636                 }
81637                 return ts.setOriginalNode(ts.setTextRange(ts.createYield(createDownlevelAwait(node.expression
81638                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
81639                     : ts.createVoidZero())), node), node);
81640             }
81641             return ts.visitEachChild(node, visitor, context);
81642         }
81643         function visitReturnStatement(node) {
81644             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
81645                 return ts.updateReturn(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : ts.createVoidZero()));
81646             }
81647             return ts.visitEachChild(node, visitor, context);
81648         }
81649         function visitLabeledStatement(node) {
81650             if (enclosingFunctionFlags & 2 /* Async */) {
81651                 var statement = ts.unwrapInnermostStatementOfLabel(node);
81652                 if (statement.kind === 232 /* ForOfStatement */ && statement.awaitModifier) {
81653                     return visitForOfStatement(statement, node);
81654                 }
81655                 return ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node);
81656             }
81657             return ts.visitEachChild(node, visitor, context);
81658         }
81659         function chunkObjectLiteralElements(elements) {
81660             var chunkObject;
81661             var objects = [];
81662             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
81663                 var e = elements_4[_i];
81664                 if (e.kind === 283 /* SpreadAssignment */) {
81665                     if (chunkObject) {
81666                         objects.push(ts.createObjectLiteral(chunkObject));
81667                         chunkObject = undefined;
81668                     }
81669                     var target = e.expression;
81670                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
81671                 }
81672                 else {
81673                     chunkObject = ts.append(chunkObject, e.kind === 281 /* PropertyAssignment */
81674                         ? ts.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
81675                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
81676                 }
81677             }
81678             if (chunkObject) {
81679                 objects.push(ts.createObjectLiteral(chunkObject));
81680             }
81681             return objects;
81682         }
81683         function visitObjectLiteralExpression(node) {
81684             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81685                 // spread elements emit like so:
81686                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
81687                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
81688                 // If the first element is a spread element, then the first argument to __assign is {}:
81689                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
81690                 //
81691                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
81692                 // example:
81693                 //      var k = { a: 1, b: 2 };
81694                 //      var o = { a: 3, ...k, b: k.a++ };
81695                 //      // expected: { a: 1, b: 1 }
81696                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
81697                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
81698                 //
81699                 // This also occurs for spread elements, not just property assignments:
81700                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
81701                 //      var l = { c: 3 };
81702                 //      var o = { ...k, ...l };
81703                 //      // expected: { a: 1, b: 2, z: 9 }
81704                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
81705                 // end up with `{ a: 1, b: 2, c: 3 }`
81706                 var objects = chunkObjectLiteralElements(node.properties);
81707                 if (objects.length && objects[0].kind !== 193 /* ObjectLiteralExpression */) {
81708                     objects.unshift(ts.createObjectLiteral());
81709                 }
81710                 var expression = objects[0];
81711                 if (objects.length > 1) {
81712                     for (var i = 1; i < objects.length; i++) {
81713                         expression = createAssignHelper(context, [expression, objects[i]]);
81714                     }
81715                     return expression;
81716                 }
81717                 else {
81718                     return createAssignHelper(context, objects);
81719                 }
81720             }
81721             return ts.visitEachChild(node, visitor, context);
81722         }
81723         function visitExpressionStatement(node) {
81724             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81725         }
81726         function visitParenthesizedExpression(node, noDestructuringValue) {
81727             return ts.visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context);
81728         }
81729         function visitSourceFile(node) {
81730             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
81731                 0 /* StrictModeSourceFileIncludes */ :
81732                 1 /* SourceFileIncludes */);
81733             exportedVariableStatement = false;
81734             var visited = ts.visitEachChild(node, visitor, context);
81735             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
81736                 ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations))
81737             ]);
81738             var result = ts.updateSourceFileNode(visited, ts.setTextRange(ts.createNodeArray(statement), node.statements));
81739             exitSubtree(ancestorFacts);
81740             return result;
81741         }
81742         function visitTaggedTemplateExpression(node) {
81743             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
81744         }
81745         /**
81746          * Visits a BinaryExpression that contains a destructuring assignment.
81747          *
81748          * @param node A BinaryExpression node.
81749          */
81750         function visitBinaryExpression(node, noDestructuringValue) {
81751             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81752                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !noDestructuringValue);
81753             }
81754             else if (node.operatorToken.kind === 27 /* CommaToken */) {
81755                 return ts.updateBinary(node, ts.visitNode(node.left, visitorNoDestructuringValue, ts.isExpression), ts.visitNode(node.right, noDestructuringValue ? visitorNoDestructuringValue : visitor, ts.isExpression));
81756             }
81757             return ts.visitEachChild(node, visitor, context);
81758         }
81759         function visitCatchClause(node) {
81760             if (node.variableDeclaration &&
81761                 ts.isBindingPattern(node.variableDeclaration.name) &&
81762                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81763                 var name = ts.getGeneratedNameForNode(node.variableDeclaration.name);
81764                 var updatedDecl = ts.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*type*/ undefined, name);
81765                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
81766                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
81767                 if (ts.some(visitedBindings)) {
81768                     block = ts.updateBlock(block, __spreadArrays([
81769                         ts.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
81770                     ], block.statements));
81771                 }
81772                 return ts.updateCatchClause(node, ts.updateVariableDeclaration(node.variableDeclaration, name, /*type*/ undefined, /*initializer*/ undefined), block);
81773             }
81774             return ts.visitEachChild(node, visitor, context);
81775         }
81776         function visitVariableStatement(node) {
81777             if (ts.hasModifier(node, 1 /* Export */)) {
81778                 var savedExportedVariableStatement = exportedVariableStatement;
81779                 exportedVariableStatement = true;
81780                 var visited = ts.visitEachChild(node, visitor, context);
81781                 exportedVariableStatement = savedExportedVariableStatement;
81782                 return visited;
81783             }
81784             return ts.visitEachChild(node, visitor, context);
81785         }
81786         /**
81787          * Visits a VariableDeclaration node with a binding pattern.
81788          *
81789          * @param node A VariableDeclaration node.
81790          */
81791         function visitVariableDeclaration(node) {
81792             if (exportedVariableStatement) {
81793                 var savedExportedVariableStatement = exportedVariableStatement;
81794                 exportedVariableStatement = false;
81795                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
81796                 exportedVariableStatement = savedExportedVariableStatement;
81797                 return visited;
81798             }
81799             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
81800         }
81801         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
81802             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
81803             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81804                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
81805                 /*rval*/ undefined, exportedVariableStatement);
81806             }
81807             return ts.visitEachChild(node, visitor, context);
81808         }
81809         function visitForStatement(node) {
81810             return ts.updateFor(node, ts.visitNode(node.initializer, visitorNoDestructuringValue, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
81811         }
81812         function visitVoidExpression(node) {
81813             return ts.visitEachChild(node, visitorNoDestructuringValue, context);
81814         }
81815         /**
81816          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
81817          *
81818          * @param node A ForOfStatement.
81819          */
81820         function visitForOfStatement(node, outermostLabeledStatement) {
81821             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
81822             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81823                 node = transformForOfStatementWithObjectRest(node);
81824             }
81825             var result = node.awaitModifier ?
81826                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
81827                 ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
81828             exitSubtree(ancestorFacts);
81829             return result;
81830         }
81831         function transformForOfStatementWithObjectRest(node) {
81832             var initializerWithoutParens = ts.skipParentheses(node.initializer);
81833             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
81834                 var bodyLocation = void 0;
81835                 var statementsLocation = void 0;
81836                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
81837                 var statements = [ts.createForOfBindingStatement(initializerWithoutParens, temp)];
81838                 if (ts.isBlock(node.statement)) {
81839                     ts.addRange(statements, node.statement.statements);
81840                     bodyLocation = node.statement;
81841                     statementsLocation = node.statement.statements;
81842                 }
81843                 else if (node.statement) {
81844                     ts.append(statements, node.statement);
81845                     bodyLocation = node.statement;
81846                     statementsLocation = node.statement;
81847                 }
81848                 return ts.updateForOf(node, node.awaitModifier, ts.setTextRange(ts.createVariableDeclarationList([
81849                     ts.setTextRange(ts.createVariableDeclaration(temp), node.initializer)
81850                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81851                 /*multiLine*/ true), bodyLocation));
81852             }
81853             return node;
81854         }
81855         function convertForOfStatementHead(node, boundValue) {
81856             var binding = ts.createForOfBindingStatement(node.initializer, boundValue);
81857             var bodyLocation;
81858             var statementsLocation;
81859             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
81860             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
81861             if (ts.isBlock(statement)) {
81862                 ts.addRange(statements, statement.statements);
81863                 bodyLocation = statement;
81864                 statementsLocation = statement.statements;
81865             }
81866             else {
81867                 statements.push(statement);
81868             }
81869             return ts.setEmitFlags(ts.setTextRange(ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), 
81870             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
81871         }
81872         function createDownlevelAwait(expression) {
81873             return enclosingFunctionFlags & 1 /* Generator */
81874                 ? ts.createYield(/*asteriskToken*/ undefined, createAwaitHelper(context, expression))
81875                 : ts.createAwait(expression);
81876         }
81877         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
81878             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
81879             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81880             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
81881             var errorRecord = ts.createUniqueName("e");
81882             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
81883             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
81884             var callValues = createAsyncValuesHelper(context, expression, /*location*/ node.expression);
81885             var callNext = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
81886             var getDone = ts.createPropertyAccess(result, "done");
81887             var getValue = ts.createPropertyAccess(result, "value");
81888             var callReturn = ts.createFunctionCall(returnMethod, iterator, []);
81889             hoistVariableDeclaration(errorRecord);
81890             hoistVariableDeclaration(returnMethod);
81891             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
81892             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
81893                 ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), callValues]) :
81894                 callValues;
81895             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
81896             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
81897                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
81898                 ts.createVariableDeclaration(result)
81899             ]), node.expression), 2097152 /* NoHoisting */), 
81900             /*condition*/ ts.createComma(ts.createAssignment(result, createDownlevelAwait(callNext)), ts.createLogicalNot(getDone)), 
81901             /*incrementor*/ undefined, 
81902             /*statement*/ convertForOfStatementHead(node, getValue)), 
81903             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
81904             return ts.createTry(ts.createBlock([
81905                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
81906             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
81907                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
81908                     ts.createPropertyAssignment("error", catchVariable)
81909                 ])))
81910             ]), 1 /* SingleLine */)), ts.createBlock([
81911                 ts.createTry(
81912                 /*tryBlock*/ ts.createBlock([
81913                     ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(getDone)), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)
81914                 ]), 
81915                 /*catchClause*/ undefined, 
81916                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
81917                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
81918                 ]), 1 /* SingleLine */))
81919             ]));
81920         }
81921         function visitParameter(node) {
81922             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
81923                 // Binding patterns are converted into a generated name and are
81924                 // evaluated inside the function body.
81925                 return ts.updateParameter(node, 
81926                 /*decorators*/ undefined, 
81927                 /*modifiers*/ undefined, node.dotDotDotToken, ts.getGeneratedNameForNode(node), 
81928                 /*questionToken*/ undefined, 
81929                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
81930             }
81931             return ts.visitEachChild(node, visitor, context);
81932         }
81933         function visitConstructorDeclaration(node) {
81934             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81935             enclosingFunctionFlags = 0 /* Normal */;
81936             var updated = ts.updateConstructor(node, 
81937             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81938             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81939             return updated;
81940         }
81941         function visitGetAccessorDeclaration(node) {
81942             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81943             enclosingFunctionFlags = 0 /* Normal */;
81944             var updated = ts.updateGetAccessor(node, 
81945             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
81946             /*type*/ undefined, transformFunctionBody(node));
81947             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81948             return updated;
81949         }
81950         function visitSetAccessorDeclaration(node) {
81951             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81952             enclosingFunctionFlags = 0 /* Normal */;
81953             var updated = ts.updateSetAccessor(node, 
81954             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
81955             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81956             return updated;
81957         }
81958         function visitMethodDeclaration(node) {
81959             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81960             enclosingFunctionFlags = ts.getFunctionFlags(node);
81961             var updated = ts.updateMethod(node, 
81962             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81963                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81964                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81965                 ? undefined
81966                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
81967             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81968             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81969                 ? transformAsyncGeneratorFunctionBody(node)
81970                 : transformFunctionBody(node));
81971             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81972             return updated;
81973         }
81974         function visitFunctionDeclaration(node) {
81975             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81976             enclosingFunctionFlags = ts.getFunctionFlags(node);
81977             var updated = ts.updateFunctionDeclaration(node, 
81978             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
81979                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
81980                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
81981                 ? undefined
81982                 : node.asteriskToken, node.name, 
81983             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81984             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
81985                 ? transformAsyncGeneratorFunctionBody(node)
81986                 : transformFunctionBody(node));
81987             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81988             return updated;
81989         }
81990         function visitArrowFunction(node) {
81991             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
81992             enclosingFunctionFlags = ts.getFunctionFlags(node);
81993             var updated = ts.updateArrowFunction(node, node.modifiers, 
81994             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
81995             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
81996             enclosingFunctionFlags = savedEnclosingFunctionFlags;
81997             return updated;
81998         }
81999         function visitFunctionExpression(node) {
82000             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
82001             enclosingFunctionFlags = ts.getFunctionFlags(node);
82002             var updated = ts.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
82003                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
82004                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
82005                 ? undefined
82006                 : node.asteriskToken, node.name, 
82007             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
82008             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
82009                 ? transformAsyncGeneratorFunctionBody(node)
82010                 : transformFunctionBody(node));
82011             enclosingFunctionFlags = savedEnclosingFunctionFlags;
82012             return updated;
82013         }
82014         function transformAsyncGeneratorFunctionBody(node) {
82015             resumeLexicalEnvironment();
82016             var statements = [];
82017             var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor);
82018             appendObjectRestAssignmentsIfNeeded(statements, node);
82019             var savedCapturedSuperProperties = capturedSuperProperties;
82020             var savedHasSuperElementAccess = hasSuperElementAccess;
82021             capturedSuperProperties = ts.createUnderscoreEscapedMap();
82022             hasSuperElementAccess = false;
82023             var returnStatement = ts.createReturn(createAsyncGeneratorHelper(context, ts.createFunctionExpression(
82024             /*modifiers*/ undefined, ts.createToken(41 /* AsteriskToken */), node.name && ts.getGeneratedNameForNode(node.name), 
82025             /*typeParameters*/ undefined, 
82026             /*parameters*/ [], 
82027             /*type*/ undefined, ts.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
82028             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
82029             // This step isn't needed if we eventually transform this to ES5.
82030             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
82031             if (emitSuperHelpers) {
82032                 enableSubstitutionForAsyncMethodsWithSuper();
82033                 var variableStatement = ts.createSuperAccessVariableStatement(resolver, node, capturedSuperProperties);
82034                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
82035                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
82036             }
82037             statements.push(returnStatement);
82038             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
82039             var block = ts.updateBlock(node.body, statements);
82040             if (emitSuperHelpers && hasSuperElementAccess) {
82041                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
82042                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
82043                 }
82044                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
82045                     ts.addEmitHelper(block, ts.asyncSuperHelper);
82046                 }
82047             }
82048             capturedSuperProperties = savedCapturedSuperProperties;
82049             hasSuperElementAccess = savedHasSuperElementAccess;
82050             return block;
82051         }
82052         function transformFunctionBody(node) {
82053             resumeLexicalEnvironment();
82054             var statementOffset = 0;
82055             var statements = [];
82056             var body = ts.visitNode(node.body, visitor, ts.isConciseBody);
82057             if (ts.isBlock(body)) {
82058                 statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
82059             }
82060             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
82061             var leadingStatements = endLexicalEnvironment();
82062             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
82063                 var block = ts.convertToFunctionBody(body, /*multiLine*/ true);
82064                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
82065                 ts.addRange(statements, block.statements.slice(statementOffset));
82066                 return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(statements), block.statements));
82067             }
82068             return body;
82069         }
82070         function appendObjectRestAssignmentsIfNeeded(statements, node) {
82071             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
82072                 var parameter = _a[_i];
82073                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
82074                     var temp = ts.getGeneratedNameForNode(parameter);
82075                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
82076                     /*doNotRecordTempVariablesInLine*/ false, 
82077                     /*skipInitializer*/ true);
82078                     if (ts.some(declarations)) {
82079                         var statement = ts.createVariableStatement(
82080                         /*modifiers*/ undefined, ts.createVariableDeclarationList(declarations));
82081                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
82082                         statements = ts.append(statements, statement);
82083                     }
82084                 }
82085             }
82086             return statements;
82087         }
82088         function enableSubstitutionForAsyncMethodsWithSuper() {
82089             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
82090                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
82091                 // We need to enable substitutions for call, property access, and element access
82092                 // if we need to rewrite super calls.
82093                 context.enableSubstitution(196 /* CallExpression */);
82094                 context.enableSubstitution(194 /* PropertyAccessExpression */);
82095                 context.enableSubstitution(195 /* ElementAccessExpression */);
82096                 // We need to be notified when entering and exiting declarations that bind super.
82097                 context.enableEmitNotification(245 /* ClassDeclaration */);
82098                 context.enableEmitNotification(161 /* MethodDeclaration */);
82099                 context.enableEmitNotification(163 /* GetAccessor */);
82100                 context.enableEmitNotification(164 /* SetAccessor */);
82101                 context.enableEmitNotification(162 /* Constructor */);
82102                 // We need to be notified when entering the generated accessor arrow functions.
82103                 context.enableEmitNotification(225 /* VariableStatement */);
82104             }
82105         }
82106         /**
82107          * Called by the printer just before a node is printed.
82108          *
82109          * @param hint A hint as to the intended usage of the node.
82110          * @param node The node to be printed.
82111          * @param emitCallback The callback used to emit the node.
82112          */
82113         function onEmitNode(hint, node, emitCallback) {
82114             // If we need to support substitutions for `super` in an async method,
82115             // we should track it here.
82116             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
82117                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
82118                 if (superContainerFlags !== enclosingSuperContainerFlags) {
82119                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82120                     enclosingSuperContainerFlags = superContainerFlags;
82121                     previousOnEmitNode(hint, node, emitCallback);
82122                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82123                     return;
82124                 }
82125             }
82126             // Disable substitution in the generated super accessor itself.
82127             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
82128                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
82129                 enclosingSuperContainerFlags = 0;
82130                 previousOnEmitNode(hint, node, emitCallback);
82131                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
82132                 return;
82133             }
82134             previousOnEmitNode(hint, node, emitCallback);
82135         }
82136         /**
82137          * Hooks node substitutions.
82138          *
82139          * @param hint The context for the emitter.
82140          * @param node The node to substitute.
82141          */
82142         function onSubstituteNode(hint, node) {
82143             node = previousOnSubstituteNode(hint, node);
82144             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
82145                 return substituteExpression(node);
82146             }
82147             return node;
82148         }
82149         function substituteExpression(node) {
82150             switch (node.kind) {
82151                 case 194 /* PropertyAccessExpression */:
82152                     return substitutePropertyAccessExpression(node);
82153                 case 195 /* ElementAccessExpression */:
82154                     return substituteElementAccessExpression(node);
82155                 case 196 /* CallExpression */:
82156                     return substituteCallExpression(node);
82157             }
82158             return node;
82159         }
82160         function substitutePropertyAccessExpression(node) {
82161             if (node.expression.kind === 102 /* SuperKeyword */) {
82162                 return ts.setTextRange(ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), node.name), node);
82163             }
82164             return node;
82165         }
82166         function substituteElementAccessExpression(node) {
82167             if (node.expression.kind === 102 /* SuperKeyword */) {
82168                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
82169             }
82170             return node;
82171         }
82172         function substituteCallExpression(node) {
82173             var expression = node.expression;
82174             if (ts.isSuperProperty(expression)) {
82175                 var argumentExpression = ts.isPropertyAccessExpression(expression)
82176                     ? substitutePropertyAccessExpression(expression)
82177                     : substituteElementAccessExpression(expression);
82178                 return ts.createCall(ts.createPropertyAccess(argumentExpression, "call"), 
82179                 /*typeArguments*/ undefined, __spreadArrays([
82180                     ts.createThis()
82181                 ], node.arguments));
82182             }
82183             return node;
82184         }
82185         function isSuperContainer(node) {
82186             var kind = node.kind;
82187             return kind === 245 /* ClassDeclaration */
82188                 || kind === 162 /* Constructor */
82189                 || kind === 161 /* MethodDeclaration */
82190                 || kind === 163 /* GetAccessor */
82191                 || kind === 164 /* SetAccessor */;
82192         }
82193         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
82194             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
82195                 return ts.setTextRange(ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_superIndex"), 
82196                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
82197             }
82198             else {
82199                 return ts.setTextRange(ts.createCall(ts.createIdentifier("_superIndex"), 
82200                 /*typeArguments*/ undefined, [argumentExpression]), location);
82201             }
82202         }
82203     }
82204     ts.transformES2018 = transformES2018;
82205     ts.assignHelper = {
82206         name: "typescript:assign",
82207         importName: "__assign",
82208         scoped: false,
82209         priority: 1,
82210         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            };"
82211     };
82212     function createAssignHelper(context, attributesSegments) {
82213         if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
82214             return ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "assign"), /*typeArguments*/ undefined, attributesSegments);
82215         }
82216         context.requestEmitHelper(ts.assignHelper);
82217         return ts.createCall(ts.getUnscopedHelperName("__assign"), 
82218         /*typeArguments*/ undefined, attributesSegments);
82219     }
82220     ts.createAssignHelper = createAssignHelper;
82221     ts.awaitHelper = {
82222         name: "typescript:await",
82223         importName: "__await",
82224         scoped: false,
82225         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
82226     };
82227     function createAwaitHelper(context, expression) {
82228         context.requestEmitHelper(ts.awaitHelper);
82229         return ts.createCall(ts.getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
82230     }
82231     ts.asyncGeneratorHelper = {
82232         name: "typescript:asyncGenerator",
82233         importName: "__asyncGenerator",
82234         scoped: false,
82235         dependencies: [ts.awaitHelper],
82236         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            };"
82237     };
82238     function createAsyncGeneratorHelper(context, generatorFunc, hasLexicalThis) {
82239         context.requestEmitHelper(ts.asyncGeneratorHelper);
82240         // Mark this node as originally an async function
82241         (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
82242         return ts.createCall(ts.getUnscopedHelperName("__asyncGenerator"), 
82243         /*typeArguments*/ undefined, [
82244             hasLexicalThis ? ts.createThis() : ts.createVoidZero(),
82245             ts.createIdentifier("arguments"),
82246             generatorFunc
82247         ]);
82248     }
82249     ts.asyncDelegator = {
82250         name: "typescript:asyncDelegator",
82251         importName: "__asyncDelegator",
82252         scoped: false,
82253         dependencies: [ts.awaitHelper],
82254         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            };"
82255     };
82256     function createAsyncDelegatorHelper(context, expression, location) {
82257         context.requestEmitHelper(ts.asyncDelegator);
82258         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncDelegator"), 
82259         /*typeArguments*/ undefined, [expression]), location);
82260     }
82261     ts.asyncValues = {
82262         name: "typescript:asyncValues",
82263         importName: "__asyncValues",
82264         scoped: false,
82265         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            };"
82266     };
82267     function createAsyncValuesHelper(context, expression, location) {
82268         context.requestEmitHelper(ts.asyncValues);
82269         return ts.setTextRange(ts.createCall(ts.getUnscopedHelperName("__asyncValues"), 
82270         /*typeArguments*/ undefined, [expression]), location);
82271     }
82272 })(ts || (ts = {}));
82273 /*@internal*/
82274 var ts;
82275 (function (ts) {
82276     function transformES2019(context) {
82277         return ts.chainBundle(transformSourceFile);
82278         function transformSourceFile(node) {
82279             if (node.isDeclarationFile) {
82280                 return node;
82281             }
82282             return ts.visitEachChild(node, visitor, context);
82283         }
82284         function visitor(node) {
82285             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
82286                 return node;
82287             }
82288             switch (node.kind) {
82289                 case 280 /* CatchClause */:
82290                     return visitCatchClause(node);
82291                 default:
82292                     return ts.visitEachChild(node, visitor, context);
82293             }
82294         }
82295         function visitCatchClause(node) {
82296             if (!node.variableDeclaration) {
82297                 return ts.updateCatchClause(node, ts.createVariableDeclaration(ts.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
82298             }
82299             return ts.visitEachChild(node, visitor, context);
82300         }
82301     }
82302     ts.transformES2019 = transformES2019;
82303 })(ts || (ts = {}));
82304 /*@internal*/
82305 var ts;
82306 (function (ts) {
82307     function transformES2020(context) {
82308         var hoistVariableDeclaration = context.hoistVariableDeclaration;
82309         return ts.chainBundle(transformSourceFile);
82310         function transformSourceFile(node) {
82311             if (node.isDeclarationFile) {
82312                 return node;
82313             }
82314             return ts.visitEachChild(node, visitor, context);
82315         }
82316         function visitor(node) {
82317             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
82318                 return node;
82319             }
82320             switch (node.kind) {
82321                 case 194 /* PropertyAccessExpression */:
82322                 case 195 /* ElementAccessExpression */:
82323                 case 196 /* CallExpression */:
82324                     if (node.flags & 32 /* OptionalChain */) {
82325                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
82326                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
82327                         return updated;
82328                     }
82329                     return ts.visitEachChild(node, visitor, context);
82330                 case 209 /* BinaryExpression */:
82331                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
82332                         return transformNullishCoalescingExpression(node);
82333                     }
82334                     return ts.visitEachChild(node, visitor, context);
82335                 case 203 /* DeleteExpression */:
82336                     return visitDeleteExpression(node);
82337                 default:
82338                     return ts.visitEachChild(node, visitor, context);
82339             }
82340         }
82341         function flattenChain(chain) {
82342             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82343             var links = [chain];
82344             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
82345                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
82346                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
82347                 links.unshift(chain);
82348             }
82349             return { expression: chain.expression, chain: links };
82350         }
82351         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
82352             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
82353             if (ts.isSyntheticReference(expression)) {
82354                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
82355                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
82356                 return ts.createSyntheticReferenceExpression(ts.updateParen(node, expression.expression), expression.thisArg);
82357             }
82358             return ts.updateParen(node, expression);
82359         }
82360         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
82361             if (ts.isOptionalChain(node)) {
82362                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82363                 return visitOptionalExpression(node, captureThisArg, isDelete);
82364             }
82365             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
82366             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
82367             var thisArg;
82368             if (captureThisArg) {
82369                 if (shouldCaptureInTempVariable(expression)) {
82370                     thisArg = ts.createTempVariable(hoistVariableDeclaration);
82371                     expression = ts.createAssignment(thisArg, expression);
82372                     // if (inParameterInitializer) tempVariableInParameter = true;
82373                 }
82374                 else {
82375                     thisArg = expression;
82376                 }
82377             }
82378             expression = node.kind === 194 /* PropertyAccessExpression */
82379                 ? ts.updatePropertyAccess(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
82380                 : ts.updateElementAccess(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
82381             return thisArg ? ts.createSyntheticReferenceExpression(expression, thisArg) : expression;
82382         }
82383         function visitNonOptionalCallExpression(node, captureThisArg) {
82384             if (ts.isOptionalChain(node)) {
82385                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
82386                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
82387             }
82388             return ts.visitEachChild(node, visitor, context);
82389         }
82390         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
82391             switch (node.kind) {
82392                 case 200 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
82393                 case 194 /* PropertyAccessExpression */:
82394                 case 195 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
82395                 case 196 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
82396                 default: return ts.visitNode(node, visitor, ts.isExpression);
82397             }
82398         }
82399         function visitOptionalExpression(node, captureThisArg, isDelete) {
82400             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
82401             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
82402             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
82403             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
82404             var capturedLeft = leftExpression;
82405             if (shouldCaptureInTempVariable(leftExpression)) {
82406                 capturedLeft = ts.createTempVariable(hoistVariableDeclaration);
82407                 leftExpression = ts.createAssignment(capturedLeft, leftExpression);
82408                 // if (inParameterInitializer) tempVariableInParameter = true;
82409             }
82410             var rightExpression = capturedLeft;
82411             var thisArg;
82412             for (var i = 0; i < chain.length; i++) {
82413                 var segment = chain[i];
82414                 switch (segment.kind) {
82415                     case 194 /* PropertyAccessExpression */:
82416                     case 195 /* ElementAccessExpression */:
82417                         if (i === chain.length - 1 && captureThisArg) {
82418                             if (shouldCaptureInTempVariable(rightExpression)) {
82419                                 thisArg = ts.createTempVariable(hoistVariableDeclaration);
82420                                 rightExpression = ts.createAssignment(thisArg, rightExpression);
82421                                 // if (inParameterInitializer) tempVariableInParameter = true;
82422                             }
82423                             else {
82424                                 thisArg = rightExpression;
82425                             }
82426                         }
82427                         rightExpression = segment.kind === 194 /* PropertyAccessExpression */
82428                             ? ts.createPropertyAccess(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
82429                             : ts.createElementAccess(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
82430                         break;
82431                     case 196 /* CallExpression */:
82432                         if (i === 0 && leftThisArg) {
82433                             rightExpression = ts.createFunctionCall(rightExpression, leftThisArg.kind === 102 /* SuperKeyword */ ? ts.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82434                         }
82435                         else {
82436                             rightExpression = ts.createCall(rightExpression, 
82437                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
82438                         }
82439                         break;
82440                 }
82441                 ts.setOriginalNode(rightExpression, segment);
82442             }
82443             var target = isDelete
82444                 ? ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createTrue(), ts.createDelete(rightExpression))
82445                 : ts.createConditional(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), ts.createVoidZero(), rightExpression);
82446             return thisArg ? ts.createSyntheticReferenceExpression(target, thisArg) : target;
82447         }
82448         function createNotNullCondition(left, right, invert) {
82449             return ts.createBinary(ts.createBinary(left, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createNull()), ts.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), ts.createBinary(right, ts.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), ts.createVoidZero()));
82450         }
82451         function transformNullishCoalescingExpression(node) {
82452             var left = ts.visitNode(node.left, visitor, ts.isExpression);
82453             var right = left;
82454             if (shouldCaptureInTempVariable(left)) {
82455                 right = ts.createTempVariable(hoistVariableDeclaration);
82456                 left = ts.createAssignment(right, left);
82457                 // if (inParameterInitializer) tempVariableInParameter = true;
82458             }
82459             return ts.createConditional(createNotNullCondition(left, right), right, ts.visitNode(node.right, visitor, ts.isExpression));
82460         }
82461         function shouldCaptureInTempVariable(expression) {
82462             // don't capture identifiers and `this` in a temporary variable
82463             // `super` cannot be captured as it's no real variable
82464             return !ts.isIdentifier(expression) &&
82465                 expression.kind !== 104 /* ThisKeyword */ &&
82466                 expression.kind !== 102 /* SuperKeyword */;
82467         }
82468         function visitDeleteExpression(node) {
82469             return ts.isOptionalChain(ts.skipParentheses(node.expression))
82470                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
82471                 : ts.updateDelete(node, ts.visitNode(node.expression, visitor, ts.isExpression));
82472         }
82473     }
82474     ts.transformES2020 = transformES2020;
82475 })(ts || (ts = {}));
82476 /*@internal*/
82477 var ts;
82478 (function (ts) {
82479     function transformESNext(context) {
82480         return ts.chainBundle(transformSourceFile);
82481         function transformSourceFile(node) {
82482             if (node.isDeclarationFile) {
82483                 return node;
82484             }
82485             return ts.visitEachChild(node, visitor, context);
82486         }
82487         function visitor(node) {
82488             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
82489                 return node;
82490             }
82491             switch (node.kind) {
82492                 default:
82493                     return ts.visitEachChild(node, visitor, context);
82494             }
82495         }
82496     }
82497     ts.transformESNext = transformESNext;
82498 })(ts || (ts = {}));
82499 /*@internal*/
82500 var ts;
82501 (function (ts) {
82502     function transformJsx(context) {
82503         var compilerOptions = context.getCompilerOptions();
82504         var currentSourceFile;
82505         return ts.chainBundle(transformSourceFile);
82506         /**
82507          * Transform JSX-specific syntax in a SourceFile.
82508          *
82509          * @param node A SourceFile node.
82510          */
82511         function transformSourceFile(node) {
82512             if (node.isDeclarationFile) {
82513                 return node;
82514             }
82515             currentSourceFile = node;
82516             var visited = ts.visitEachChild(node, visitor, context);
82517             ts.addEmitHelpers(visited, context.readEmitHelpers());
82518             return visited;
82519         }
82520         function visitor(node) {
82521             if (node.transformFlags & 2 /* ContainsJsx */) {
82522                 return visitorWorker(node);
82523             }
82524             else {
82525                 return node;
82526             }
82527         }
82528         function visitorWorker(node) {
82529             switch (node.kind) {
82530                 case 266 /* JsxElement */:
82531                     return visitJsxElement(node, /*isChild*/ false);
82532                 case 267 /* JsxSelfClosingElement */:
82533                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
82534                 case 270 /* JsxFragment */:
82535                     return visitJsxFragment(node, /*isChild*/ false);
82536                 case 276 /* JsxExpression */:
82537                     return visitJsxExpression(node);
82538                 default:
82539                     return ts.visitEachChild(node, visitor, context);
82540             }
82541         }
82542         function transformJsxChildToExpression(node) {
82543             switch (node.kind) {
82544                 case 11 /* JsxText */:
82545                     return visitJsxText(node);
82546                 case 276 /* JsxExpression */:
82547                     return visitJsxExpression(node);
82548                 case 266 /* JsxElement */:
82549                     return visitJsxElement(node, /*isChild*/ true);
82550                 case 267 /* JsxSelfClosingElement */:
82551                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
82552                 case 270 /* JsxFragment */:
82553                     return visitJsxFragment(node, /*isChild*/ true);
82554                 default:
82555                     return ts.Debug.failBadSyntaxKind(node);
82556             }
82557         }
82558         function visitJsxElement(node, isChild) {
82559             return visitJsxOpeningLikeElement(node.openingElement, node.children, isChild, /*location*/ node);
82560         }
82561         function visitJsxSelfClosingElement(node, isChild) {
82562             return visitJsxOpeningLikeElement(node, /*children*/ undefined, isChild, /*location*/ node);
82563         }
82564         function visitJsxFragment(node, isChild) {
82565             return visitJsxOpeningFragment(node.openingFragment, node.children, isChild, /*location*/ node);
82566         }
82567         function visitJsxOpeningLikeElement(node, children, isChild, location) {
82568             var tagName = getTagName(node);
82569             var objectProperties;
82570             var attrs = node.attributes.properties;
82571             if (attrs.length === 0) {
82572                 // When there are no attributes, React wants "null"
82573                 objectProperties = ts.createNull();
82574             }
82575             else {
82576                 // Map spans of JsxAttribute nodes into object literals and spans
82577                 // of JsxSpreadAttribute nodes into expressions.
82578                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
82579                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
82580                     : ts.createObjectLiteral(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
82581                 if (ts.isJsxSpreadAttribute(attrs[0])) {
82582                     // We must always emit at least one object literal before a spread
82583                     // argument.
82584                     segments.unshift(ts.createObjectLiteral());
82585                 }
82586                 // Either emit one big object literal (no spread attribs), or
82587                 // a call to the __assign helper.
82588                 objectProperties = ts.singleOrUndefined(segments);
82589                 if (!objectProperties) {
82590                     objectProperties = ts.createAssignHelper(context, segments);
82591                 }
82592             }
82593             var element = ts.createExpressionForJsxElement(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82594             tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), node, location);
82595             if (isChild) {
82596                 ts.startOnNewLine(element);
82597             }
82598             return element;
82599         }
82600         function visitJsxOpeningFragment(node, children, isChild, location) {
82601             var element = ts.createExpressionForJsxFragment(context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
82602             ts.mapDefined(children, transformJsxChildToExpression), node, location);
82603             if (isChild) {
82604                 ts.startOnNewLine(element);
82605             }
82606             return element;
82607         }
82608         function transformJsxSpreadAttributeToExpression(node) {
82609             return ts.visitNode(node.expression, visitor, ts.isExpression);
82610         }
82611         function transformJsxAttributeToObjectLiteralElement(node) {
82612             var name = getAttributeName(node);
82613             var expression = transformJsxAttributeInitializer(node.initializer);
82614             return ts.createPropertyAssignment(name, expression);
82615         }
82616         function transformJsxAttributeInitializer(node) {
82617             if (node === undefined) {
82618                 return ts.createTrue();
82619             }
82620             else if (node.kind === 10 /* StringLiteral */) {
82621                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
82622                 // Need to be escaped to be handled correctly in a normal string
82623                 var literal = ts.createLiteral(tryDecodeEntities(node.text) || node.text);
82624                 literal.singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
82625                 return ts.setTextRange(literal, node);
82626             }
82627             else if (node.kind === 276 /* JsxExpression */) {
82628                 if (node.expression === undefined) {
82629                     return ts.createTrue();
82630                 }
82631                 return visitJsxExpression(node);
82632             }
82633             else {
82634                 return ts.Debug.failBadSyntaxKind(node);
82635             }
82636         }
82637         function visitJsxText(node) {
82638             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
82639             return fixed === undefined ? undefined : ts.createLiteral(fixed);
82640         }
82641         /**
82642          * JSX trims whitespace at the end and beginning of lines, except that the
82643          * start/end of a tag is considered a start/end of a line only if that line is
82644          * on the same line as the closing tag. See examples in
82645          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
82646          * 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
82647          *
82648          * An equivalent algorithm would be:
82649          * - If there is only one line, return it.
82650          * - If there is only whitespace (but multiple lines), return `undefined`.
82651          * - Split the text into lines.
82652          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
82653          * - Decode entities on each line (individually).
82654          * - Remove empty lines and join the rest with " ".
82655          */
82656         function fixupWhitespaceAndDecodeEntities(text) {
82657             var acc;
82658             // First non-whitespace character on this line.
82659             var firstNonWhitespace = 0;
82660             // Last non-whitespace character on this line.
82661             var lastNonWhitespace = -1;
82662             // These initial values are special because the first line is:
82663             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
82664             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
82665             for (var i = 0; i < text.length; i++) {
82666                 var c = text.charCodeAt(i);
82667                 if (ts.isLineBreak(c)) {
82668                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
82669                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
82670                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
82671                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
82672                     }
82673                     // Reset firstNonWhitespace for the next line.
82674                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
82675                     firstNonWhitespace = -1;
82676                 }
82677                 else if (!ts.isWhiteSpaceSingleLine(c)) {
82678                     lastNonWhitespace = i;
82679                     if (firstNonWhitespace === -1) {
82680                         firstNonWhitespace = i;
82681                     }
82682                 }
82683             }
82684             return firstNonWhitespace !== -1
82685                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
82686                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
82687                 // Last line was all whitespace, so ignore it
82688                 : acc;
82689         }
82690         function addLineOfJsxText(acc, trimmedLine) {
82691             // We do not escape the string here as that is handled by the printer
82692             // when it emits the literal. We do, however, need to decode JSX entities.
82693             var decoded = decodeEntities(trimmedLine);
82694             return acc === undefined ? decoded : acc + " " + decoded;
82695         }
82696         /**
82697          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
82698          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
82699          */
82700         function decodeEntities(text) {
82701             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
82702                 if (decimal) {
82703                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
82704                 }
82705                 else if (hex) {
82706                     return ts.utf16EncodeAsString(parseInt(hex, 16));
82707                 }
82708                 else {
82709                     var ch = entities.get(word);
82710                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
82711                     return ch ? ts.utf16EncodeAsString(ch) : match;
82712                 }
82713             });
82714         }
82715         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
82716         function tryDecodeEntities(text) {
82717             var decoded = decodeEntities(text);
82718             return decoded === text ? undefined : decoded;
82719         }
82720         function getTagName(node) {
82721             if (node.kind === 266 /* JsxElement */) {
82722                 return getTagName(node.openingElement);
82723             }
82724             else {
82725                 var name = node.tagName;
82726                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
82727                     return ts.createLiteral(ts.idText(name));
82728                 }
82729                 else {
82730                     return ts.createExpressionFromEntityName(name);
82731                 }
82732             }
82733         }
82734         /**
82735          * Emit an attribute name, which is quoted if it needs to be quoted. Because
82736          * these emit into an object literal property name, we don't need to be worried
82737          * about keywords, just non-identifier characters
82738          */
82739         function getAttributeName(node) {
82740             var name = node.name;
82741             var text = ts.idText(name);
82742             if (/^[A-Za-z_]\w*$/.test(text)) {
82743                 return name;
82744             }
82745             else {
82746                 return ts.createLiteral(text);
82747             }
82748         }
82749         function visitJsxExpression(node) {
82750             return ts.visitNode(node.expression, visitor, ts.isExpression);
82751         }
82752     }
82753     ts.transformJsx = transformJsx;
82754     var entities = ts.createMapFromTemplate({
82755         quot: 0x0022,
82756         amp: 0x0026,
82757         apos: 0x0027,
82758         lt: 0x003C,
82759         gt: 0x003E,
82760         nbsp: 0x00A0,
82761         iexcl: 0x00A1,
82762         cent: 0x00A2,
82763         pound: 0x00A3,
82764         curren: 0x00A4,
82765         yen: 0x00A5,
82766         brvbar: 0x00A6,
82767         sect: 0x00A7,
82768         uml: 0x00A8,
82769         copy: 0x00A9,
82770         ordf: 0x00AA,
82771         laquo: 0x00AB,
82772         not: 0x00AC,
82773         shy: 0x00AD,
82774         reg: 0x00AE,
82775         macr: 0x00AF,
82776         deg: 0x00B0,
82777         plusmn: 0x00B1,
82778         sup2: 0x00B2,
82779         sup3: 0x00B3,
82780         acute: 0x00B4,
82781         micro: 0x00B5,
82782         para: 0x00B6,
82783         middot: 0x00B7,
82784         cedil: 0x00B8,
82785         sup1: 0x00B9,
82786         ordm: 0x00BA,
82787         raquo: 0x00BB,
82788         frac14: 0x00BC,
82789         frac12: 0x00BD,
82790         frac34: 0x00BE,
82791         iquest: 0x00BF,
82792         Agrave: 0x00C0,
82793         Aacute: 0x00C1,
82794         Acirc: 0x00C2,
82795         Atilde: 0x00C3,
82796         Auml: 0x00C4,
82797         Aring: 0x00C5,
82798         AElig: 0x00C6,
82799         Ccedil: 0x00C7,
82800         Egrave: 0x00C8,
82801         Eacute: 0x00C9,
82802         Ecirc: 0x00CA,
82803         Euml: 0x00CB,
82804         Igrave: 0x00CC,
82805         Iacute: 0x00CD,
82806         Icirc: 0x00CE,
82807         Iuml: 0x00CF,
82808         ETH: 0x00D0,
82809         Ntilde: 0x00D1,
82810         Ograve: 0x00D2,
82811         Oacute: 0x00D3,
82812         Ocirc: 0x00D4,
82813         Otilde: 0x00D5,
82814         Ouml: 0x00D6,
82815         times: 0x00D7,
82816         Oslash: 0x00D8,
82817         Ugrave: 0x00D9,
82818         Uacute: 0x00DA,
82819         Ucirc: 0x00DB,
82820         Uuml: 0x00DC,
82821         Yacute: 0x00DD,
82822         THORN: 0x00DE,
82823         szlig: 0x00DF,
82824         agrave: 0x00E0,
82825         aacute: 0x00E1,
82826         acirc: 0x00E2,
82827         atilde: 0x00E3,
82828         auml: 0x00E4,
82829         aring: 0x00E5,
82830         aelig: 0x00E6,
82831         ccedil: 0x00E7,
82832         egrave: 0x00E8,
82833         eacute: 0x00E9,
82834         ecirc: 0x00EA,
82835         euml: 0x00EB,
82836         igrave: 0x00EC,
82837         iacute: 0x00ED,
82838         icirc: 0x00EE,
82839         iuml: 0x00EF,
82840         eth: 0x00F0,
82841         ntilde: 0x00F1,
82842         ograve: 0x00F2,
82843         oacute: 0x00F3,
82844         ocirc: 0x00F4,
82845         otilde: 0x00F5,
82846         ouml: 0x00F6,
82847         divide: 0x00F7,
82848         oslash: 0x00F8,
82849         ugrave: 0x00F9,
82850         uacute: 0x00FA,
82851         ucirc: 0x00FB,
82852         uuml: 0x00FC,
82853         yacute: 0x00FD,
82854         thorn: 0x00FE,
82855         yuml: 0x00FF,
82856         OElig: 0x0152,
82857         oelig: 0x0153,
82858         Scaron: 0x0160,
82859         scaron: 0x0161,
82860         Yuml: 0x0178,
82861         fnof: 0x0192,
82862         circ: 0x02C6,
82863         tilde: 0x02DC,
82864         Alpha: 0x0391,
82865         Beta: 0x0392,
82866         Gamma: 0x0393,
82867         Delta: 0x0394,
82868         Epsilon: 0x0395,
82869         Zeta: 0x0396,
82870         Eta: 0x0397,
82871         Theta: 0x0398,
82872         Iota: 0x0399,
82873         Kappa: 0x039A,
82874         Lambda: 0x039B,
82875         Mu: 0x039C,
82876         Nu: 0x039D,
82877         Xi: 0x039E,
82878         Omicron: 0x039F,
82879         Pi: 0x03A0,
82880         Rho: 0x03A1,
82881         Sigma: 0x03A3,
82882         Tau: 0x03A4,
82883         Upsilon: 0x03A5,
82884         Phi: 0x03A6,
82885         Chi: 0x03A7,
82886         Psi: 0x03A8,
82887         Omega: 0x03A9,
82888         alpha: 0x03B1,
82889         beta: 0x03B2,
82890         gamma: 0x03B3,
82891         delta: 0x03B4,
82892         epsilon: 0x03B5,
82893         zeta: 0x03B6,
82894         eta: 0x03B7,
82895         theta: 0x03B8,
82896         iota: 0x03B9,
82897         kappa: 0x03BA,
82898         lambda: 0x03BB,
82899         mu: 0x03BC,
82900         nu: 0x03BD,
82901         xi: 0x03BE,
82902         omicron: 0x03BF,
82903         pi: 0x03C0,
82904         rho: 0x03C1,
82905         sigmaf: 0x03C2,
82906         sigma: 0x03C3,
82907         tau: 0x03C4,
82908         upsilon: 0x03C5,
82909         phi: 0x03C6,
82910         chi: 0x03C7,
82911         psi: 0x03C8,
82912         omega: 0x03C9,
82913         thetasym: 0x03D1,
82914         upsih: 0x03D2,
82915         piv: 0x03D6,
82916         ensp: 0x2002,
82917         emsp: 0x2003,
82918         thinsp: 0x2009,
82919         zwnj: 0x200C,
82920         zwj: 0x200D,
82921         lrm: 0x200E,
82922         rlm: 0x200F,
82923         ndash: 0x2013,
82924         mdash: 0x2014,
82925         lsquo: 0x2018,
82926         rsquo: 0x2019,
82927         sbquo: 0x201A,
82928         ldquo: 0x201C,
82929         rdquo: 0x201D,
82930         bdquo: 0x201E,
82931         dagger: 0x2020,
82932         Dagger: 0x2021,
82933         bull: 0x2022,
82934         hellip: 0x2026,
82935         permil: 0x2030,
82936         prime: 0x2032,
82937         Prime: 0x2033,
82938         lsaquo: 0x2039,
82939         rsaquo: 0x203A,
82940         oline: 0x203E,
82941         frasl: 0x2044,
82942         euro: 0x20AC,
82943         image: 0x2111,
82944         weierp: 0x2118,
82945         real: 0x211C,
82946         trade: 0x2122,
82947         alefsym: 0x2135,
82948         larr: 0x2190,
82949         uarr: 0x2191,
82950         rarr: 0x2192,
82951         darr: 0x2193,
82952         harr: 0x2194,
82953         crarr: 0x21B5,
82954         lArr: 0x21D0,
82955         uArr: 0x21D1,
82956         rArr: 0x21D2,
82957         dArr: 0x21D3,
82958         hArr: 0x21D4,
82959         forall: 0x2200,
82960         part: 0x2202,
82961         exist: 0x2203,
82962         empty: 0x2205,
82963         nabla: 0x2207,
82964         isin: 0x2208,
82965         notin: 0x2209,
82966         ni: 0x220B,
82967         prod: 0x220F,
82968         sum: 0x2211,
82969         minus: 0x2212,
82970         lowast: 0x2217,
82971         radic: 0x221A,
82972         prop: 0x221D,
82973         infin: 0x221E,
82974         ang: 0x2220,
82975         and: 0x2227,
82976         or: 0x2228,
82977         cap: 0x2229,
82978         cup: 0x222A,
82979         int: 0x222B,
82980         there4: 0x2234,
82981         sim: 0x223C,
82982         cong: 0x2245,
82983         asymp: 0x2248,
82984         ne: 0x2260,
82985         equiv: 0x2261,
82986         le: 0x2264,
82987         ge: 0x2265,
82988         sub: 0x2282,
82989         sup: 0x2283,
82990         nsub: 0x2284,
82991         sube: 0x2286,
82992         supe: 0x2287,
82993         oplus: 0x2295,
82994         otimes: 0x2297,
82995         perp: 0x22A5,
82996         sdot: 0x22C5,
82997         lceil: 0x2308,
82998         rceil: 0x2309,
82999         lfloor: 0x230A,
83000         rfloor: 0x230B,
83001         lang: 0x2329,
83002         rang: 0x232A,
83003         loz: 0x25CA,
83004         spades: 0x2660,
83005         clubs: 0x2663,
83006         hearts: 0x2665,
83007         diams: 0x2666
83008     });
83009 })(ts || (ts = {}));
83010 /*@internal*/
83011 var ts;
83012 (function (ts) {
83013     function transformES2016(context) {
83014         var hoistVariableDeclaration = context.hoistVariableDeclaration;
83015         return ts.chainBundle(transformSourceFile);
83016         function transformSourceFile(node) {
83017             if (node.isDeclarationFile) {
83018                 return node;
83019             }
83020             return ts.visitEachChild(node, visitor, context);
83021         }
83022         function visitor(node) {
83023             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
83024                 return node;
83025             }
83026             switch (node.kind) {
83027                 case 209 /* BinaryExpression */:
83028                     return visitBinaryExpression(node);
83029                 default:
83030                     return ts.visitEachChild(node, visitor, context);
83031             }
83032         }
83033         function visitBinaryExpression(node) {
83034             switch (node.operatorToken.kind) {
83035                 case 66 /* AsteriskAsteriskEqualsToken */:
83036                     return visitExponentiationAssignmentExpression(node);
83037                 case 42 /* AsteriskAsteriskToken */:
83038                     return visitExponentiationExpression(node);
83039                 default:
83040                     return ts.visitEachChild(node, visitor, context);
83041             }
83042         }
83043         function visitExponentiationAssignmentExpression(node) {
83044             var target;
83045             var value;
83046             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83047             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83048             if (ts.isElementAccessExpression(left)) {
83049                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
83050                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83051                 var argumentExpressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83052                 target = ts.setTextRange(ts.createElementAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(ts.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
83053                 value = ts.setTextRange(ts.createElementAccess(expressionTemp, argumentExpressionTemp), left);
83054             }
83055             else if (ts.isPropertyAccessExpression(left)) {
83056                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
83057                 var expressionTemp = ts.createTempVariable(hoistVariableDeclaration);
83058                 target = ts.setTextRange(ts.createPropertyAccess(ts.setTextRange(ts.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
83059                 value = ts.setTextRange(ts.createPropertyAccess(expressionTemp, left.name), left);
83060             }
83061             else {
83062                 // Transforms `a **= b` into `a = Math.pow(a, b)`
83063                 target = left;
83064                 value = left;
83065             }
83066             return ts.setTextRange(ts.createAssignment(target, ts.createMathPow(value, right, /*location*/ node)), node);
83067         }
83068         function visitExponentiationExpression(node) {
83069             // Transforms `a ** b` into `Math.pow(a, b)`
83070             var left = ts.visitNode(node.left, visitor, ts.isExpression);
83071             var right = ts.visitNode(node.right, visitor, ts.isExpression);
83072             return ts.createMathPow(left, right, /*location*/ node);
83073         }
83074     }
83075     ts.transformES2016 = transformES2016;
83076 })(ts || (ts = {}));
83077 /*@internal*/
83078 var ts;
83079 (function (ts) {
83080     var ES2015SubstitutionFlags;
83081     (function (ES2015SubstitutionFlags) {
83082         /** Enables substitutions for captured `this` */
83083         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
83084         /** Enables substitutions for block-scoped bindings. */
83085         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
83086     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
83087     var LoopOutParameterFlags;
83088     (function (LoopOutParameterFlags) {
83089         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
83090         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
83091     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
83092     var CopyDirection;
83093     (function (CopyDirection) {
83094         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
83095         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
83096     })(CopyDirection || (CopyDirection = {}));
83097     var Jump;
83098     (function (Jump) {
83099         Jump[Jump["Break"] = 2] = "Break";
83100         Jump[Jump["Continue"] = 4] = "Continue";
83101         Jump[Jump["Return"] = 8] = "Return";
83102     })(Jump || (Jump = {}));
83103     // Facts we track as we traverse the tree
83104     var HierarchyFacts;
83105     (function (HierarchyFacts) {
83106         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
83107         //
83108         // Ancestor facts
83109         //
83110         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
83111         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
83112         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
83113         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
83114         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
83115         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
83116         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
83117         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
83118         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
83119         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
83120         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
83121         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
83122         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
83123         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
83124         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
83125         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
83126         //
83127         // Ancestor masks
83128         //
83129         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
83130         // We are always in *some* kind of block scope, but only specific block-scope containers are
83131         // top-level or Blocks.
83132         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
83133         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
83134         // A source file is a top-level block scope.
83135         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
83136         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
83137         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
83138         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
83139         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
83140         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
83141         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
83142         // Arrow functions are lexically scoped to their container, but are new block scopes.
83143         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
83144         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
83145         // Constructors are both new lexical scopes and new block scopes. Constructors are also
83146         // always considered non-static members of a class.
83147         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
83148         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
83149         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
83150         // within an IterationStatement to indicate whether the embedded statement is an
83151         // IterationStatementBlock.
83152         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
83153         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
83154         // 'for' statements are new block scopes and have special handling for 'let' declarations.
83155         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
83156         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
83157         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
83158         // 'let' declarations.
83159         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
83160         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
83161         // Blocks (other than function bodies) are new block scopes.
83162         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
83163         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
83164         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
83165         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
83166         //
83167         // Subtree facts
83168         //
83169         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
83170         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
83171         //
83172         // Subtree masks
83173         //
83174         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
83175         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
83176         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
83177     })(HierarchyFacts || (HierarchyFacts = {}));
83178     function transformES2015(context) {
83179         var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83180         var compilerOptions = context.getCompilerOptions();
83181         var resolver = context.getEmitResolver();
83182         var previousOnSubstituteNode = context.onSubstituteNode;
83183         var previousOnEmitNode = context.onEmitNode;
83184         context.onEmitNode = onEmitNode;
83185         context.onSubstituteNode = onSubstituteNode;
83186         var currentSourceFile;
83187         var currentText;
83188         var hierarchyFacts;
83189         var taggedTemplateStringDeclarations;
83190         function recordTaggedTemplateString(temp) {
83191             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, ts.createVariableDeclaration(temp));
83192         }
83193         /**
83194          * Used to track if we are emitting body of the converted loop
83195          */
83196         var convertedLoopState;
83197         /**
83198          * Keeps track of whether substitutions have been enabled for specific cases.
83199          * They are persisted between each SourceFile transformation and should not
83200          * be reset.
83201          */
83202         var enabledSubstitutions;
83203         return ts.chainBundle(transformSourceFile);
83204         function transformSourceFile(node) {
83205             if (node.isDeclarationFile) {
83206                 return node;
83207             }
83208             currentSourceFile = node;
83209             currentText = node.text;
83210             var visited = visitSourceFile(node);
83211             ts.addEmitHelpers(visited, context.readEmitHelpers());
83212             currentSourceFile = undefined;
83213             currentText = undefined;
83214             taggedTemplateStringDeclarations = undefined;
83215             hierarchyFacts = 0 /* None */;
83216             return visited;
83217         }
83218         /**
83219          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
83220          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
83221          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
83222          */
83223         function enterSubtree(excludeFacts, includeFacts) {
83224             var ancestorFacts = hierarchyFacts;
83225             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
83226             return ancestorFacts;
83227         }
83228         /**
83229          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
83230          * subtree, propagating specific facts from the subtree.
83231          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
83232          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
83233          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
83234          */
83235         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
83236             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
83237         }
83238         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
83239             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
83240                 && node.kind === 235 /* ReturnStatement */
83241                 && !node.expression;
83242         }
83243         function shouldVisitNode(node) {
83244             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
83245                 || convertedLoopState !== undefined
83246                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && (ts.isStatement(node) || (node.kind === 223 /* Block */)))
83247                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
83248                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
83249         }
83250         function visitor(node) {
83251             if (shouldVisitNode(node)) {
83252                 return visitJavaScript(node);
83253             }
83254             else {
83255                 return node;
83256             }
83257         }
83258         function callExpressionVisitor(node) {
83259             if (node.kind === 102 /* SuperKeyword */) {
83260                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
83261             }
83262             return visitor(node);
83263         }
83264         function visitJavaScript(node) {
83265             switch (node.kind) {
83266                 case 120 /* StaticKeyword */:
83267                     return undefined; // elide static keyword
83268                 case 245 /* ClassDeclaration */:
83269                     return visitClassDeclaration(node);
83270                 case 214 /* ClassExpression */:
83271                     return visitClassExpression(node);
83272                 case 156 /* Parameter */:
83273                     return visitParameter(node);
83274                 case 244 /* FunctionDeclaration */:
83275                     return visitFunctionDeclaration(node);
83276                 case 202 /* ArrowFunction */:
83277                     return visitArrowFunction(node);
83278                 case 201 /* FunctionExpression */:
83279                     return visitFunctionExpression(node);
83280                 case 242 /* VariableDeclaration */:
83281                     return visitVariableDeclaration(node);
83282                 case 75 /* Identifier */:
83283                     return visitIdentifier(node);
83284                 case 243 /* VariableDeclarationList */:
83285                     return visitVariableDeclarationList(node);
83286                 case 237 /* SwitchStatement */:
83287                     return visitSwitchStatement(node);
83288                 case 251 /* CaseBlock */:
83289                     return visitCaseBlock(node);
83290                 case 223 /* Block */:
83291                     return visitBlock(node, /*isFunctionBody*/ false);
83292                 case 234 /* BreakStatement */:
83293                 case 233 /* ContinueStatement */:
83294                     return visitBreakOrContinueStatement(node);
83295                 case 238 /* LabeledStatement */:
83296                     return visitLabeledStatement(node);
83297                 case 228 /* DoStatement */:
83298                 case 229 /* WhileStatement */:
83299                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
83300                 case 230 /* ForStatement */:
83301                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
83302                 case 231 /* ForInStatement */:
83303                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
83304                 case 232 /* ForOfStatement */:
83305                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
83306                 case 226 /* ExpressionStatement */:
83307                     return visitExpressionStatement(node);
83308                 case 193 /* ObjectLiteralExpression */:
83309                     return visitObjectLiteralExpression(node);
83310                 case 280 /* CatchClause */:
83311                     return visitCatchClause(node);
83312                 case 282 /* ShorthandPropertyAssignment */:
83313                     return visitShorthandPropertyAssignment(node);
83314                 case 154 /* ComputedPropertyName */:
83315                     return visitComputedPropertyName(node);
83316                 case 192 /* ArrayLiteralExpression */:
83317                     return visitArrayLiteralExpression(node);
83318                 case 196 /* CallExpression */:
83319                     return visitCallExpression(node);
83320                 case 197 /* NewExpression */:
83321                     return visitNewExpression(node);
83322                 case 200 /* ParenthesizedExpression */:
83323                     return visitParenthesizedExpression(node, /*needsDestructuringValue*/ true);
83324                 case 209 /* BinaryExpression */:
83325                     return visitBinaryExpression(node, /*needsDestructuringValue*/ true);
83326                 case 14 /* NoSubstitutionTemplateLiteral */:
83327                 case 15 /* TemplateHead */:
83328                 case 16 /* TemplateMiddle */:
83329                 case 17 /* TemplateTail */:
83330                     return visitTemplateLiteral(node);
83331                 case 10 /* StringLiteral */:
83332                     return visitStringLiteral(node);
83333                 case 8 /* NumericLiteral */:
83334                     return visitNumericLiteral(node);
83335                 case 198 /* TaggedTemplateExpression */:
83336                     return visitTaggedTemplateExpression(node);
83337                 case 211 /* TemplateExpression */:
83338                     return visitTemplateExpression(node);
83339                 case 212 /* YieldExpression */:
83340                     return visitYieldExpression(node);
83341                 case 213 /* SpreadElement */:
83342                     return visitSpreadElement(node);
83343                 case 102 /* SuperKeyword */:
83344                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
83345                 case 104 /* ThisKeyword */:
83346                     return visitThisKeyword(node);
83347                 case 219 /* MetaProperty */:
83348                     return visitMetaProperty(node);
83349                 case 161 /* MethodDeclaration */:
83350                     return visitMethodDeclaration(node);
83351                 case 163 /* GetAccessor */:
83352                 case 164 /* SetAccessor */:
83353                     return visitAccessorDeclaration(node);
83354                 case 225 /* VariableStatement */:
83355                     return visitVariableStatement(node);
83356                 case 235 /* ReturnStatement */:
83357                     return visitReturnStatement(node);
83358                 default:
83359                     return ts.visitEachChild(node, visitor, context);
83360             }
83361         }
83362         function visitSourceFile(node) {
83363             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
83364             var prologue = [];
83365             var statements = [];
83366             startLexicalEnvironment();
83367             var statementOffset = ts.addStandardPrologue(prologue, node.statements, /*ensureUseStrict*/ false);
83368             statementOffset = ts.addCustomPrologue(prologue, node.statements, statementOffset, visitor);
83369             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
83370             if (taggedTemplateStringDeclarations) {
83371                 statements.push(ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList(taggedTemplateStringDeclarations)));
83372             }
83373             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83374             insertCaptureThisForNodeIfNeeded(prologue, node);
83375             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83376             return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
83377         }
83378         function visitSwitchStatement(node) {
83379             if (convertedLoopState !== undefined) {
83380                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
83381                 // for switch statement allow only non-labeled break
83382                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
83383                 var result = ts.visitEachChild(node, visitor, context);
83384                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
83385                 return result;
83386             }
83387             return ts.visitEachChild(node, visitor, context);
83388         }
83389         function visitCaseBlock(node) {
83390             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
83391             var updated = ts.visitEachChild(node, visitor, context);
83392             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
83393             return updated;
83394         }
83395         function returnCapturedThis(node) {
83396             return ts.setOriginalNode(ts.createReturn(ts.createFileLevelUniqueName("_this")), node);
83397         }
83398         function visitReturnStatement(node) {
83399             if (convertedLoopState) {
83400                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
83401                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83402                     node = returnCapturedThis(node);
83403                 }
83404                 return ts.createReturn(ts.createObjectLiteral([
83405                     ts.createPropertyAssignment(ts.createIdentifier("value"), node.expression
83406                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
83407                         : ts.createVoidZero())
83408                 ]));
83409             }
83410             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
83411                 return returnCapturedThis(node);
83412             }
83413             return ts.visitEachChild(node, visitor, context);
83414         }
83415         function visitThisKeyword(node) {
83416             if (hierarchyFacts & 2 /* ArrowFunction */) {
83417                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
83418             }
83419             if (convertedLoopState) {
83420                 if (hierarchyFacts & 2 /* ArrowFunction */) {
83421                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
83422                     convertedLoopState.containsLexicalThis = true;
83423                     return node;
83424                 }
83425                 return convertedLoopState.thisName || (convertedLoopState.thisName = ts.createUniqueName("this"));
83426             }
83427             return node;
83428         }
83429         function visitIdentifier(node) {
83430             if (!convertedLoopState) {
83431                 return node;
83432             }
83433             if (ts.isGeneratedIdentifier(node)) {
83434                 return node;
83435             }
83436             if (node.escapedText !== "arguments" || !resolver.isArgumentsLocalBinding(node)) {
83437                 return node;
83438             }
83439             return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = ts.createUniqueName("arguments"));
83440         }
83441         function visitBreakOrContinueStatement(node) {
83442             if (convertedLoopState) {
83443                 // check if we can emit break/continue as is
83444                 // it is possible if either
83445                 //   - break/continue is labeled and label is located inside the converted loop
83446                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
83447                 var jump = node.kind === 234 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
83448                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
83449                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
83450                 if (!canUseBreakOrContinue) {
83451                     var labelMarker = void 0;
83452                     var label = node.label;
83453                     if (!label) {
83454                         if (node.kind === 234 /* BreakStatement */) {
83455                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
83456                             labelMarker = "break";
83457                         }
83458                         else {
83459                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
83460                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
83461                             labelMarker = "continue";
83462                         }
83463                     }
83464                     else {
83465                         if (node.kind === 234 /* BreakStatement */) {
83466                             labelMarker = "break-" + label.escapedText;
83467                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
83468                         }
83469                         else {
83470                             labelMarker = "continue-" + label.escapedText;
83471                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
83472                         }
83473                     }
83474                     var returnExpression = ts.createLiteral(labelMarker);
83475                     if (convertedLoopState.loopOutParameters.length) {
83476                         var outParams = convertedLoopState.loopOutParameters;
83477                         var expr = void 0;
83478                         for (var i = 0; i < outParams.length; i++) {
83479                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
83480                             if (i === 0) {
83481                                 expr = copyExpr;
83482                             }
83483                             else {
83484                                 expr = ts.createBinary(expr, 27 /* CommaToken */, copyExpr);
83485                             }
83486                         }
83487                         returnExpression = ts.createBinary(expr, 27 /* CommaToken */, returnExpression);
83488                     }
83489                     return ts.createReturn(returnExpression);
83490                 }
83491             }
83492             return ts.visitEachChild(node, visitor, context);
83493         }
83494         /**
83495          * Visits a ClassDeclaration and transforms it into a variable statement.
83496          *
83497          * @param node A ClassDeclaration node.
83498          */
83499         function visitClassDeclaration(node) {
83500             // [source]
83501             //      class C { }
83502             //
83503             // [output]
83504             //      var C = (function () {
83505             //          function C() {
83506             //          }
83507             //          return C;
83508             //      }());
83509             var variable = ts.createVariableDeclaration(ts.getLocalName(node, /*allowComments*/ true), 
83510             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
83511             ts.setOriginalNode(variable, node);
83512             var statements = [];
83513             var statement = ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([variable]));
83514             ts.setOriginalNode(statement, node);
83515             ts.setTextRange(statement, node);
83516             ts.startOnNewLine(statement);
83517             statements.push(statement);
83518             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
83519             if (ts.hasModifier(node, 1 /* Export */)) {
83520                 var exportStatement = ts.hasModifier(node, 512 /* Default */)
83521                     ? ts.createExportDefault(ts.getLocalName(node))
83522                     : ts.createExternalModuleExport(ts.getLocalName(node));
83523                 ts.setOriginalNode(exportStatement, statement);
83524                 statements.push(exportStatement);
83525             }
83526             var emitFlags = ts.getEmitFlags(node);
83527             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
83528                 // Add a DeclarationMarker as a marker for the end of the declaration
83529                 statements.push(ts.createEndOfDeclarationMarker(node));
83530                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
83531             }
83532             return ts.singleOrMany(statements);
83533         }
83534         /**
83535          * Visits a ClassExpression and transforms it into an expression.
83536          *
83537          * @param node A ClassExpression node.
83538          */
83539         function visitClassExpression(node) {
83540             // [source]
83541             //      C = class { }
83542             //
83543             // [output]
83544             //      C = (function () {
83545             //          function class_1() {
83546             //          }
83547             //          return class_1;
83548             //      }())
83549             return transformClassLikeDeclarationToExpression(node);
83550         }
83551         /**
83552          * Transforms a ClassExpression or ClassDeclaration into an expression.
83553          *
83554          * @param node A ClassExpression or ClassDeclaration node.
83555          */
83556         function transformClassLikeDeclarationToExpression(node) {
83557             // [source]
83558             //      class C extends D {
83559             //          constructor() {}
83560             //          method() {}
83561             //          get prop() {}
83562             //          set prop(v) {}
83563             //      }
83564             //
83565             // [output]
83566             //      (function (_super) {
83567             //          __extends(C, _super);
83568             //          function C() {
83569             //          }
83570             //          C.prototype.method = function () {}
83571             //          Object.defineProperty(C.prototype, "prop", {
83572             //              get: function() {},
83573             //              set: function() {},
83574             //              enumerable: true,
83575             //              configurable: true
83576             //          });
83577             //          return C;
83578             //      }(D))
83579             if (node.name) {
83580                 enableSubstitutionsForBlockScopedBindings();
83581             }
83582             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
83583             var classFunction = ts.createFunctionExpression(
83584             /*modifiers*/ undefined, 
83585             /*asteriskToken*/ undefined, 
83586             /*name*/ undefined, 
83587             /*typeParameters*/ undefined, extendsClauseElement ? [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, ts.createFileLevelUniqueName("_super"))] : [], 
83588             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
83589             // To preserve the behavior of the old emitter, we explicitly indent
83590             // the body of the function here if it was requested in an earlier
83591             // transformation.
83592             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
83593             // "inner" and "outer" below are added purely to preserve source map locations from
83594             // the old emitter
83595             var inner = ts.createPartiallyEmittedExpression(classFunction);
83596             inner.end = node.end;
83597             ts.setEmitFlags(inner, 1536 /* NoComments */);
83598             var outer = ts.createPartiallyEmittedExpression(inner);
83599             outer.end = ts.skipTrivia(currentText, node.pos);
83600             ts.setEmitFlags(outer, 1536 /* NoComments */);
83601             var result = ts.createParen(ts.createCall(outer, 
83602             /*typeArguments*/ undefined, extendsClauseElement
83603                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
83604                 : []));
83605             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
83606             return result;
83607         }
83608         /**
83609          * Transforms a ClassExpression or ClassDeclaration into a function body.
83610          *
83611          * @param node A ClassExpression or ClassDeclaration node.
83612          * @param extendsClauseElement The expression for the class `extends` clause.
83613          */
83614         function transformClassBody(node, extendsClauseElement) {
83615             var statements = [];
83616             startLexicalEnvironment();
83617             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
83618             addConstructor(statements, node, extendsClauseElement);
83619             addClassMembers(statements, node);
83620             // Create a synthetic text range for the return statement.
83621             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
83622             var localName = ts.getInternalName(node);
83623             // The following partially-emitted expression exists purely to align our sourcemap
83624             // emit with the original emitter.
83625             var outer = ts.createPartiallyEmittedExpression(localName);
83626             outer.end = closingBraceLocation.end;
83627             ts.setEmitFlags(outer, 1536 /* NoComments */);
83628             var statement = ts.createReturn(outer);
83629             statement.pos = closingBraceLocation.pos;
83630             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
83631             statements.push(statement);
83632             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
83633             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
83634             ts.setEmitFlags(block, 1536 /* NoComments */);
83635             return block;
83636         }
83637         /**
83638          * Adds a call to the `__extends` helper if needed for a class.
83639          *
83640          * @param statements The statements of the class body function.
83641          * @param node The ClassExpression or ClassDeclaration node.
83642          * @param extendsClauseElement The expression for the class `extends` clause.
83643          */
83644         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
83645             if (extendsClauseElement) {
83646                 statements.push(ts.setTextRange(ts.createExpressionStatement(createExtendsHelper(context, ts.getInternalName(node))), 
83647                 /*location*/ extendsClauseElement));
83648             }
83649         }
83650         /**
83651          * Adds the constructor of the class to a class body function.
83652          *
83653          * @param statements The statements of the class body function.
83654          * @param node The ClassExpression or ClassDeclaration node.
83655          * @param extendsClauseElement The expression for the class `extends` clause.
83656          */
83657         function addConstructor(statements, node, extendsClauseElement) {
83658             var savedConvertedLoopState = convertedLoopState;
83659             convertedLoopState = undefined;
83660             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
83661             var constructor = ts.getFirstConstructorWithBody(node);
83662             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
83663             var constructorFunction = ts.createFunctionDeclaration(
83664             /*decorators*/ undefined, 
83665             /*modifiers*/ undefined, 
83666             /*asteriskToken*/ undefined, ts.getInternalName(node), 
83667             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
83668             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
83669             ts.setTextRange(constructorFunction, constructor || node);
83670             if (extendsClauseElement) {
83671                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
83672             }
83673             statements.push(constructorFunction);
83674             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
83675             convertedLoopState = savedConvertedLoopState;
83676         }
83677         /**
83678          * Transforms the parameters of the constructor declaration of a class.
83679          *
83680          * @param constructor The constructor for the class.
83681          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83682          *                            synthesized `super` call.
83683          */
83684         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
83685             // If the TypeScript transformer needed to synthesize a constructor for property
83686             // initializers, it would have also added a synthetic `...args` parameter and
83687             // `super` call.
83688             // If this is the case, we do not include the synthetic `...args` parameter and
83689             // will instead use the `arguments` object in ES5/3.
83690             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
83691                 || [];
83692         }
83693         function createDefaultConstructorBody(node, isDerivedClass) {
83694             // We must be here because the user didn't write a constructor
83695             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
83696             // If that's the case we can just immediately return the result of a 'super()' call.
83697             var statements = [];
83698             resumeLexicalEnvironment();
83699             ts.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83700             if (isDerivedClass) {
83701                 // return _super !== null && _super.apply(this, arguments) || this;
83702                 statements.push(ts.createReturn(createDefaultSuperCallOrThis()));
83703             }
83704             var statementsArray = ts.createNodeArray(statements);
83705             ts.setTextRange(statementsArray, node.members);
83706             var block = ts.createBlock(statementsArray, /*multiLine*/ true);
83707             ts.setTextRange(block, node);
83708             ts.setEmitFlags(block, 1536 /* NoComments */);
83709             return block;
83710         }
83711         /**
83712          * Transforms the body of a constructor declaration of a class.
83713          *
83714          * @param constructor The constructor for the class.
83715          * @param node The node which contains the constructor.
83716          * @param extendsClauseElement The expression for the class `extends` clause.
83717          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
83718          *                            synthesized `super` call.
83719          */
83720         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
83721             // determine whether the class is known syntactically to be a derived class (e.g. a
83722             // class that extends a value that is not syntactically known to be `null`).
83723             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 100 /* NullKeyword */;
83724             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
83725             // representation:
83726             //
83727             // ```
83728             // // es2015 (source)
83729             // class C extends Base { }
83730             //
83731             // // es5 (transformed)
83732             // var C = (function (_super) {
83733             //     function C() {
83734             //         return _super.apply(this, arguments) || this;
83735             //     }
83736             //     return C;
83737             // })(Base);
83738             // ```
83739             if (!constructor)
83740                 return createDefaultConstructorBody(node, isDerivedClass);
83741             // The prologue will contain all leading standard and custom prologue statements added by this transform
83742             var prologue = [];
83743             var statements = [];
83744             resumeLexicalEnvironment();
83745             // If a super call has already been synthesized,
83746             // we're going to assume that we should just transform everything after that.
83747             // The assumption is that no prior step in the pipeline has added any prologue directives.
83748             var statementOffset = 0;
83749             if (!hasSynthesizedSuper)
83750                 statementOffset = ts.addStandardPrologue(prologue, constructor.body.statements, /*ensureUseStrict*/ false);
83751             addDefaultValueAssignmentsIfNeeded(statements, constructor);
83752             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
83753             if (!hasSynthesizedSuper)
83754                 statementOffset = ts.addCustomPrologue(statements, constructor.body.statements, statementOffset, visitor);
83755             // If the first statement is a call to `super()`, visit the statement directly
83756             var superCallExpression;
83757             if (hasSynthesizedSuper) {
83758                 superCallExpression = createDefaultSuperCallOrThis();
83759             }
83760             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
83761                 var firstStatement = constructor.body.statements[statementOffset];
83762                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
83763                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
83764                 }
83765             }
83766             if (superCallExpression) {
83767                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
83768                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
83769             }
83770             // visit the remaining statements
83771             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
83772             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
83773             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
83774             if (isDerivedClass) {
83775                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
83776                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
83777                     // following representation:
83778                     //
83779                     // ```
83780                     // // es2015 (source)
83781                     // class C extends Base {
83782                     //     constructor() {
83783                     //         super("foo");
83784                     //     }
83785                     // }
83786                     //
83787                     // // es5 (transformed)
83788                     // var C = (function (_super) {
83789                     //     function C() {
83790                     //         return _super.call(this, "foo") || this;
83791                     //     }
83792                     //     return C;
83793                     // })(Base);
83794                     // ```
83795                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
83796                     var returnStatement = ts.createReturn(superCallExpression);
83797                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
83798                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
83799                     statements.push(returnStatement);
83800                 }
83801                 else {
83802                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
83803                     //
83804                     // ```
83805                     // // es2015 (source)
83806                     // class C extends Base {
83807                     //     constructor() {
83808                     //         super("foo");
83809                     //         this.x = 1;
83810                     //     }
83811                     // }
83812                     //
83813                     // // es5 (transformed)
83814                     // var C = (function (_super) {
83815                     //     function C() {
83816                     //         var _this = _super.call(this, "foo") || this;
83817                     //         _this.x = 1;
83818                     //         return _this;
83819                     //     }
83820                     //     return C;
83821                     // })(Base);
83822                     // ```
83823                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
83824                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
83825                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
83826                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
83827                         statements.push(ts.createReturn(ts.createFileLevelUniqueName("_this")));
83828                     }
83829                 }
83830             }
83831             else {
83832                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
83833                 // captured when necessitated by an arrow function capturing the lexical `this`:
83834                 //
83835                 // ```
83836                 // // es2015
83837                 // class C {}
83838                 //
83839                 // // es5
83840                 // var C = (function () {
83841                 //     function C() {
83842                 //     }
83843                 //     return C;
83844                 // })();
83845                 // ```
83846                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
83847             }
83848             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(ts.concatenate(prologue, statements)), 
83849             /*location*/ constructor.body.statements), 
83850             /*multiLine*/ true);
83851             ts.setTextRange(block, constructor.body);
83852             return block;
83853         }
83854         /**
83855          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
83856          * It would generate obviously dead code, so we'll try to make things a little bit prettier
83857          * by doing a minimal check on whether some common patterns always explicitly return.
83858          */
83859         function isSufficientlyCoveredByReturnStatements(statement) {
83860             // A return statement is considered covered.
83861             if (statement.kind === 235 /* ReturnStatement */) {
83862                 return true;
83863             }
83864             // An if-statement with two covered branches is covered.
83865             else if (statement.kind === 227 /* IfStatement */) {
83866                 var ifStatement = statement;
83867                 if (ifStatement.elseStatement) {
83868                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
83869                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
83870                 }
83871             }
83872             // A block is covered if it has a last statement which is covered.
83873             else if (statement.kind === 223 /* Block */) {
83874                 var lastStatement = ts.lastOrUndefined(statement.statements);
83875                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
83876                     return true;
83877                 }
83878             }
83879             return false;
83880         }
83881         function createActualThis() {
83882             return ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */);
83883         }
83884         function createDefaultSuperCallOrThis() {
83885             return ts.createLogicalOr(ts.createLogicalAnd(ts.createStrictInequality(ts.createFileLevelUniqueName("_super"), ts.createNull()), ts.createFunctionApply(ts.createFileLevelUniqueName("_super"), createActualThis(), ts.createIdentifier("arguments"))), createActualThis());
83886         }
83887         /**
83888          * Visits a parameter declaration.
83889          *
83890          * @param node A ParameterDeclaration node.
83891          */
83892         function visitParameter(node) {
83893             if (node.dotDotDotToken) {
83894                 // rest parameters are elided
83895                 return undefined;
83896             }
83897             else if (ts.isBindingPattern(node.name)) {
83898                 // Binding patterns are converted into a generated name and are
83899                 // evaluated inside the function body.
83900                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83901                 /*decorators*/ undefined, 
83902                 /*modifiers*/ undefined, 
83903                 /*dotDotDotToken*/ undefined, ts.getGeneratedNameForNode(node), 
83904                 /*questionToken*/ undefined, 
83905                 /*type*/ undefined, 
83906                 /*initializer*/ undefined), 
83907                 /*location*/ node), 
83908                 /*original*/ node);
83909             }
83910             else if (node.initializer) {
83911                 // Initializers are elided
83912                 return ts.setOriginalNode(ts.setTextRange(ts.createParameter(
83913                 /*decorators*/ undefined, 
83914                 /*modifiers*/ undefined, 
83915                 /*dotDotDotToken*/ undefined, node.name, 
83916                 /*questionToken*/ undefined, 
83917                 /*type*/ undefined, 
83918                 /*initializer*/ undefined), 
83919                 /*location*/ node), 
83920                 /*original*/ node);
83921             }
83922             else {
83923                 return node;
83924             }
83925         }
83926         function hasDefaultValueOrBindingPattern(node) {
83927             return node.initializer !== undefined
83928                 || ts.isBindingPattern(node.name);
83929         }
83930         /**
83931          * Adds statements to the body of a function-like node if it contains parameters with
83932          * binding patterns or initializers.
83933          *
83934          * @param statements The statements for the new function body.
83935          * @param node A function-like node.
83936          */
83937         function addDefaultValueAssignmentsIfNeeded(statements, node) {
83938             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
83939                 return false;
83940             }
83941             var added = false;
83942             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
83943                 var parameter = _a[_i];
83944                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
83945                 // A rest parameter cannot have a binding pattern or an initializer,
83946                 // so let's just ignore it.
83947                 if (dotDotDotToken) {
83948                     continue;
83949                 }
83950                 if (ts.isBindingPattern(name)) {
83951                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
83952                 }
83953                 else if (initializer) {
83954                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
83955                     added = true;
83956                 }
83957             }
83958             return added;
83959         }
83960         /**
83961          * Adds statements to the body of a function-like node for parameters with binding patterns
83962          *
83963          * @param statements The statements for the new function body.
83964          * @param parameter The parameter for the function.
83965          * @param name The name of the parameter.
83966          * @param initializer The initializer for the parameter.
83967          */
83968         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
83969             // In cases where a binding pattern is simply '[]' or '{}',
83970             // we usually don't want to emit a var declaration; however, in the presence
83971             // of an initializer, we must emit that expression to preserve side effects.
83972             if (name.elements.length > 0) {
83973                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createVariableStatement(
83974                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, ts.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
83975                 return true;
83976             }
83977             else if (initializer) {
83978                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(ts.createExpressionStatement(ts.createAssignment(ts.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
83979                 return true;
83980             }
83981             return false;
83982         }
83983         /**
83984          * Adds statements to the body of a function-like node for parameters with initializers.
83985          *
83986          * @param statements The statements for the new function body.
83987          * @param parameter The parameter for the function.
83988          * @param name The name of the parameter.
83989          * @param initializer The initializer for the parameter.
83990          */
83991         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
83992             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
83993             var statement = ts.createIf(ts.createTypeCheck(ts.getSynthesizedClone(name), "undefined"), ts.setEmitFlags(ts.setTextRange(ts.createBlock([
83994                 ts.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
83995             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
83996             ts.startOnNewLine(statement);
83997             ts.setTextRange(statement, parameter);
83998             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
83999             ts.insertStatementAfterCustomPrologue(statements, statement);
84000         }
84001         /**
84002          * Gets a value indicating whether we need to add statements to handle a rest parameter.
84003          *
84004          * @param node A ParameterDeclaration node.
84005          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84006          *                                          part of a constructor declaration with a
84007          *                                          synthesized call to `super`
84008          */
84009         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
84010             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
84011         }
84012         /**
84013          * Adds statements to the body of a function-like node if it contains a rest parameter.
84014          *
84015          * @param statements The statements for the new function body.
84016          * @param node A function-like node.
84017          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
84018          *                                          part of a constructor declaration with a
84019          *                                          synthesized call to `super`
84020          */
84021         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
84022             var prologueStatements = [];
84023             var parameter = ts.lastOrUndefined(node.parameters);
84024             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
84025                 return false;
84026             }
84027             // `declarationName` is the name of the local declaration for the parameter.
84028             var declarationName = parameter.name.kind === 75 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84029             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
84030             // `expressionName` is the name of the parameter used in expressions.
84031             var expressionName = parameter.name.kind === 75 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName;
84032             var restIndex = node.parameters.length - 1;
84033             var temp = ts.createLoopVariable();
84034             // var param = [];
84035             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84036             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84037                 ts.createVariableDeclaration(declarationName, 
84038                 /*type*/ undefined, ts.createArrayLiteral([]))
84039             ])), 
84040             /*location*/ parameter), 1048576 /* CustomPrologue */));
84041             // for (var _i = restIndex; _i < arguments.length; _i++) {
84042             //   param[_i - restIndex] = arguments[_i];
84043             // }
84044             var forStatement = ts.createFor(ts.setTextRange(ts.createVariableDeclarationList([
84045                 ts.createVariableDeclaration(temp, /*type*/ undefined, ts.createLiteral(restIndex))
84046             ]), parameter), ts.setTextRange(ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(ts.createPostfixIncrement(temp), parameter), ts.createBlock([
84047                 ts.startOnNewLine(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(expressionName, restIndex === 0
84048                     ? temp
84049                     : ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp))), 
84050                 /*location*/ parameter))
84051             ]));
84052             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
84053             ts.startOnNewLine(forStatement);
84054             prologueStatements.push(forStatement);
84055             if (parameter.name.kind !== 75 /* Identifier */) {
84056                 // do the actual destructuring of the rest parameter if necessary
84057                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(
84058                 /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
84059             }
84060             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
84061             return true;
84062         }
84063         /**
84064          * Adds a statement to capture the `this` of a function declaration if it is needed.
84065          * NOTE: This must be executed *after* the subtree has been visited.
84066          *
84067          * @param statements The statements for the new function body.
84068          * @param node A node.
84069          */
84070         function insertCaptureThisForNodeIfNeeded(statements, node) {
84071             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 202 /* ArrowFunction */) {
84072                 insertCaptureThisForNode(statements, node, ts.createThis());
84073                 return true;
84074             }
84075             return false;
84076         }
84077         function insertCaptureThisForNode(statements, node, initializer) {
84078             enableSubstitutionsForCapturedThis();
84079             var captureThisStatement = ts.createVariableStatement(
84080             /*modifiers*/ undefined, ts.createVariableDeclarationList([
84081                 ts.createVariableDeclaration(ts.createFileLevelUniqueName("_this"), 
84082                 /*type*/ undefined, initializer)
84083             ]));
84084             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84085             ts.setSourceMapRange(captureThisStatement, node);
84086             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
84087         }
84088         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
84089             if (hierarchyFacts & 16384 /* NewTarget */) {
84090                 var newTarget = void 0;
84091                 switch (node.kind) {
84092                     case 202 /* ArrowFunction */:
84093                         return statements;
84094                     case 161 /* MethodDeclaration */:
84095                     case 163 /* GetAccessor */:
84096                     case 164 /* SetAccessor */:
84097                         // Methods and accessors cannot be constructors, so 'new.target' will
84098                         // always return 'undefined'.
84099                         newTarget = ts.createVoidZero();
84100                         break;
84101                     case 162 /* Constructor */:
84102                         // Class constructors can only be called with `new`, so `this.constructor`
84103                         // should be relatively safe to use.
84104                         newTarget = ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor");
84105                         break;
84106                     case 244 /* FunctionDeclaration */:
84107                     case 201 /* FunctionExpression */:
84108                         // Functions can be called or constructed, and may have a `this` due to
84109                         // being a member or when calling an imported function via `other_1.f()`.
84110                         newTarget = ts.createConditional(ts.createLogicalAnd(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), ts.createBinary(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), 98 /* InstanceOfKeyword */, ts.getLocalName(node))), ts.createPropertyAccess(ts.setEmitFlags(ts.createThis(), 4 /* NoSubstitution */), "constructor"), ts.createVoidZero());
84111                         break;
84112                     default:
84113                         return ts.Debug.failBadSyntaxKind(node);
84114                 }
84115                 var captureNewTargetStatement = ts.createVariableStatement(
84116                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
84117                     ts.createVariableDeclaration(ts.createFileLevelUniqueName("_newTarget"), 
84118                     /*type*/ undefined, newTarget)
84119                 ]));
84120                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
84121                 if (copyOnWrite) {
84122                     statements = statements.slice();
84123                 }
84124                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
84125             }
84126             return statements;
84127         }
84128         /**
84129          * Adds statements to the class body function for a class to define the members of the
84130          * class.
84131          *
84132          * @param statements The statements for the class body function.
84133          * @param node The ClassExpression or ClassDeclaration node.
84134          */
84135         function addClassMembers(statements, node) {
84136             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
84137                 var member = _a[_i];
84138                 switch (member.kind) {
84139                     case 222 /* SemicolonClassElement */:
84140                         statements.push(transformSemicolonClassElementToStatement(member));
84141                         break;
84142                     case 161 /* MethodDeclaration */:
84143                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
84144                         break;
84145                     case 163 /* GetAccessor */:
84146                     case 164 /* SetAccessor */:
84147                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
84148                         if (member === accessors.firstAccessor) {
84149                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
84150                         }
84151                         break;
84152                     case 162 /* Constructor */:
84153                         // Constructors are handled in visitClassExpression/visitClassDeclaration
84154                         break;
84155                     default:
84156                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
84157                         break;
84158                 }
84159             }
84160         }
84161         /**
84162          * Transforms a SemicolonClassElement into a statement for a class body function.
84163          *
84164          * @param member The SemicolonClassElement node.
84165          */
84166         function transformSemicolonClassElementToStatement(member) {
84167             return ts.setTextRange(ts.createEmptyStatement(), member);
84168         }
84169         /**
84170          * Transforms a MethodDeclaration into a statement for a class body function.
84171          *
84172          * @param receiver The receiver for the member.
84173          * @param member The MethodDeclaration node.
84174          */
84175         function transformClassMethodDeclarationToStatement(receiver, member, container) {
84176             var commentRange = ts.getCommentRange(member);
84177             var sourceMapRange = ts.getSourceMapRange(member);
84178             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
84179             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
84180             var e;
84181             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
84182                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
84183                     : ts.isIdentifier(propertyName) ? ts.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
84184                         : propertyName;
84185                 e = ts.createObjectDefinePropertyCall(receiver, name, ts.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
84186             }
84187             else {
84188                 var memberName = ts.createMemberAccessForPropertyName(receiver, propertyName, /*location*/ member.name);
84189                 e = ts.createAssignment(memberName, memberFunction);
84190             }
84191             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
84192             ts.setSourceMapRange(memberFunction, sourceMapRange);
84193             var statement = ts.setTextRange(ts.createExpressionStatement(e), /*location*/ member);
84194             ts.setOriginalNode(statement, member);
84195             ts.setCommentRange(statement, commentRange);
84196             // The location for the statement is used to emit comments only.
84197             // No source map should be emitted for this statement to align with the
84198             // old emitter.
84199             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
84200             return statement;
84201         }
84202         /**
84203          * Transforms a set of related of get/set accessors into a statement for a class body function.
84204          *
84205          * @param receiver The receiver for the member.
84206          * @param accessors The set of related get/set accessors.
84207          */
84208         function transformAccessorsToStatement(receiver, accessors, container) {
84209             var statement = ts.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
84210             // The location for the statement is used to emit source maps only.
84211             // No comments should be emitted for this statement to align with the
84212             // old emitter.
84213             ts.setEmitFlags(statement, 1536 /* NoComments */);
84214             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
84215             return statement;
84216         }
84217         /**
84218          * Transforms a set of related get/set accessors into an expression for either a class
84219          * body function or an ObjectLiteralExpression with computed properties.
84220          *
84221          * @param receiver The receiver for the member.
84222          */
84223         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
84224             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
84225             // To align with source maps in the old emitter, the receiver and property name
84226             // arguments are both mapped contiguously to the accessor name.
84227             var target = ts.getMutableClone(receiver);
84228             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
84229             ts.setSourceMapRange(target, firstAccessor.name);
84230             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
84231             if (ts.isPrivateIdentifier(visitedAccessorName)) {
84232                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
84233             }
84234             var propertyName = ts.createExpressionForPropertyName(visitedAccessorName);
84235             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
84236             ts.setSourceMapRange(propertyName, firstAccessor.name);
84237             var properties = [];
84238             if (getAccessor) {
84239                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
84240                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
84241                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
84242                 var getter = ts.createPropertyAssignment("get", getterFunction);
84243                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
84244                 properties.push(getter);
84245             }
84246             if (setAccessor) {
84247                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
84248                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
84249                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
84250                 var setter = ts.createPropertyAssignment("set", setterFunction);
84251                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
84252                 properties.push(setter);
84253             }
84254             properties.push(ts.createPropertyAssignment("enumerable", getAccessor || setAccessor ? ts.createFalse() : ts.createTrue()), ts.createPropertyAssignment("configurable", ts.createTrue()));
84255             var call = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
84256             /*typeArguments*/ undefined, [
84257                 target,
84258                 propertyName,
84259                 ts.createObjectLiteral(properties, /*multiLine*/ true)
84260             ]);
84261             if (startsOnNewLine) {
84262                 ts.startOnNewLine(call);
84263             }
84264             return call;
84265         }
84266         /**
84267          * Visits an ArrowFunction and transforms it into a FunctionExpression.
84268          *
84269          * @param node An ArrowFunction node.
84270          */
84271         function visitArrowFunction(node) {
84272             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
84273                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
84274             }
84275             var savedConvertedLoopState = convertedLoopState;
84276             convertedLoopState = undefined;
84277             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
84278             var func = ts.createFunctionExpression(
84279             /*modifiers*/ undefined, 
84280             /*asteriskToken*/ undefined, 
84281             /*name*/ undefined, 
84282             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84283             /*type*/ undefined, transformFunctionBody(node));
84284             ts.setTextRange(func, node);
84285             ts.setOriginalNode(func, node);
84286             ts.setEmitFlags(func, 8 /* CapturesThis */);
84287             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
84288                 enableSubstitutionsForCapturedThis();
84289             }
84290             // If an arrow function contains
84291             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
84292             convertedLoopState = savedConvertedLoopState;
84293             return func;
84294         }
84295         /**
84296          * Visits a FunctionExpression node.
84297          *
84298          * @param node a FunctionExpression node.
84299          */
84300         function visitFunctionExpression(node) {
84301             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
84302                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
84303                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84304             var savedConvertedLoopState = convertedLoopState;
84305             convertedLoopState = undefined;
84306             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84307             var body = transformFunctionBody(node);
84308             var name = hierarchyFacts & 16384 /* NewTarget */
84309                 ? ts.getLocalName(node)
84310                 : node.name;
84311             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84312             convertedLoopState = savedConvertedLoopState;
84313             return ts.updateFunctionExpression(node, 
84314             /*modifiers*/ undefined, node.asteriskToken, name, 
84315             /*typeParameters*/ undefined, parameters, 
84316             /*type*/ undefined, body);
84317         }
84318         /**
84319          * Visits a FunctionDeclaration node.
84320          *
84321          * @param node a FunctionDeclaration node.
84322          */
84323         function visitFunctionDeclaration(node) {
84324             var savedConvertedLoopState = convertedLoopState;
84325             convertedLoopState = undefined;
84326             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84327             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84328             var body = transformFunctionBody(node);
84329             var name = hierarchyFacts & 16384 /* NewTarget */
84330                 ? ts.getLocalName(node)
84331                 : node.name;
84332             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84333             convertedLoopState = savedConvertedLoopState;
84334             return ts.updateFunctionDeclaration(node, 
84335             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
84336             /*typeParameters*/ undefined, parameters, 
84337             /*type*/ undefined, body);
84338         }
84339         /**
84340          * Transforms a function-like node into a FunctionExpression.
84341          *
84342          * @param node The function-like node to transform.
84343          * @param location The source-map location for the new FunctionExpression.
84344          * @param name The name of the new FunctionExpression.
84345          */
84346         function transformFunctionLikeToExpression(node, location, name, container) {
84347             var savedConvertedLoopState = convertedLoopState;
84348             convertedLoopState = undefined;
84349             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasModifier(node, 32 /* Static */)
84350                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
84351                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
84352             var parameters = ts.visitParameterList(node.parameters, visitor, context);
84353             var body = transformFunctionBody(node);
84354             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 244 /* FunctionDeclaration */ || node.kind === 201 /* FunctionExpression */)) {
84355                 name = ts.getGeneratedNameForNode(node);
84356             }
84357             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
84358             convertedLoopState = savedConvertedLoopState;
84359             return ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
84360             /*modifiers*/ undefined, node.asteriskToken, name, 
84361             /*typeParameters*/ undefined, parameters, 
84362             /*type*/ undefined, body), location), 
84363             /*original*/ node);
84364         }
84365         /**
84366          * Transforms the body of a function-like node.
84367          *
84368          * @param node A function-like node.
84369          */
84370         function transformFunctionBody(node) {
84371             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
84372             var singleLine = false; // indicates whether the block *may* be emitted as a single line
84373             var statementsLocation;
84374             var closeBraceLocation;
84375             var prologue = [];
84376             var statements = [];
84377             var body = node.body;
84378             var statementOffset;
84379             resumeLexicalEnvironment();
84380             if (ts.isBlock(body)) {
84381                 // ensureUseStrict is false because no new prologue-directive should be added.
84382                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
84383                 statementOffset = ts.addStandardPrologue(prologue, body.statements, /*ensureUseStrict*/ false);
84384                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedFunction);
84385                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor, ts.isHoistedVariableStatement);
84386             }
84387             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
84388             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
84389             if (ts.isBlock(body)) {
84390                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
84391                 statementOffset = ts.addCustomPrologue(statements, body.statements, statementOffset, visitor);
84392                 statementsLocation = body.statements;
84393                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
84394                 // If the original body was a multi-line block, this must be a multi-line block.
84395                 if (!multiLine && body.multiLine) {
84396                     multiLine = true;
84397                 }
84398             }
84399             else {
84400                 ts.Debug.assert(node.kind === 202 /* ArrowFunction */);
84401                 // To align with the old emitter, we use a synthetic end position on the location
84402                 // for the statement list we synthesize when we down-level an arrow function with
84403                 // an expression function body. This prevents both comments and source maps from
84404                 // being emitted for the end position only.
84405                 statementsLocation = ts.moveRangeEnd(body, -1);
84406                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
84407                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
84408                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
84409                         singleLine = true;
84410                     }
84411                     else {
84412                         multiLine = true;
84413                     }
84414                 }
84415                 var expression = ts.visitNode(body, visitor, ts.isExpression);
84416                 var returnStatement = ts.createReturn(expression);
84417                 ts.setTextRange(returnStatement, body);
84418                 ts.moveSyntheticComments(returnStatement, body);
84419                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
84420                 statements.push(returnStatement);
84421                 // To align with the source map emit for the old emitter, we set a custom
84422                 // source map location for the close brace.
84423                 closeBraceLocation = body;
84424             }
84425             ts.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
84426             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
84427             insertCaptureThisForNodeIfNeeded(prologue, node);
84428             // If we added any final generated statements, this must be a multi-line block
84429             if (ts.some(prologue)) {
84430                 multiLine = true;
84431             }
84432             statements.unshift.apply(statements, prologue);
84433             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
84434                 // no changes were made, preserve the tree
84435                 return body;
84436             }
84437             var block = ts.createBlock(ts.setTextRange(ts.createNodeArray(statements), statementsLocation), multiLine);
84438             ts.setTextRange(block, node.body);
84439             if (!multiLine && singleLine) {
84440                 ts.setEmitFlags(block, 1 /* SingleLine */);
84441             }
84442             if (closeBraceLocation) {
84443                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
84444             }
84445             ts.setOriginalNode(block, node.body);
84446             return block;
84447         }
84448         function visitBlock(node, isFunctionBody) {
84449             if (isFunctionBody) {
84450                 // A function body is not a block scope.
84451                 return ts.visitEachChild(node, visitor, context);
84452             }
84453             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
84454                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
84455                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
84456             var updated = ts.visitEachChild(node, visitor, context);
84457             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84458             return updated;
84459         }
84460         /**
84461          * Visits an ExpressionStatement that contains a destructuring assignment.
84462          *
84463          * @param node An ExpressionStatement node.
84464          */
84465         function visitExpressionStatement(node) {
84466             // If we are here it is most likely because our expression is a destructuring assignment.
84467             switch (node.expression.kind) {
84468                 case 200 /* ParenthesizedExpression */:
84469                     return ts.updateExpressionStatement(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84470                 case 209 /* BinaryExpression */:
84471                     return ts.updateExpressionStatement(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84472             }
84473             return ts.visitEachChild(node, visitor, context);
84474         }
84475         /**
84476          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
84477          *
84478          * @param node A ParenthesizedExpression node.
84479          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84480          *                                of a destructuring assignment.
84481          */
84482         function visitParenthesizedExpression(node, needsDestructuringValue) {
84483             // If we are here it is most likely because our expression is a destructuring assignment.
84484             if (!needsDestructuringValue) {
84485                 // By default we always emit the RHS at the end of a flattened destructuring
84486                 // expression. If we are in a state where we do not need the destructuring value,
84487                 // we pass that information along to the children that care about it.
84488                 switch (node.expression.kind) {
84489                     case 200 /* ParenthesizedExpression */:
84490                         return ts.updateParen(node, visitParenthesizedExpression(node.expression, /*needsDestructuringValue*/ false));
84491                     case 209 /* BinaryExpression */:
84492                         return ts.updateParen(node, visitBinaryExpression(node.expression, /*needsDestructuringValue*/ false));
84493                 }
84494             }
84495             return ts.visitEachChild(node, visitor, context);
84496         }
84497         /**
84498          * Visits a BinaryExpression that contains a destructuring assignment.
84499          *
84500          * @param node A BinaryExpression node.
84501          * @param needsDestructuringValue A value indicating whether we need to hold onto the rhs
84502          *                                of a destructuring assignment.
84503          */
84504         function visitBinaryExpression(node, needsDestructuringValue) {
84505             // If we are here it is because this is a destructuring assignment.
84506             if (ts.isDestructuringAssignment(node)) {
84507                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, needsDestructuringValue);
84508             }
84509             return ts.visitEachChild(node, visitor, context);
84510         }
84511         function isVariableStatementOfTypeScriptClassWrapper(node) {
84512             return node.declarationList.declarations.length === 1
84513                 && !!node.declarationList.declarations[0].initializer
84514                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
84515         }
84516         function visitVariableStatement(node) {
84517             var ancestorFacts = enterSubtree(0 /* None */, ts.hasModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
84518             var updated;
84519             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
84520                 // we are inside a converted loop - hoist variable declarations
84521                 var assignments = void 0;
84522                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
84523                     var decl = _a[_i];
84524                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
84525                     if (decl.initializer) {
84526                         var assignment = void 0;
84527                         if (ts.isBindingPattern(decl.name)) {
84528                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
84529                         }
84530                         else {
84531                             assignment = ts.createBinary(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
84532                             ts.setTextRange(assignment, decl);
84533                         }
84534                         assignments = ts.append(assignments, assignment);
84535                     }
84536                 }
84537                 if (assignments) {
84538                     updated = ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(assignments)), node);
84539                 }
84540                 else {
84541                     // none of declarations has initializer - the entire variable statement can be deleted
84542                     updated = undefined;
84543                 }
84544             }
84545             else {
84546                 updated = ts.visitEachChild(node, visitor, context);
84547             }
84548             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84549             return updated;
84550         }
84551         /**
84552          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
84553          *
84554          * @param node A VariableDeclarationList node.
84555          */
84556         function visitVariableDeclarationList(node) {
84557             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
84558                 if (node.flags & 3 /* BlockScoped */) {
84559                     enableSubstitutionsForBlockScopedBindings();
84560                 }
84561                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
84562                     ? visitVariableDeclarationInLetDeclarationList
84563                     : visitVariableDeclaration);
84564                 var declarationList = ts.createVariableDeclarationList(declarations);
84565                 ts.setOriginalNode(declarationList, node);
84566                 ts.setTextRange(declarationList, node);
84567                 ts.setCommentRange(declarationList, node);
84568                 // If the first or last declaration is a binding pattern, we need to modify
84569                 // the source map range for the declaration list.
84570                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
84571                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
84572                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
84573                 }
84574                 return declarationList;
84575             }
84576             return ts.visitEachChild(node, visitor, context);
84577         }
84578         function getRangeUnion(declarations) {
84579             // declarations may not be sorted by position.
84580             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
84581             var pos = -1, end = -1;
84582             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
84583                 var node = declarations_10[_i];
84584                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
84585                 end = Math.max(end, node.end);
84586             }
84587             return ts.createRange(pos, end);
84588         }
84589         /**
84590          * Gets a value indicating whether we should emit an explicit initializer for a variable
84591          * declaration in a `let` declaration list.
84592          *
84593          * @param node A VariableDeclaration node.
84594          */
84595         function shouldEmitExplicitInitializerForLetDeclaration(node) {
84596             // Nested let bindings might need to be initialized explicitly to preserve
84597             // ES6 semantic:
84598             //
84599             //  { let x = 1; }
84600             //  { let x; } // x here should be undefined. not 1
84601             //
84602             // Top level bindings never collide with anything and thus don't require
84603             // explicit initialization. As for nested let bindings there are two cases:
84604             //
84605             // - Nested let bindings that were not renamed definitely should be
84606             //   initialized explicitly:
84607             //
84608             //    { let x = 1; }
84609             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
84610             //
84611             //   Without explicit initialization code in /*1*/ can be executed even if
84612             //   some-condition is evaluated to false.
84613             //
84614             // - Renaming introduces fresh name that should not collide with any
84615             //   existing names, however renamed bindings sometimes also should be
84616             //   explicitly initialized. One particular case: non-captured binding
84617             //   declared inside loop body (but not in loop initializer):
84618             //
84619             //    let x;
84620             //    for (;;) {
84621             //        let x;
84622             //    }
84623             //
84624             //   In downlevel codegen inner 'x' will be renamed so it won't collide
84625             //   with outer 'x' however it will should be reset on every iteration as
84626             //   if it was declared anew.
84627             //
84628             //   * Why non-captured binding?
84629             //     - Because if loop contains block scoped binding captured in some
84630             //       function then loop body will be rewritten to have a fresh scope
84631             //       on every iteration so everything will just work.
84632             //
84633             //   * Why loop initializer is excluded?
84634             //     - Since we've introduced a fresh name it already will be undefined.
84635             var flags = resolver.getNodeCheckFlags(node);
84636             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
84637             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
84638             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
84639                 || (isCapturedInFunction
84640                     && isDeclaredInLoop
84641                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
84642             var emitExplicitInitializer = !emittedAsTopLevel
84643                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
84644                 && (!resolver.isDeclarationWithCollidingName(node)
84645                     || (isDeclaredInLoop
84646                         && !isCapturedInFunction
84647                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
84648             return emitExplicitInitializer;
84649         }
84650         /**
84651          * Visits a VariableDeclaration in a `let` declaration list.
84652          *
84653          * @param node A VariableDeclaration node.
84654          */
84655         function visitVariableDeclarationInLetDeclarationList(node) {
84656             // For binding pattern names that lack initializers there is no point to emit
84657             // explicit initializer since downlevel codegen for destructuring will fail
84658             // in the absence of initializer so all binding elements will say uninitialized
84659             var name = node.name;
84660             if (ts.isBindingPattern(name)) {
84661                 return visitVariableDeclaration(node);
84662             }
84663             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
84664                 var clone_3 = ts.getMutableClone(node);
84665                 clone_3.initializer = ts.createVoidZero();
84666                 return clone_3;
84667             }
84668             return ts.visitEachChild(node, visitor, context);
84669         }
84670         /**
84671          * Visits a VariableDeclaration node with a binding pattern.
84672          *
84673          * @param node A VariableDeclaration node.
84674          */
84675         function visitVariableDeclaration(node) {
84676             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
84677             var updated;
84678             if (ts.isBindingPattern(node.name)) {
84679                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
84680                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
84681             }
84682             else {
84683                 updated = ts.visitEachChild(node, visitor, context);
84684             }
84685             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84686             return updated;
84687         }
84688         function recordLabel(node) {
84689             convertedLoopState.labels.set(ts.idText(node.label), true);
84690         }
84691         function resetLabel(node) {
84692             convertedLoopState.labels.set(ts.idText(node.label), false);
84693         }
84694         function visitLabeledStatement(node) {
84695             if (convertedLoopState && !convertedLoopState.labels) {
84696                 convertedLoopState.labels = ts.createMap();
84697             }
84698             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
84699             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
84700                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
84701                 : ts.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, ts.liftToBlock), node, convertedLoopState && resetLabel);
84702         }
84703         function visitIterationStatement(node, outermostLabeledStatement) {
84704             switch (node.kind) {
84705                 case 228 /* DoStatement */:
84706                 case 229 /* WhileStatement */:
84707                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
84708                 case 230 /* ForStatement */:
84709                     return visitForStatement(node, outermostLabeledStatement);
84710                 case 231 /* ForInStatement */:
84711                     return visitForInStatement(node, outermostLabeledStatement);
84712                 case 232 /* ForOfStatement */:
84713                     return visitForOfStatement(node, outermostLabeledStatement);
84714             }
84715         }
84716         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
84717             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
84718             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
84719             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
84720             return updated;
84721         }
84722         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
84723             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
84724         }
84725         function visitForStatement(node, outermostLabeledStatement) {
84726             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
84727         }
84728         function visitForInStatement(node, outermostLabeledStatement) {
84729             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
84730         }
84731         function visitForOfStatement(node, outermostLabeledStatement) {
84732             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
84733         }
84734         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
84735             var statements = [];
84736             var initializer = node.initializer;
84737             if (ts.isVariableDeclarationList(initializer)) {
84738                 if (node.initializer.flags & 3 /* BlockScoped */) {
84739                     enableSubstitutionsForBlockScopedBindings();
84740                 }
84741                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
84742                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
84743                     // This works whether the declaration is a var, let, or const.
84744                     // It will use rhsIterationValue _a[_i] as the initializer.
84745                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
84746                     var declarationList = ts.setTextRange(ts.createVariableDeclarationList(declarations), node.initializer);
84747                     ts.setOriginalNode(declarationList, node.initializer);
84748                     // Adjust the source map range for the first declaration to align with the old
84749                     // emitter.
84750                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
84751                     statements.push(ts.createVariableStatement(
84752                     /*modifiers*/ undefined, declarationList));
84753                 }
84754                 else {
84755                     // The following call does not include the initializer, so we have
84756                     // to emit it separately.
84757                     statements.push(ts.setTextRange(ts.createVariableStatement(
84758                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclarationList([
84759                         ts.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : ts.createTempVariable(/*recordTempVariable*/ undefined), 
84760                         /*type*/ undefined, boundValue)
84761                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
84762                 }
84763             }
84764             else {
84765                 // Initializer is an expression. Emit the expression in the body, so that it's
84766                 // evaluated on every iteration.
84767                 var assignment = ts.createAssignment(initializer, boundValue);
84768                 if (ts.isDestructuringAssignment(assignment)) {
84769                     ts.aggregateTransformFlags(assignment);
84770                     statements.push(ts.createExpressionStatement(visitBinaryExpression(assignment, /*needsDestructuringValue*/ false)));
84771                 }
84772                 else {
84773                     assignment.end = initializer.end;
84774                     statements.push(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
84775                 }
84776             }
84777             if (convertedLoopBodyStatements) {
84778                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
84779             }
84780             else {
84781                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
84782                 if (ts.isBlock(statement)) {
84783                     return ts.updateBlock(statement, ts.setTextRange(ts.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
84784                 }
84785                 else {
84786                     statements.push(statement);
84787                     return createSyntheticBlockForConvertedStatements(statements);
84788                 }
84789             }
84790         }
84791         function createSyntheticBlockForConvertedStatements(statements) {
84792             return ts.setEmitFlags(ts.createBlock(ts.createNodeArray(statements), 
84793             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
84794         }
84795         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
84796             // The following ES6 code:
84797             //
84798             //    for (let v of expr) { }
84799             //
84800             // should be emitted as
84801             //
84802             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
84803             //        var v = _a[_i];
84804             //    }
84805             //
84806             // where _a and _i are temps emitted to capture the RHS and the counter,
84807             // respectively.
84808             // When the left hand side is an expression instead of a let declaration,
84809             // the "let v" is not emitted.
84810             // When the left hand side is a let/const, the v is renamed if there is
84811             // another v in scope.
84812             // Note that all assignments to the LHS are emitted in the body, including
84813             // all destructuring.
84814             // Note also that because an extra statement is needed to assign to the LHS,
84815             // for-of bodies are always emitted as blocks.
84816             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84817             // In the case where the user wrote an identifier as the RHS, like this:
84818             //
84819             //     for (let v of arr) { }
84820             //
84821             // we don't want to emit a temporary variable for the RHS, just use it directly.
84822             var counter = ts.createLoopVariable();
84823             var rhsReference = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84824             // The old emitter does not emit source maps for the expression
84825             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
84826             var forStatement = ts.setTextRange(ts.createFor(
84827             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84828                 ts.setTextRange(ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0)), ts.moveRangePos(node.expression, -1)),
84829                 ts.setTextRange(ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression), node.expression)
84830             ]), node.expression), 2097152 /* NoHoisting */), 
84831             /*condition*/ ts.setTextRange(ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length")), node.expression), 
84832             /*incrementor*/ ts.setTextRange(ts.createPostfixIncrement(counter), node.expression), 
84833             /*statement*/ convertForOfStatementHead(node, ts.createElementAccess(rhsReference, counter), convertedLoopBodyStatements)), 
84834             /*location*/ node);
84835             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
84836             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
84837             ts.setTextRange(forStatement, node);
84838             return ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
84839         }
84840         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
84841             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
84842             var iterator = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(expression) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84843             var result = ts.isIdentifier(expression) ? ts.getGeneratedNameForNode(iterator) : ts.createTempVariable(/*recordTempVariable*/ undefined);
84844             var errorRecord = ts.createUniqueName("e");
84845             var catchVariable = ts.getGeneratedNameForNode(errorRecord);
84846             var returnMethod = ts.createTempVariable(/*recordTempVariable*/ undefined);
84847             var values = ts.createValuesHelper(context, expression, node.expression);
84848             var next = ts.createCall(ts.createPropertyAccess(iterator, "next"), /*typeArguments*/ undefined, []);
84849             hoistVariableDeclaration(errorRecord);
84850             hoistVariableDeclaration(returnMethod);
84851             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
84852             var initializer = ancestorFacts & 1024 /* IterationContainer */
84853                 ? ts.inlineExpressions([ts.createAssignment(errorRecord, ts.createVoidZero()), values])
84854                 : values;
84855             var forStatement = ts.setEmitFlags(ts.setTextRange(ts.createFor(
84856             /*initializer*/ ts.setEmitFlags(ts.setTextRange(ts.createVariableDeclarationList([
84857                 ts.setTextRange(ts.createVariableDeclaration(iterator, /*type*/ undefined, initializer), node.expression),
84858                 ts.createVariableDeclaration(result, /*type*/ undefined, next)
84859             ]), node.expression), 2097152 /* NoHoisting */), 
84860             /*condition*/ ts.createLogicalNot(ts.createPropertyAccess(result, "done")), 
84861             /*incrementor*/ ts.createAssignment(result, next), 
84862             /*statement*/ convertForOfStatementHead(node, ts.createPropertyAccess(result, "value"), convertedLoopBodyStatements)), 
84863             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
84864             return ts.createTry(ts.createBlock([
84865                 ts.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
84866             ]), ts.createCatchClause(ts.createVariableDeclaration(catchVariable), ts.setEmitFlags(ts.createBlock([
84867                 ts.createExpressionStatement(ts.createAssignment(errorRecord, ts.createObjectLiteral([
84868                     ts.createPropertyAssignment("error", catchVariable)
84869                 ])))
84870             ]), 1 /* SingleLine */)), ts.createBlock([
84871                 ts.createTry(
84872                 /*tryBlock*/ ts.createBlock([
84873                     ts.setEmitFlags(ts.createIf(ts.createLogicalAnd(ts.createLogicalAnd(result, ts.createLogicalNot(ts.createPropertyAccess(result, "done"))), ts.createAssignment(returnMethod, ts.createPropertyAccess(iterator, "return"))), ts.createExpressionStatement(ts.createFunctionCall(returnMethod, iterator, []))), 1 /* SingleLine */),
84874                 ]), 
84875                 /*catchClause*/ undefined, 
84876                 /*finallyBlock*/ ts.setEmitFlags(ts.createBlock([
84877                     ts.setEmitFlags(ts.createIf(errorRecord, ts.createThrow(ts.createPropertyAccess(errorRecord, "error"))), 1 /* SingleLine */)
84878                 ]), 1 /* SingleLine */))
84879             ]));
84880         }
84881         /**
84882          * Visits an ObjectLiteralExpression with computed property names.
84883          *
84884          * @param node An ObjectLiteralExpression node.
84885          */
84886         function visitObjectLiteralExpression(node) {
84887             // We are here because a ComputedPropertyName was used somewhere in the expression.
84888             var properties = node.properties;
84889             var numProperties = properties.length;
84890             // Find the first computed property.
84891             // Everything until that point can be emitted as part of the initial object literal.
84892             var numInitialProperties = numProperties;
84893             var numInitialPropertiesWithoutYield = numProperties;
84894             for (var i = 0; i < numProperties; i++) {
84895                 var property = properties[i];
84896                 if ((property.transformFlags & 262144 /* ContainsYield */ && hierarchyFacts & 4 /* AsyncFunctionBody */)
84897                     && i < numInitialPropertiesWithoutYield) {
84898                     numInitialPropertiesWithoutYield = i;
84899                 }
84900                 if (property.name.kind === 154 /* ComputedPropertyName */) {
84901                     numInitialProperties = i;
84902                     break;
84903                 }
84904             }
84905             if (numInitialProperties !== numProperties) {
84906                 if (numInitialPropertiesWithoutYield < numInitialProperties) {
84907                     numInitialProperties = numInitialPropertiesWithoutYield;
84908                 }
84909                 // For computed properties, we need to create a unique handle to the object
84910                 // literal so we can modify it without risking internal assignments tainting the object.
84911                 var temp = ts.createTempVariable(hoistVariableDeclaration);
84912                 // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
84913                 var expressions = [];
84914                 var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), 65536 /* Indented */));
84915                 if (node.multiLine) {
84916                     ts.startOnNewLine(assignment);
84917                 }
84918                 expressions.push(assignment);
84919                 addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
84920                 // We need to clone the temporary identifier so that we can write it on a
84921                 // new line
84922                 expressions.push(node.multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
84923                 return ts.inlineExpressions(expressions);
84924             }
84925             return ts.visitEachChild(node, visitor, context);
84926         }
84927         function shouldConvertPartOfIterationStatement(node) {
84928             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
84929         }
84930         function shouldConvertInitializerOfForStatement(node) {
84931             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
84932         }
84933         function shouldConvertConditionOfForStatement(node) {
84934             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
84935         }
84936         function shouldConvertIncrementorOfForStatement(node) {
84937             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
84938         }
84939         function shouldConvertIterationStatement(node) {
84940             return shouldConvertBodyOfIterationStatement(node)
84941                 || shouldConvertInitializerOfForStatement(node);
84942         }
84943         function shouldConvertBodyOfIterationStatement(node) {
84944             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
84945         }
84946         /**
84947          * Records constituents of name for the given variable to be hoisted in the outer scope.
84948          */
84949         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
84950             if (!state.hoistedLocalVariables) {
84951                 state.hoistedLocalVariables = [];
84952             }
84953             visit(node.name);
84954             function visit(node) {
84955                 if (node.kind === 75 /* Identifier */) {
84956                     state.hoistedLocalVariables.push(node);
84957                 }
84958                 else {
84959                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
84960                         var element = _a[_i];
84961                         if (!ts.isOmittedExpression(element)) {
84962                             visit(element.name);
84963                         }
84964                     }
84965                 }
84966             }
84967         }
84968         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
84969             if (!shouldConvertIterationStatement(node)) {
84970                 var saveAllowedNonLabeledJumps = void 0;
84971                 if (convertedLoopState) {
84972                     // we get here if we are trying to emit normal loop loop inside converted loop
84973                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
84974                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
84975                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
84976                 }
84977                 var result = convert
84978                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
84979                     : ts.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
84980                 if (convertedLoopState) {
84981                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
84982                 }
84983                 return result;
84984             }
84985             var currentState = createConvertedLoopState(node);
84986             var statements = [];
84987             var outerConvertedLoopState = convertedLoopState;
84988             convertedLoopState = currentState;
84989             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
84990             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
84991             convertedLoopState = outerConvertedLoopState;
84992             if (initializerFunction)
84993                 statements.push(initializerFunction.functionDeclaration);
84994             if (bodyFunction)
84995                 statements.push(bodyFunction.functionDeclaration);
84996             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
84997             if (initializerFunction) {
84998                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
84999             }
85000             var loop;
85001             if (bodyFunction) {
85002                 if (convert) {
85003                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
85004                 }
85005                 else {
85006                     var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.createBlock(bodyFunction.part, /*multiLine*/ true));
85007                     ts.aggregateTransformFlags(clone_4);
85008                     loop = ts.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
85009                 }
85010             }
85011             else {
85012                 var clone_5 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
85013                 ts.aggregateTransformFlags(clone_5);
85014                 loop = ts.restoreEnclosingLabel(clone_5, outermostLabeledStatement, convertedLoopState && resetLabel);
85015             }
85016             statements.push(loop);
85017             return statements;
85018         }
85019         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
85020             switch (node.kind) {
85021                 case 230 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
85022                 case 231 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
85023                 case 232 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
85024                 case 228 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
85025                 case 229 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
85026                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
85027             }
85028         }
85029         function convertForStatement(node, initializerFunction, convertedLoopBody) {
85030             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
85031             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
85032             return ts.updateFor(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitor, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitor, ts.isExpression), convertedLoopBody);
85033         }
85034         function convertForOfStatement(node, convertedLoopBody) {
85035             return ts.updateForOf(node, 
85036             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85037         }
85038         function convertForInStatement(node, convertedLoopBody) {
85039             return ts.updateForIn(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85040         }
85041         function convertDoStatement(node, convertedLoopBody) {
85042             return ts.updateDo(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
85043         }
85044         function convertWhileStatement(node, convertedLoopBody) {
85045             return ts.updateWhile(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
85046         }
85047         function createConvertedLoopState(node) {
85048             var loopInitializer;
85049             switch (node.kind) {
85050                 case 230 /* ForStatement */:
85051                 case 231 /* ForInStatement */:
85052                 case 232 /* ForOfStatement */:
85053                     var initializer = node.initializer;
85054                     if (initializer && initializer.kind === 243 /* VariableDeclarationList */) {
85055                         loopInitializer = initializer;
85056                     }
85057                     break;
85058             }
85059             // variables that will be passed to the loop as parameters
85060             var loopParameters = [];
85061             // variables declared in the loop initializer that will be changed inside the loop
85062             var loopOutParameters = [];
85063             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
85064                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
85065                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
85066                     var decl = _a[_i];
85067                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85068                 }
85069             }
85070             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
85071             if (convertedLoopState) {
85072                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
85073                 // if outer converted loop has already accumulated some state - pass it through
85074                 if (convertedLoopState.argumentsName) {
85075                     // outer loop has already used 'arguments' so we've already have some name to alias it
85076                     // use the same name in all nested loops
85077                     currentState.argumentsName = convertedLoopState.argumentsName;
85078                 }
85079                 if (convertedLoopState.thisName) {
85080                     // outer loop has already used 'this' so we've already have some name to alias it
85081                     // use the same name in all nested loops
85082                     currentState.thisName = convertedLoopState.thisName;
85083                 }
85084                 if (convertedLoopState.hoistedLocalVariables) {
85085                     // we've already collected some non-block scoped variable declarations in enclosing loop
85086                     // use the same storage in nested loop
85087                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
85088                 }
85089             }
85090             return currentState;
85091         }
85092         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
85093             var extraVariableDeclarations;
85094             // propagate state from the inner loop to the outer loop if necessary
85095             if (state.argumentsName) {
85096                 // if alias for arguments is set
85097                 if (outerState) {
85098                     // pass it to outer converted loop
85099                     outerState.argumentsName = state.argumentsName;
85100                 }
85101                 else {
85102                     // this is top level converted loop and we need to create an alias for 'arguments' object
85103                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.argumentsName, 
85104                     /*type*/ undefined, ts.createIdentifier("arguments")));
85105                 }
85106             }
85107             if (state.thisName) {
85108                 // if alias for this is set
85109                 if (outerState) {
85110                     // pass it to outer converted loop
85111                     outerState.thisName = state.thisName;
85112                 }
85113                 else {
85114                     // this is top level converted loop so we need to create an alias for 'this' here
85115                     // NOTE:
85116                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
85117                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
85118                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(ts.createVariableDeclaration(state.thisName, 
85119                     /*type*/ undefined, ts.createIdentifier("this")));
85120                 }
85121             }
85122             if (state.hoistedLocalVariables) {
85123                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
85124                 if (outerState) {
85125                     // pass them to outer converted loop
85126                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
85127                 }
85128                 else {
85129                     if (!extraVariableDeclarations) {
85130                         extraVariableDeclarations = [];
85131                     }
85132                     // hoist collected variable declarations
85133                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
85134                         var identifier = _a[_i];
85135                         extraVariableDeclarations.push(ts.createVariableDeclaration(identifier));
85136                     }
85137                 }
85138             }
85139             // add extra variables to hold out parameters if necessary
85140             if (state.loopOutParameters.length) {
85141                 if (!extraVariableDeclarations) {
85142                     extraVariableDeclarations = [];
85143                 }
85144                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
85145                     var outParam = _c[_b];
85146                     extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName));
85147                 }
85148             }
85149             if (state.conditionVariable) {
85150                 if (!extraVariableDeclarations) {
85151                     extraVariableDeclarations = [];
85152                 }
85153                 extraVariableDeclarations.push(ts.createVariableDeclaration(state.conditionVariable, /*type*/ undefined, ts.createFalse()));
85154             }
85155             // create variable statement to hold all introduced variable declarations
85156             if (extraVariableDeclarations) {
85157                 statements.push(ts.createVariableStatement(
85158                 /*modifiers*/ undefined, ts.createVariableDeclarationList(extraVariableDeclarations)));
85159             }
85160         }
85161         function createOutVariable(p) {
85162             return ts.createVariableDeclaration(p.originalName, /*type*/ undefined, p.outParamName);
85163         }
85164         /**
85165          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
85166          * that is captured in a closure inside of the initializer. The `_loop_init` function is
85167          * used to preserve the per-iteration environment semantics of
85168          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85169          */
85170         function createFunctionForInitializerOfForStatement(node, currentState) {
85171             var functionName = ts.createUniqueName("_loop_init");
85172             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
85173             var emitFlags = 0 /* None */;
85174             if (currentState.containsLexicalThis)
85175                 emitFlags |= 8 /* CapturesThis */;
85176             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
85177                 emitFlags |= 262144 /* AsyncFunctionBody */;
85178             var statements = [];
85179             statements.push(ts.createVariableStatement(/*modifiers*/ undefined, node.initializer));
85180             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
85181             // This transforms the following ES2015 syntax:
85182             //
85183             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
85184             //      // loop body
85185             //  }
85186             //
85187             // Into the following ES5 syntax:
85188             //
85189             //  var _loop_init_1 = function () {
85190             //      var i = (setImmediate(() => console.log(i)), 0);
85191             //      out_i_1 = i;
85192             //  };
85193             //  var out_i_1;
85194             //  _loop_init_1();
85195             //  for (var i = out_i_1; i < 2; i++) {
85196             //      // loop body
85197             //  }
85198             //
85199             // Which prevents mutations to `i` in the per-iteration environment of the body
85200             // from affecting the initial value for `i` outside of the per-iteration environment.
85201             var functionDeclaration = ts.createVariableStatement(
85202             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85203                 ts.createVariableDeclaration(functionName, 
85204                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85205                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85206                 /*name*/ undefined, 
85207                 /*typeParameters*/ undefined, 
85208                 /*parameters*/ undefined, 
85209                 /*type*/ undefined, ts.visitNode(ts.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
85210             ]), 2097152 /* NoHoisting */));
85211             var part = ts.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
85212             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85213         }
85214         /**
85215          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
85216          * that is captured in a closure inside of the loop body. The `_loop` function is used to
85217          * preserve the per-iteration environment semantics of
85218          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
85219          */
85220         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
85221             var functionName = ts.createUniqueName("_loop");
85222             startLexicalEnvironment();
85223             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock);
85224             var lexicalEnvironment = endLexicalEnvironment();
85225             var statements = [];
85226             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
85227                 // If a block-scoped variable declared in the initializer of `node` is captured in
85228                 // the condition or incrementor, we must move the condition and incrementor into
85229                 // the body of the for loop.
85230                 //
85231                 // This transforms the following ES2015 syntax:
85232                 //
85233                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
85234                 //      // loop body
85235                 //  }
85236                 //
85237                 // Into the following ES5 syntax:
85238                 //
85239                 //  var _loop_1 = function (i) {
85240                 //      if (inc_1)
85241                 //          setImmediate(() => console.log(i)), i++;
85242                 //      else
85243                 //          inc_1 = true;
85244                 //      if (!(setImmediate(() => console.log(i)), i < 2))
85245                 //          return out_i_1 = i, "break";
85246                 //      // loop body
85247                 //      out_i_1 = i;
85248                 //  }
85249                 //  var out_i_1, inc_1 = false;
85250                 //  for (var i = 0;;) {
85251                 //      var state_1 = _loop_1(i);
85252                 //      i = out_i_1;
85253                 //      if (state_1 === "break")
85254                 //          break;
85255                 //  }
85256                 //
85257                 // Which prevents mutations to `i` in the per-iteration environment of the body
85258                 // from affecting the value of `i` in the previous per-iteration environment.
85259                 //
85260                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
85261                 // environment that is carried over to the next iteration of the loop. As a result,
85262                 // we must indicate whether this is the first evaluation of the loop body so that
85263                 // we only evaluate the incrementor on subsequent evaluations.
85264                 currentState.conditionVariable = ts.createUniqueName("inc");
85265                 statements.push(ts.createIf(currentState.conditionVariable, ts.createStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), ts.createStatement(ts.createAssignment(currentState.conditionVariable, ts.createTrue()))));
85266                 if (shouldConvertConditionOfForStatement(node)) {
85267                     statements.push(ts.createIf(ts.createPrefix(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(ts.createBreak(), visitor, ts.isStatement)));
85268                 }
85269             }
85270             if (ts.isBlock(statement)) {
85271                 ts.addRange(statements, statement.statements);
85272             }
85273             else {
85274                 statements.push(statement);
85275             }
85276             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
85277             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
85278             var loopBody = ts.createBlock(statements, /*multiLine*/ true);
85279             if (ts.isBlock(statement))
85280                 ts.setOriginalNode(loopBody, statement);
85281             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
85282             var emitFlags = 0;
85283             if (currentState.containsLexicalThis)
85284                 emitFlags |= 8 /* CapturesThis */;
85285             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
85286                 emitFlags |= 262144 /* AsyncFunctionBody */;
85287             // This transforms the following ES2015 syntax (in addition to other variations):
85288             //
85289             //  for (let i = 0; i < 2; i++) {
85290             //      setImmediate(() => console.log(i));
85291             //  }
85292             //
85293             // Into the following ES5 syntax:
85294             //
85295             //  var _loop_1 = function (i) {
85296             //      setImmediate(() => console.log(i));
85297             //  };
85298             //  for (var i = 0; i < 2; i++) {
85299             //      _loop_1(i);
85300             //  }
85301             var functionDeclaration = ts.createVariableStatement(
85302             /*modifiers*/ undefined, ts.setEmitFlags(ts.createVariableDeclarationList([
85303                 ts.createVariableDeclaration(functionName, 
85304                 /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(
85305                 /*modifiers*/ undefined, containsYield ? ts.createToken(41 /* AsteriskToken */) : undefined, 
85306                 /*name*/ undefined, 
85307                 /*typeParameters*/ undefined, currentState.loopParameters, 
85308                 /*type*/ undefined, loopBody), emitFlags))
85309             ]), 2097152 /* NoHoisting */));
85310             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
85311             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
85312         }
85313         function copyOutParameter(outParam, copyDirection) {
85314             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
85315             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
85316             return ts.createBinary(target, 62 /* EqualsToken */, source);
85317         }
85318         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
85319             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
85320                 var outParam = outParams_1[_i];
85321                 if (outParam.flags & partFlags) {
85322                     statements.push(ts.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
85323                 }
85324             }
85325         }
85326         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
85327             var call = ts.createCall(initFunctionExpressionName, /*typeArguments*/ undefined, []);
85328             var callResult = containsYield
85329                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85330                 : call;
85331             return ts.createStatement(callResult);
85332         }
85333         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
85334             var statements = [];
85335             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
85336             // simple loops are emitted as just 'loop()';
85337             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
85338             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
85339                 !state.labeledNonLocalBreaks &&
85340                 !state.labeledNonLocalContinues;
85341             var call = ts.createCall(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
85342             var callResult = containsYield
85343                 ? ts.createYield(ts.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
85344                 : call;
85345             if (isSimpleLoop) {
85346                 statements.push(ts.createExpressionStatement(callResult));
85347                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85348             }
85349             else {
85350                 var loopResultName = ts.createUniqueName("state");
85351                 var stateVariable = ts.createVariableStatement(
85352                 /*modifiers*/ undefined, ts.createVariableDeclarationList([ts.createVariableDeclaration(loopResultName, /*type*/ undefined, callResult)]));
85353                 statements.push(stateVariable);
85354                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
85355                 if (state.nonLocalJumps & 8 /* Return */) {
85356                     var returnStatement = void 0;
85357                     if (outerState) {
85358                         outerState.nonLocalJumps |= 8 /* Return */;
85359                         returnStatement = ts.createReturn(loopResultName);
85360                     }
85361                     else {
85362                         returnStatement = ts.createReturn(ts.createPropertyAccess(loopResultName, "value"));
85363                     }
85364                     statements.push(ts.createIf(ts.createBinary(ts.createTypeOf(loopResultName), 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("object")), returnStatement));
85365                 }
85366                 if (state.nonLocalJumps & 2 /* Break */) {
85367                     statements.push(ts.createIf(ts.createBinary(loopResultName, 36 /* EqualsEqualsEqualsToken */, ts.createLiteral("break")), ts.createBreak()));
85368                 }
85369                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
85370                     var caseClauses = [];
85371                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
85372                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
85373                     statements.push(ts.createSwitch(loopResultName, ts.createCaseBlock(caseClauses)));
85374                 }
85375             }
85376             return statements;
85377         }
85378         function setLabeledJump(state, isBreak, labelText, labelMarker) {
85379             if (isBreak) {
85380                 if (!state.labeledNonLocalBreaks) {
85381                     state.labeledNonLocalBreaks = ts.createMap();
85382                 }
85383                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
85384             }
85385             else {
85386                 if (!state.labeledNonLocalContinues) {
85387                     state.labeledNonLocalContinues = ts.createMap();
85388                 }
85389                 state.labeledNonLocalContinues.set(labelText, labelMarker);
85390             }
85391         }
85392         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
85393             if (!table) {
85394                 return;
85395             }
85396             table.forEach(function (labelMarker, labelText) {
85397                 var statements = [];
85398                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
85399                 // then emit labeled break\continue
85400                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
85401                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
85402                     var label = ts.createIdentifier(labelText);
85403                     statements.push(isBreak ? ts.createBreak(label) : ts.createContinue(label));
85404                 }
85405                 else {
85406                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
85407                     statements.push(ts.createReturn(loopResultName));
85408                 }
85409                 caseClauses.push(ts.createCaseClause(ts.createLiteral(labelMarker), statements));
85410             });
85411         }
85412         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
85413             var name = decl.name;
85414             if (ts.isBindingPattern(name)) {
85415                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
85416                     var element = _a[_i];
85417                     if (!ts.isOmittedExpression(element)) {
85418                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
85419                     }
85420                 }
85421             }
85422             else {
85423                 loopParameters.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
85424                 var checkFlags = resolver.getNodeCheckFlags(decl);
85425                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
85426                     var outParamName = ts.createUniqueName("out_" + ts.idText(name));
85427                     var flags = 0;
85428                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
85429                         flags |= 1 /* Body */;
85430                     }
85431                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
85432                         flags |= 2 /* Initializer */;
85433                     }
85434                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
85435                 }
85436             }
85437         }
85438         /**
85439          * Adds the members of an object literal to an array of expressions.
85440          *
85441          * @param expressions An array of expressions.
85442          * @param node An ObjectLiteralExpression node.
85443          * @param receiver The receiver for members of the ObjectLiteralExpression.
85444          * @param numInitialNonComputedProperties The number of initial properties without
85445          *                                        computed property names.
85446          */
85447         function addObjectLiteralMembers(expressions, node, receiver, start) {
85448             var properties = node.properties;
85449             var numProperties = properties.length;
85450             for (var i = start; i < numProperties; i++) {
85451                 var property = properties[i];
85452                 switch (property.kind) {
85453                     case 163 /* GetAccessor */:
85454                     case 164 /* SetAccessor */:
85455                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
85456                         if (property === accessors.firstAccessor) {
85457                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
85458                         }
85459                         break;
85460                     case 161 /* MethodDeclaration */:
85461                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
85462                         break;
85463                     case 281 /* PropertyAssignment */:
85464                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
85465                         break;
85466                     case 282 /* ShorthandPropertyAssignment */:
85467                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
85468                         break;
85469                     default:
85470                         ts.Debug.failBadSyntaxKind(node);
85471                         break;
85472                 }
85473             }
85474         }
85475         /**
85476          * Transforms a PropertyAssignment node into an expression.
85477          *
85478          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
85479          * @param property The PropertyAssignment node.
85480          * @param receiver The receiver for the assignment.
85481          */
85482         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85483             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
85484             ts.setTextRange(expression, property);
85485             if (startsOnNewLine) {
85486                 ts.startOnNewLine(expression);
85487             }
85488             return expression;
85489         }
85490         /**
85491          * Transforms a ShorthandPropertyAssignment node into an expression.
85492          *
85493          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
85494          * @param property The ShorthandPropertyAssignment node.
85495          * @param receiver The receiver for the assignment.
85496          */
85497         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
85498             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.getSynthesizedClone(property.name));
85499             ts.setTextRange(expression, property);
85500             if (startsOnNewLine) {
85501                 ts.startOnNewLine(expression);
85502             }
85503             return expression;
85504         }
85505         /**
85506          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
85507          *
85508          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
85509          * @param method The MethodDeclaration node.
85510          * @param receiver The receiver for the assignment.
85511          */
85512         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
85513             var expression = ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
85514             ts.setTextRange(expression, method);
85515             if (startsOnNewLine) {
85516                 ts.startOnNewLine(expression);
85517             }
85518             return expression;
85519         }
85520         function visitCatchClause(node) {
85521             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
85522             var updated;
85523             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
85524             if (ts.isBindingPattern(node.variableDeclaration.name)) {
85525                 var temp = ts.createTempVariable(/*recordTempVariable*/ undefined);
85526                 var newVariableDeclaration = ts.createVariableDeclaration(temp);
85527                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
85528                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
85529                 var list = ts.createVariableDeclarationList(vars);
85530                 ts.setTextRange(list, node.variableDeclaration);
85531                 var destructure = ts.createVariableStatement(/*modifiers*/ undefined, list);
85532                 updated = ts.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
85533             }
85534             else {
85535                 updated = ts.visitEachChild(node, visitor, context);
85536             }
85537             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
85538             return updated;
85539         }
85540         function addStatementToStartOfBlock(block, statement) {
85541             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
85542             return ts.updateBlock(block, __spreadArrays([statement], transformedStatements));
85543         }
85544         /**
85545          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
85546          * PropertyAssignment.
85547          *
85548          * @param node A MethodDeclaration node.
85549          */
85550         function visitMethodDeclaration(node) {
85551             // We should only get here for methods on an object literal with regular identifier names.
85552             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
85553             // Methods with computed property names are handled in visitObjectLiteralExpression.
85554             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85555             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
85556             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
85557             return ts.setTextRange(ts.createPropertyAssignment(node.name, functionExpression), 
85558             /*location*/ node);
85559         }
85560         /**
85561          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
85562          *
85563          * @param node An AccessorDeclaration node.
85564          */
85565         function visitAccessorDeclaration(node) {
85566             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
85567             var savedConvertedLoopState = convertedLoopState;
85568             convertedLoopState = undefined;
85569             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
85570             var updated;
85571             var parameters = ts.visitParameterList(node.parameters, visitor, context);
85572             var body = transformFunctionBody(node);
85573             if (node.kind === 163 /* GetAccessor */) {
85574                 updated = ts.updateGetAccessor(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
85575             }
85576             else {
85577                 updated = ts.updateSetAccessor(node, node.decorators, node.modifiers, node.name, parameters, body);
85578             }
85579             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
85580             convertedLoopState = savedConvertedLoopState;
85581             return updated;
85582         }
85583         /**
85584          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
85585          *
85586          * @param node A ShorthandPropertyAssignment node.
85587          */
85588         function visitShorthandPropertyAssignment(node) {
85589             return ts.setTextRange(ts.createPropertyAssignment(node.name, ts.getSynthesizedClone(node.name)), 
85590             /*location*/ node);
85591         }
85592         function visitComputedPropertyName(node) {
85593             return ts.visitEachChild(node, visitor, context);
85594         }
85595         /**
85596          * Visits a YieldExpression node.
85597          *
85598          * @param node A YieldExpression node.
85599          */
85600         function visitYieldExpression(node) {
85601             // `yield` expressions are transformed using the generators transformer.
85602             return ts.visitEachChild(node, visitor, context);
85603         }
85604         /**
85605          * Visits an ArrayLiteralExpression that contains a spread element.
85606          *
85607          * @param node An ArrayLiteralExpression node.
85608          */
85609         function visitArrayLiteralExpression(node) {
85610             if (ts.some(node.elements, ts.isSpreadElement)) {
85611                 // We are here because we contain a SpreadElementExpression.
85612                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
85613             }
85614             return ts.visitEachChild(node, visitor, context);
85615         }
85616         /**
85617          * Visits a CallExpression that contains either a spread element or `super`.
85618          *
85619          * @param node a CallExpression.
85620          */
85621         function visitCallExpression(node) {
85622             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
85623                 return visitTypeScriptClassWrapper(node);
85624             }
85625             var expression = ts.skipOuterExpressions(node.expression);
85626             if (expression.kind === 102 /* SuperKeyword */ ||
85627                 ts.isSuperProperty(expression) ||
85628                 ts.some(node.arguments, ts.isSpreadElement)) {
85629                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
85630             }
85631             return ts.updateCall(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
85632             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85633         }
85634         function visitTypeScriptClassWrapper(node) {
85635             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
85636             // The wrapper has a form similar to:
85637             //
85638             //  (function() {
85639             //      class C { // 1
85640             //      }
85641             //      C.x = 1; // 2
85642             //      return C;
85643             //  }())
85644             //
85645             // When we transform the class, we end up with something like this:
85646             //
85647             //  (function () {
85648             //      var C = (function () { // 3
85649             //          function C() {
85650             //          }
85651             //          return C; // 4
85652             //      }());
85653             //      C.x = 1;
85654             //      return C;
85655             //  }())
85656             //
85657             // We want to simplify the two nested IIFEs to end up with something like this:
85658             //
85659             //  (function () {
85660             //      function C() {
85661             //      }
85662             //      C.x = 1;
85663             //      return C;
85664             //  }())
85665             // We skip any outer expressions in a number of places to get to the innermost
85666             // expression, but we will restore them later to preserve comments and source maps.
85667             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
85668             // The class statements are the statements generated by visiting the first statement with initializer of the
85669             // body (1), while all other statements are added to remainingStatements (2)
85670             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
85671             // visit the class body statements outside of any converted loop body.
85672             var savedConvertedLoopState = convertedLoopState;
85673             convertedLoopState = undefined;
85674             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
85675             convertedLoopState = savedConvertedLoopState;
85676             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
85677             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
85678             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
85679             // We know there is only one variable declaration here as we verified this in an
85680             // earlier call to isTypeScriptClassWrapper
85681             var variable = varStatement.declarationList.declarations[0];
85682             var initializer = ts.skipOuterExpressions(variable.initializer);
85683             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
85684             // we see as an assignment, for example:
85685             //
85686             //  (function () {
85687             //      var C_1;
85688             //      var C = C_1 = (function () {
85689             //          function C() {
85690             //          }
85691             //          C.x = function () { return C_1; }
85692             //          return C;
85693             //      }());
85694             //      C = C_1 = __decorate([dec], C);
85695             //      return C;
85696             //  }())
85697             //
85698             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
85699             // The underlying call (3) is another IIFE that may contain a '_super' argument.
85700             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
85701             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
85702             var funcStatements = func.body.statements;
85703             var classBodyStart = 0;
85704             var classBodyEnd = -1;
85705             var statements = [];
85706             if (aliasAssignment) {
85707                 // If we have a class alias assignment, we need to move it to the down-level constructor
85708                 // function we generated for the class.
85709                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
85710                 if (extendsCall) {
85711                     statements.push(extendsCall);
85712                     classBodyStart++;
85713                 }
85714                 // The next statement is the function declaration.
85715                 statements.push(funcStatements[classBodyStart]);
85716                 classBodyStart++;
85717                 // Add the class alias following the declaration.
85718                 statements.push(ts.createExpressionStatement(ts.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
85719             }
85720             // Find the trailing 'return' statement (4)
85721             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
85722                 classBodyEnd--;
85723             }
85724             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
85725             // as we already have one that has been introduced by the 'ts' transformer.
85726             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
85727             if (classBodyEnd < -1) {
85728                 // If there were any hoisted declarations following the return statement, we should
85729                 // append them.
85730                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
85731             }
85732             // Add the remaining statements of the outer wrapper.
85733             ts.addRange(statements, remainingStatements);
85734             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
85735             // after the remaining statements from the 'ts' transformer.
85736             ts.addRange(statements, classStatements, /*start*/ 1);
85737             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
85738             // and comment locations.
85739             return ts.recreateOuterExpressions(node.expression, ts.recreateOuterExpressions(variable.initializer, ts.recreateOuterExpressions(aliasAssignment && aliasAssignment.right, ts.updateCall(call, ts.recreateOuterExpressions(call.expression, ts.updateFunctionExpression(func, 
85740             /*modifiers*/ undefined, 
85741             /*asteriskToken*/ undefined, 
85742             /*name*/ undefined, 
85743             /*typeParameters*/ undefined, func.parameters, 
85744             /*type*/ undefined, ts.updateBlock(func.body, statements))), 
85745             /*typeArguments*/ undefined, call.arguments))));
85746         }
85747         function visitImmediateSuperCallInBody(node) {
85748             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
85749         }
85750         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
85751             // We are here either because SuperKeyword was used somewhere in the expression, or
85752             // because we contain a SpreadElementExpression.
85753             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
85754                 node.expression.kind === 102 /* SuperKeyword */ ||
85755                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
85756                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85757                 if (node.expression.kind === 102 /* SuperKeyword */) {
85758                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
85759                 }
85760                 var resultingCall = void 0;
85761                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
85762                     // [source]
85763                     //      f(...a, b)
85764                     //      x.m(...a, b)
85765                     //      super(...a, b)
85766                     //      super.m(...a, b) // in static
85767                     //      super.m(...a, b) // in instance
85768                     //
85769                     // [output]
85770                     //      f.apply(void 0, a.concat([b]))
85771                     //      (_a = x).m.apply(_a, a.concat([b]))
85772                     //      _super.apply(this, a.concat([b]))
85773                     //      _super.m.apply(this, a.concat([b]))
85774                     //      _super.prototype.m.apply(this, a.concat([b]))
85775                     resultingCall = ts.createFunctionApply(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 102 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
85776                 }
85777                 else {
85778                     // [source]
85779                     //      super(a)
85780                     //      super.m(a) // in static
85781                     //      super.m(a) // in instance
85782                     //
85783                     // [output]
85784                     //      _super.call(this, a)
85785                     //      _super.m.call(this, a)
85786                     //      _super.prototype.m.call(this, a)
85787                     resultingCall = ts.createFunctionCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 102 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), 
85788                     /*location*/ node);
85789                 }
85790                 if (node.expression.kind === 102 /* SuperKeyword */) {
85791                     var initializer = ts.createLogicalOr(resultingCall, createActualThis());
85792                     resultingCall = assignToCapturedThis
85793                         ? ts.createAssignment(ts.createFileLevelUniqueName("_this"), initializer)
85794                         : initializer;
85795                 }
85796                 return ts.setOriginalNode(resultingCall, node);
85797             }
85798             return ts.visitEachChild(node, visitor, context);
85799         }
85800         /**
85801          * Visits a NewExpression that contains a spread element.
85802          *
85803          * @param node A NewExpression node.
85804          */
85805         function visitNewExpression(node) {
85806             if (ts.some(node.arguments, ts.isSpreadElement)) {
85807                 // We are here because we contain a SpreadElementExpression.
85808                 // [source]
85809                 //      new C(...a)
85810                 //
85811                 // [output]
85812                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
85813                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
85814                 return ts.createNew(ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(ts.createNodeArray(__spreadArrays([ts.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), 
85815                 /*typeArguments*/ undefined, []);
85816             }
85817             return ts.visitEachChild(node, visitor, context);
85818         }
85819         /**
85820          * Transforms an array of Expression nodes that contains a SpreadExpression.
85821          *
85822          * @param elements The array of Expression nodes.
85823          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
85824          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
85825          */
85826         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
85827             // [source]
85828             //      [a, ...b, c]
85829             //
85830             // [output (downlevelIteration)]
85831             //      __spread([a], b, [c])
85832             //
85833             // [output]
85834             //      __spreadArrays([a], b, [c])
85835             // Map spans of spread expressions into their expressions and spans of other
85836             // expressions into an array literal.
85837             var numElements = elements.length;
85838             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
85839                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
85840             }));
85841             if (compilerOptions.downlevelIteration) {
85842                 if (segments.length === 1) {
85843                     var firstSegment = segments[0];
85844                     if (isCallToHelper(firstSegment, "___spread")) {
85845                         return segments[0];
85846                     }
85847                 }
85848                 return ts.createSpreadHelper(context, segments);
85849             }
85850             else {
85851                 if (segments.length === 1) {
85852                     var firstSegment = segments[0];
85853                     if (!needsUniqueCopy
85854                         || isPackedArrayLiteral(firstSegment)
85855                         || isCallToHelper(firstSegment, "___spreadArrays")) {
85856                         return segments[0];
85857                     }
85858                 }
85859                 return ts.createSpreadArraysHelper(context, segments);
85860             }
85861         }
85862         function isPackedElement(node) {
85863             return !ts.isOmittedExpression(node);
85864         }
85865         function isPackedArrayLiteral(node) {
85866             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
85867         }
85868         function isCallToHelper(firstSegment, helperName) {
85869             return ts.isCallExpression(firstSegment)
85870                 && ts.isIdentifier(firstSegment.expression)
85871                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
85872                 && firstSegment.expression.escapedText === helperName;
85873         }
85874         function partitionSpread(node) {
85875             return ts.isSpreadElement(node)
85876                 ? visitSpanOfSpreads
85877                 : visitSpanOfNonSpreads;
85878         }
85879         function visitSpanOfSpreads(chunk) {
85880             return ts.map(chunk, visitExpressionOfSpread);
85881         }
85882         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
85883             return ts.createArrayLiteral(ts.visitNodes(ts.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
85884         }
85885         function visitSpreadElement(node) {
85886             return ts.visitNode(node.expression, visitor, ts.isExpression);
85887         }
85888         /**
85889          * Transforms the expression of a SpreadExpression node.
85890          *
85891          * @param node A SpreadExpression node.
85892          */
85893         function visitExpressionOfSpread(node) {
85894             return ts.visitNode(node.expression, visitor, ts.isExpression);
85895         }
85896         /**
85897          * Visits a template literal.
85898          *
85899          * @param node A template literal.
85900          */
85901         function visitTemplateLiteral(node) {
85902             return ts.setTextRange(ts.createLiteral(node.text), node);
85903         }
85904         /**
85905          * Visits a string literal with an extended unicode escape.
85906          *
85907          * @param node A string literal.
85908          */
85909         function visitStringLiteral(node) {
85910             if (node.hasExtendedUnicodeEscape) {
85911                 return ts.setTextRange(ts.createLiteral(node.text), node);
85912             }
85913             return node;
85914         }
85915         /**
85916          * Visits a binary or octal (ES6) numeric literal.
85917          *
85918          * @param node A string literal.
85919          */
85920         function visitNumericLiteral(node) {
85921             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
85922                 return ts.setTextRange(ts.createNumericLiteral(node.text), node);
85923             }
85924             return node;
85925         }
85926         /**
85927          * Visits a TaggedTemplateExpression node.
85928          *
85929          * @param node A TaggedTemplateExpression node.
85930          */
85931         function visitTaggedTemplateExpression(node) {
85932             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
85933         }
85934         /**
85935          * Visits a TemplateExpression node.
85936          *
85937          * @param node A TemplateExpression node.
85938          */
85939         function visitTemplateExpression(node) {
85940             var expressions = [];
85941             addTemplateHead(expressions, node);
85942             addTemplateSpans(expressions, node);
85943             // createAdd will check if each expression binds less closely than binary '+'.
85944             // If it does, it wraps the expression in parentheses. Otherwise, something like
85945             //    `abc${ 1 << 2 }`
85946             // becomes
85947             //    "abc" + 1 << 2 + ""
85948             // which is really
85949             //    ("abc" + 1) << (2 + "")
85950             // rather than
85951             //    "abc" + (1 << 2) + ""
85952             var expression = ts.reduceLeft(expressions, ts.createAdd);
85953             if (ts.nodeIsSynthesized(expression)) {
85954                 expression.pos = node.pos;
85955                 expression.end = node.end;
85956             }
85957             return expression;
85958         }
85959         /**
85960          * Gets a value indicating whether we need to include the head of a TemplateExpression.
85961          *
85962          * @param node A TemplateExpression node.
85963          */
85964         function shouldAddTemplateHead(node) {
85965             // If this expression has an empty head literal and the first template span has a non-empty
85966             // literal, then emitting the empty head literal is not necessary.
85967             //     `${ foo } and ${ bar }`
85968             // can be emitted as
85969             //     foo + " and " + bar
85970             // This is because it is only required that one of the first two operands in the emit
85971             // output must be a string literal, so that the other operand and all following operands
85972             // are forced into strings.
85973             //
85974             // If the first template span has an empty literal, then the head must still be emitted.
85975             //     `${ foo }${ bar }`
85976             // must still be emitted as
85977             //     "" + foo + bar
85978             // There is always atleast one templateSpan in this code path, since
85979             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
85980             ts.Debug.assert(node.templateSpans.length !== 0);
85981             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
85982         }
85983         /**
85984          * Adds the head of a TemplateExpression to an array of expressions.
85985          *
85986          * @param expressions An array of expressions.
85987          * @param node A TemplateExpression node.
85988          */
85989         function addTemplateHead(expressions, node) {
85990             if (!shouldAddTemplateHead(node)) {
85991                 return;
85992             }
85993             expressions.push(ts.createLiteral(node.head.text));
85994         }
85995         /**
85996          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
85997          *
85998          * @param expressions An array of expressions.
85999          * @param node A TemplateExpression node.
86000          */
86001         function addTemplateSpans(expressions, node) {
86002             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
86003                 var span = _a[_i];
86004                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
86005                 // Only emit if the literal is non-empty.
86006                 // The binary '+' operator is left-associative, so the first string concatenation
86007                 // with the head will force the result up to this point to be a string.
86008                 // Emitting a '+ ""' has no semantic effect for middles and tails.
86009                 if (span.literal.text.length !== 0) {
86010                     expressions.push(ts.createLiteral(span.literal.text));
86011                 }
86012             }
86013         }
86014         /**
86015          * Visits the `super` keyword
86016          */
86017         function visitSuperKeyword(isExpressionOfCall) {
86018             return hierarchyFacts & 8 /* NonStaticClassElement */ && !isExpressionOfCall ? ts.createPropertyAccess(ts.createFileLevelUniqueName("_super"), "prototype") :
86019                 ts.createFileLevelUniqueName("_super");
86020         }
86021         function visitMetaProperty(node) {
86022             if (node.keywordToken === 99 /* NewKeyword */ && node.name.escapedText === "target") {
86023                 hierarchyFacts |= 16384 /* NewTarget */;
86024                 return ts.createFileLevelUniqueName("_newTarget");
86025             }
86026             return node;
86027         }
86028         /**
86029          * Called by the printer just before a node is printed.
86030          *
86031          * @param hint A hint as to the intended usage of the node.
86032          * @param node The node to be printed.
86033          * @param emitCallback The callback used to emit the node.
86034          */
86035         function onEmitNode(hint, node, emitCallback) {
86036             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
86037                 // If we are tracking a captured `this`, keep track of the enclosing function.
86038                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
86039                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
86040                     : 65 /* FunctionIncludes */);
86041                 previousOnEmitNode(hint, node, emitCallback);
86042                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
86043                 return;
86044             }
86045             previousOnEmitNode(hint, node, emitCallback);
86046         }
86047         /**
86048          * Enables a more costly code path for substitutions when we determine a source file
86049          * contains block-scoped bindings (e.g. `let` or `const`).
86050          */
86051         function enableSubstitutionsForBlockScopedBindings() {
86052             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
86053                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
86054                 context.enableSubstitution(75 /* Identifier */);
86055             }
86056         }
86057         /**
86058          * Enables a more costly code path for substitutions when we determine a source file
86059          * contains a captured `this`.
86060          */
86061         function enableSubstitutionsForCapturedThis() {
86062             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
86063                 enabledSubstitutions |= 1 /* CapturedThis */;
86064                 context.enableSubstitution(104 /* ThisKeyword */);
86065                 context.enableEmitNotification(162 /* Constructor */);
86066                 context.enableEmitNotification(161 /* MethodDeclaration */);
86067                 context.enableEmitNotification(163 /* GetAccessor */);
86068                 context.enableEmitNotification(164 /* SetAccessor */);
86069                 context.enableEmitNotification(202 /* ArrowFunction */);
86070                 context.enableEmitNotification(201 /* FunctionExpression */);
86071                 context.enableEmitNotification(244 /* FunctionDeclaration */);
86072             }
86073         }
86074         /**
86075          * Hooks node substitutions.
86076          *
86077          * @param hint The context for the emitter.
86078          * @param node The node to substitute.
86079          */
86080         function onSubstituteNode(hint, node) {
86081             node = previousOnSubstituteNode(hint, node);
86082             if (hint === 1 /* Expression */) {
86083                 return substituteExpression(node);
86084             }
86085             if (ts.isIdentifier(node)) {
86086                 return substituteIdentifier(node);
86087             }
86088             return node;
86089         }
86090         /**
86091          * Hooks substitutions for non-expression identifiers.
86092          */
86093         function substituteIdentifier(node) {
86094             // Only substitute the identifier if we have enabled substitutions for block-scoped
86095             // bindings.
86096             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86097                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
86098                 if (original && isNameOfDeclarationWithCollidingName(original)) {
86099                     return ts.setTextRange(ts.getGeneratedNameForNode(original), node);
86100                 }
86101             }
86102             return node;
86103         }
86104         /**
86105          * Determines whether a name is the name of a declaration with a colliding name.
86106          * NOTE: This function expects to be called with an original source tree node.
86107          *
86108          * @param node An original source tree node.
86109          */
86110         function isNameOfDeclarationWithCollidingName(node) {
86111             switch (node.parent.kind) {
86112                 case 191 /* BindingElement */:
86113                 case 245 /* ClassDeclaration */:
86114                 case 248 /* EnumDeclaration */:
86115                 case 242 /* VariableDeclaration */:
86116                     return node.parent.name === node
86117                         && resolver.isDeclarationWithCollidingName(node.parent);
86118             }
86119             return false;
86120         }
86121         /**
86122          * Substitutes an expression.
86123          *
86124          * @param node An Expression node.
86125          */
86126         function substituteExpression(node) {
86127             switch (node.kind) {
86128                 case 75 /* Identifier */:
86129                     return substituteExpressionIdentifier(node);
86130                 case 104 /* ThisKeyword */:
86131                     return substituteThisKeyword(node);
86132             }
86133             return node;
86134         }
86135         /**
86136          * Substitutes an expression identifier.
86137          *
86138          * @param node An Identifier node.
86139          */
86140         function substituteExpressionIdentifier(node) {
86141             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
86142                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
86143                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
86144                     return ts.setTextRange(ts.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
86145                 }
86146             }
86147             return node;
86148         }
86149         function isPartOfClassBody(declaration, node) {
86150             var currentNode = ts.getParseTreeNode(node);
86151             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
86152                 // if the node has no correlation to a parse tree node, its definitely not
86153                 // part of the body.
86154                 // if the node is outside of the document range of the declaration, its
86155                 // definitely not part of the body.
86156                 return false;
86157             }
86158             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
86159             while (currentNode) {
86160                 if (currentNode === blockScope || currentNode === declaration) {
86161                     // if we are in the enclosing block scope of the declaration, we are definitely
86162                     // not inside the class body.
86163                     return false;
86164                 }
86165                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
86166                     return true;
86167                 }
86168                 currentNode = currentNode.parent;
86169             }
86170             return false;
86171         }
86172         /**
86173          * Substitutes `this` when contained within an arrow function.
86174          *
86175          * @param node The ThisKeyword node.
86176          */
86177         function substituteThisKeyword(node) {
86178             if (enabledSubstitutions & 1 /* CapturedThis */
86179                 && hierarchyFacts & 16 /* CapturesThis */) {
86180                 return ts.setTextRange(ts.createFileLevelUniqueName("_this"), node);
86181             }
86182             return node;
86183         }
86184         function getClassMemberPrefix(node, member) {
86185             return ts.hasModifier(member, 32 /* Static */)
86186                 ? ts.getInternalName(node)
86187                 : ts.createPropertyAccess(ts.getInternalName(node), "prototype");
86188         }
86189         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
86190             if (!constructor || !hasExtendsClause) {
86191                 return false;
86192             }
86193             if (ts.some(constructor.parameters)) {
86194                 return false;
86195             }
86196             var statement = ts.firstOrUndefined(constructor.body.statements);
86197             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 226 /* ExpressionStatement */) {
86198                 return false;
86199             }
86200             var statementExpression = statement.expression;
86201             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 196 /* CallExpression */) {
86202                 return false;
86203             }
86204             var callTarget = statementExpression.expression;
86205             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 102 /* SuperKeyword */) {
86206                 return false;
86207             }
86208             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
86209             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 213 /* SpreadElement */) {
86210                 return false;
86211             }
86212             var expression = callArgument.expression;
86213             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
86214         }
86215     }
86216     ts.transformES2015 = transformES2015;
86217     function createExtendsHelper(context, name) {
86218         context.requestEmitHelper(ts.extendsHelper);
86219         return ts.createCall(ts.getUnscopedHelperName("__extends"), 
86220         /*typeArguments*/ undefined, [
86221             name,
86222             ts.createFileLevelUniqueName("_super")
86223         ]);
86224     }
86225     ts.extendsHelper = {
86226         name: "typescript:extends",
86227         importName: "__extends",
86228         scoped: false,
86229         priority: 0,
86230         text: "\n            var __extends = (this && this.__extends) || (function () {\n                var extendStatics = function (d, b) {\n                    extendStatics = Object.setPrototypeOf ||\n                        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n                        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n                    return extendStatics(d, b);\n                };\n\n                return function (d, b) {\n                    extendStatics(d, b);\n                    function __() { this.constructor = d; }\n                    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n                };\n            })();"
86231     };
86232 })(ts || (ts = {}));
86233 /*@internal*/
86234 var ts;
86235 (function (ts) {
86236     /**
86237      * Transforms ES5 syntax into ES3 syntax.
86238      *
86239      * @param context Context and state information for the transformation.
86240      */
86241     function transformES5(context) {
86242         var compilerOptions = context.getCompilerOptions();
86243         // enable emit notification only if using --jsx preserve or react-native
86244         var previousOnEmitNode;
86245         var noSubstitution;
86246         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
86247             previousOnEmitNode = context.onEmitNode;
86248             context.onEmitNode = onEmitNode;
86249             context.enableEmitNotification(268 /* JsxOpeningElement */);
86250             context.enableEmitNotification(269 /* JsxClosingElement */);
86251             context.enableEmitNotification(267 /* JsxSelfClosingElement */);
86252             noSubstitution = [];
86253         }
86254         var previousOnSubstituteNode = context.onSubstituteNode;
86255         context.onSubstituteNode = onSubstituteNode;
86256         context.enableSubstitution(194 /* PropertyAccessExpression */);
86257         context.enableSubstitution(281 /* PropertyAssignment */);
86258         return ts.chainBundle(transformSourceFile);
86259         /**
86260          * Transforms an ES5 source file to ES3.
86261          *
86262          * @param node A SourceFile
86263          */
86264         function transformSourceFile(node) {
86265             return node;
86266         }
86267         /**
86268          * Called by the printer just before a node is printed.
86269          *
86270          * @param hint A hint as to the intended usage of the node.
86271          * @param node The node to emit.
86272          * @param emitCallback A callback used to emit the node.
86273          */
86274         function onEmitNode(hint, node, emitCallback) {
86275             switch (node.kind) {
86276                 case 268 /* JsxOpeningElement */:
86277                 case 269 /* JsxClosingElement */:
86278                 case 267 /* JsxSelfClosingElement */:
86279                     var tagName = node.tagName;
86280                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
86281                     break;
86282             }
86283             previousOnEmitNode(hint, node, emitCallback);
86284         }
86285         /**
86286          * Hooks node substitutions.
86287          *
86288          * @param hint A hint as to the intended usage of the node.
86289          * @param node The node to substitute.
86290          */
86291         function onSubstituteNode(hint, node) {
86292             if (node.id && noSubstitution && noSubstitution[node.id]) {
86293                 return previousOnSubstituteNode(hint, node);
86294             }
86295             node = previousOnSubstituteNode(hint, node);
86296             if (ts.isPropertyAccessExpression(node)) {
86297                 return substitutePropertyAccessExpression(node);
86298             }
86299             else if (ts.isPropertyAssignment(node)) {
86300                 return substitutePropertyAssignment(node);
86301             }
86302             return node;
86303         }
86304         /**
86305          * Substitutes a PropertyAccessExpression whose name is a reserved word.
86306          *
86307          * @param node A PropertyAccessExpression
86308          */
86309         function substitutePropertyAccessExpression(node) {
86310             if (ts.isPrivateIdentifier(node.name)) {
86311                 return node;
86312             }
86313             var literalName = trySubstituteReservedName(node.name);
86314             if (literalName) {
86315                 return ts.setTextRange(ts.createElementAccess(node.expression, literalName), node);
86316             }
86317             return node;
86318         }
86319         /**
86320          * Substitutes a PropertyAssignment whose name is a reserved word.
86321          *
86322          * @param node A PropertyAssignment
86323          */
86324         function substitutePropertyAssignment(node) {
86325             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
86326             if (literalName) {
86327                 return ts.updatePropertyAssignment(node, literalName, node.initializer);
86328             }
86329             return node;
86330         }
86331         /**
86332          * If an identifier name is a reserved word, returns a string literal for the name.
86333          *
86334          * @param name An Identifier
86335          */
86336         function trySubstituteReservedName(name) {
86337             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
86338             if (token !== undefined && token >= 77 /* FirstReservedWord */ && token <= 112 /* LastReservedWord */) {
86339                 return ts.setTextRange(ts.createLiteral(name), name);
86340             }
86341             return undefined;
86342         }
86343     }
86344     ts.transformES5 = transformES5;
86345 })(ts || (ts = {}));
86346 // Transforms generator functions into a compatible ES5 representation with similar runtime
86347 // semantics. This is accomplished by first transforming the body of each generator
86348 // function into an intermediate representation that is the compiled into a JavaScript
86349 // switch statement.
86350 //
86351 // Many functions in this transformer will contain comments indicating the expected
86352 // intermediate representation. For illustrative purposes, the following intermediate
86353 // language is used to define this intermediate representation:
86354 //
86355 //  .nop                            - Performs no operation.
86356 //  .local NAME, ...                - Define local variable declarations.
86357 //  .mark LABEL                     - Mark the location of a label.
86358 //  .br LABEL                       - Jump to a label. If jumping out of a protected
86359 //                                    region, all .finally blocks are executed.
86360 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
86361 //                                    If jumping out of a protected region, all .finally
86362 //                                    blocks are executed.
86363 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
86364 //                                    If jumping out of a protected region, all .finally
86365 //                                    blocks are executed.
86366 //  .yield (x)                      - Yield the value of the optional expression `x`.
86367 //                                    Resume at the next label.
86368 //  .yieldstar (x)                  - Delegate yield to the value of the optional
86369 //                                    expression `x`. Resume at the next label.
86370 //                                    NOTE: `x` must be an Iterator, not an Iterable.
86371 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
86372 //                                    "break" abrupt completions jump to the CONTINUE or
86373 //                                    BREAK labels, respectively.
86374 //  .endloop                        - Marks the end of a loop.
86375 //  .with (x)                       - Marks the beginning of a WithStatement block, using
86376 //                                    the supplied expression.
86377 //  .endwith                        - Marks the end of a WithStatement.
86378 //  .switch                         - Marks the beginning of a SwitchStatement.
86379 //  .endswitch                      - Marks the end of a SwitchStatement.
86380 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
86381 //                                    supplied name.
86382 //  .endlabeled                     - Marks the end of a LabeledStatement.
86383 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
86384 //                                    labels for each block.
86385 //  .catch (x)                      - Marks the beginning of a catch block.
86386 //  .finally                        - Marks the beginning of a finally block.
86387 //  .endfinally                     - Marks the end of a finally block.
86388 //  .endtry                         - Marks the end of a protected region.
86389 //  .throw (x)                      - Throws the value of the expression `x`.
86390 //  .return (x)                     - Returns the value of the expression `x`.
86391 //
86392 // In addition, the illustrative intermediate representation introduces some special
86393 // variables:
86394 //
86395 //  %sent%                          - Either returns the next value sent to the generator,
86396 //                                    returns the result of a delegated yield, or throws
86397 //                                    the exception sent to the generator.
86398 //  %error%                         - Returns the value of the current exception in a
86399 //                                    catch block.
86400 //
86401 // This intermediate representation is then compiled into JavaScript syntax. The resulting
86402 // compilation output looks something like the following:
86403 //
86404 //  function f() {
86405 //      var /*locals*/;
86406 //      /*functions*/
86407 //      return __generator(function (state) {
86408 //          switch (state.label) {
86409 //              /*cases per label*/
86410 //          }
86411 //      });
86412 //  }
86413 //
86414 // Each of the above instructions corresponds to JavaScript emit similar to the following:
86415 //
86416 //  .local NAME                   | var NAME;
86417 // -------------------------------|----------------------------------------------
86418 //  .mark LABEL                   | case LABEL:
86419 // -------------------------------|----------------------------------------------
86420 //  .br LABEL                     |     return [3 /*break*/, LABEL];
86421 // -------------------------------|----------------------------------------------
86422 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
86423 // -------------------------------|----------------------------------------------
86424 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
86425 // -------------------------------|----------------------------------------------
86426 //  .yield (x)                    |     return [4 /*yield*/, x];
86427 //  .mark RESUME                  | case RESUME:
86428 //      a = %sent%;               |     a = state.sent();
86429 // -------------------------------|----------------------------------------------
86430 //  .yieldstar (x)                |     return [5 /*yield**/, x];
86431 //  .mark RESUME                  | case RESUME:
86432 //      a = %sent%;               |     a = state.sent();
86433 // -------------------------------|----------------------------------------------
86434 //  .with (_a)                    |     with (_a) {
86435 //      a();                      |         a();
86436 //                                |     }
86437 //                                |     state.label = LABEL;
86438 //  .mark LABEL                   | case LABEL:
86439 //                                |     with (_a) {
86440 //      b();                      |         b();
86441 //                                |     }
86442 //  .endwith                      |
86443 // -------------------------------|----------------------------------------------
86444 //                                | case 0:
86445 //                                |     state.trys = [];
86446 //                                | ...
86447 //  .try TRY, CATCH, FINALLY, END |
86448 //  .mark TRY                     | case TRY:
86449 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
86450 //  .nop                          |
86451 //      a();                      |     a();
86452 //  .br END                       |     return [3 /*break*/, END];
86453 //  .catch (e)                    |
86454 //  .mark CATCH                   | case CATCH:
86455 //                                |     e = state.sent();
86456 //      b();                      |     b();
86457 //  .br END                       |     return [3 /*break*/, END];
86458 //  .finally                      |
86459 //  .mark FINALLY                 | case FINALLY:
86460 //      c();                      |     c();
86461 //  .endfinally                   |     return [7 /*endfinally*/];
86462 //  .endtry                       |
86463 //  .mark END                     | case END:
86464 /*@internal*/
86465 var ts;
86466 (function (ts) {
86467     var OpCode;
86468     (function (OpCode) {
86469         OpCode[OpCode["Nop"] = 0] = "Nop";
86470         OpCode[OpCode["Statement"] = 1] = "Statement";
86471         OpCode[OpCode["Assign"] = 2] = "Assign";
86472         OpCode[OpCode["Break"] = 3] = "Break";
86473         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
86474         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
86475         OpCode[OpCode["Yield"] = 6] = "Yield";
86476         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
86477         OpCode[OpCode["Return"] = 8] = "Return";
86478         OpCode[OpCode["Throw"] = 9] = "Throw";
86479         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
86480     })(OpCode || (OpCode = {}));
86481     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
86482     var BlockAction;
86483     (function (BlockAction) {
86484         BlockAction[BlockAction["Open"] = 0] = "Open";
86485         BlockAction[BlockAction["Close"] = 1] = "Close";
86486     })(BlockAction || (BlockAction = {}));
86487     // the kind for a generated code block in a FunctionBuilder
86488     var CodeBlockKind;
86489     (function (CodeBlockKind) {
86490         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
86491         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
86492         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
86493         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
86494         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
86495     })(CodeBlockKind || (CodeBlockKind = {}));
86496     // the state for a generated code exception block
86497     var ExceptionBlockState;
86498     (function (ExceptionBlockState) {
86499         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
86500         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
86501         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
86502         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
86503     })(ExceptionBlockState || (ExceptionBlockState = {}));
86504     // NOTE: changes to this enum should be reflected in the __generator helper.
86505     var Instruction;
86506     (function (Instruction) {
86507         Instruction[Instruction["Next"] = 0] = "Next";
86508         Instruction[Instruction["Throw"] = 1] = "Throw";
86509         Instruction[Instruction["Return"] = 2] = "Return";
86510         Instruction[Instruction["Break"] = 3] = "Break";
86511         Instruction[Instruction["Yield"] = 4] = "Yield";
86512         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
86513         Instruction[Instruction["Catch"] = 6] = "Catch";
86514         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
86515     })(Instruction || (Instruction = {}));
86516     function getInstructionName(instruction) {
86517         switch (instruction) {
86518             case 2 /* Return */: return "return";
86519             case 3 /* Break */: return "break";
86520             case 4 /* Yield */: return "yield";
86521             case 5 /* YieldStar */: return "yield*";
86522             case 7 /* Endfinally */: return "endfinally";
86523             default: return undefined; // TODO: GH#18217
86524         }
86525     }
86526     function transformGenerators(context) {
86527         var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
86528         var compilerOptions = context.getCompilerOptions();
86529         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86530         var resolver = context.getEmitResolver();
86531         var previousOnSubstituteNode = context.onSubstituteNode;
86532         context.onSubstituteNode = onSubstituteNode;
86533         var renamedCatchVariables;
86534         var renamedCatchVariableDeclarations;
86535         var inGeneratorFunctionBody;
86536         var inStatementContainingYield;
86537         // The following three arrays store information about generated code blocks.
86538         // All three arrays are correlated by their index. This approach is used over allocating
86539         // objects to store the same information to avoid GC overhead.
86540         //
86541         var blocks; // Information about the code block
86542         var blockOffsets; // The operation offset at which a code block begins or ends
86543         var blockActions; // Whether the code block is opened or closed
86544         var blockStack; // A stack of currently open code blocks
86545         // Labels are used to mark locations in the code that can be the target of a Break (jump)
86546         // operation. These are translated into case clauses in a switch statement.
86547         // The following two arrays are correlated by their index. This approach is used over
86548         // allocating objects to store the same information to avoid GC overhead.
86549         //
86550         var labelOffsets; // The operation offset at which the label is defined.
86551         var labelExpressions; // The NumericLiteral nodes bound to each label.
86552         var nextLabelId = 1; // The next label id to use.
86553         // Operations store information about generated code for the function body. This
86554         // Includes things like statements, assignments, breaks (jumps), and yields.
86555         // The following three arrays are correlated by their index. This approach is used over
86556         // allocating objects to store the same information to avoid GC overhead.
86557         //
86558         var operations; // The operation to perform.
86559         var operationArguments; // The arguments to the operation.
86560         var operationLocations; // The source map location for the operation.
86561         var state; // The name of the state object used by the generator at runtime.
86562         // The following variables store information used by the `build` function:
86563         //
86564         var blockIndex = 0; // The index of the current block.
86565         var labelNumber = 0; // The current label number.
86566         var labelNumbers;
86567         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
86568         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
86569         var clauses; // The case clauses generated for labels.
86570         var statements; // The statements for the current label.
86571         var exceptionBlockStack; // A stack of containing exception blocks.
86572         var currentExceptionBlock; // The current exception block.
86573         var withBlockStack; // A stack containing `with` blocks.
86574         return ts.chainBundle(transformSourceFile);
86575         function transformSourceFile(node) {
86576             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
86577                 return node;
86578             }
86579             var visited = ts.visitEachChild(node, visitor, context);
86580             ts.addEmitHelpers(visited, context.readEmitHelpers());
86581             return visited;
86582         }
86583         /**
86584          * Visits a node.
86585          *
86586          * @param node The node to visit.
86587          */
86588         function visitor(node) {
86589             var transformFlags = node.transformFlags;
86590             if (inStatementContainingYield) {
86591                 return visitJavaScriptInStatementContainingYield(node);
86592             }
86593             else if (inGeneratorFunctionBody) {
86594                 return visitJavaScriptInGeneratorFunctionBody(node);
86595             }
86596             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
86597                 return visitGenerator(node);
86598             }
86599             else if (transformFlags & 512 /* ContainsGenerator */) {
86600                 return ts.visitEachChild(node, visitor, context);
86601             }
86602             else {
86603                 return node;
86604             }
86605         }
86606         /**
86607          * Visits a node that is contained within a statement that contains yield.
86608          *
86609          * @param node The node to visit.
86610          */
86611         function visitJavaScriptInStatementContainingYield(node) {
86612             switch (node.kind) {
86613                 case 228 /* DoStatement */:
86614                     return visitDoStatement(node);
86615                 case 229 /* WhileStatement */:
86616                     return visitWhileStatement(node);
86617                 case 237 /* SwitchStatement */:
86618                     return visitSwitchStatement(node);
86619                 case 238 /* LabeledStatement */:
86620                     return visitLabeledStatement(node);
86621                 default:
86622                     return visitJavaScriptInGeneratorFunctionBody(node);
86623             }
86624         }
86625         /**
86626          * Visits a node that is contained within a generator function.
86627          *
86628          * @param node The node to visit.
86629          */
86630         function visitJavaScriptInGeneratorFunctionBody(node) {
86631             switch (node.kind) {
86632                 case 244 /* FunctionDeclaration */:
86633                     return visitFunctionDeclaration(node);
86634                 case 201 /* FunctionExpression */:
86635                     return visitFunctionExpression(node);
86636                 case 163 /* GetAccessor */:
86637                 case 164 /* SetAccessor */:
86638                     return visitAccessorDeclaration(node);
86639                 case 225 /* VariableStatement */:
86640                     return visitVariableStatement(node);
86641                 case 230 /* ForStatement */:
86642                     return visitForStatement(node);
86643                 case 231 /* ForInStatement */:
86644                     return visitForInStatement(node);
86645                 case 234 /* BreakStatement */:
86646                     return visitBreakStatement(node);
86647                 case 233 /* ContinueStatement */:
86648                     return visitContinueStatement(node);
86649                 case 235 /* ReturnStatement */:
86650                     return visitReturnStatement(node);
86651                 default:
86652                     if (node.transformFlags & 262144 /* ContainsYield */) {
86653                         return visitJavaScriptContainingYield(node);
86654                     }
86655                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
86656                         return ts.visitEachChild(node, visitor, context);
86657                     }
86658                     else {
86659                         return node;
86660                     }
86661             }
86662         }
86663         /**
86664          * Visits a node that contains a YieldExpression.
86665          *
86666          * @param node The node to visit.
86667          */
86668         function visitJavaScriptContainingYield(node) {
86669             switch (node.kind) {
86670                 case 209 /* BinaryExpression */:
86671                     return visitBinaryExpression(node);
86672                 case 210 /* ConditionalExpression */:
86673                     return visitConditionalExpression(node);
86674                 case 212 /* YieldExpression */:
86675                     return visitYieldExpression(node);
86676                 case 192 /* ArrayLiteralExpression */:
86677                     return visitArrayLiteralExpression(node);
86678                 case 193 /* ObjectLiteralExpression */:
86679                     return visitObjectLiteralExpression(node);
86680                 case 195 /* ElementAccessExpression */:
86681                     return visitElementAccessExpression(node);
86682                 case 196 /* CallExpression */:
86683                     return visitCallExpression(node);
86684                 case 197 /* NewExpression */:
86685                     return visitNewExpression(node);
86686                 default:
86687                     return ts.visitEachChild(node, visitor, context);
86688             }
86689         }
86690         /**
86691          * Visits a generator function.
86692          *
86693          * @param node The node to visit.
86694          */
86695         function visitGenerator(node) {
86696             switch (node.kind) {
86697                 case 244 /* FunctionDeclaration */:
86698                     return visitFunctionDeclaration(node);
86699                 case 201 /* FunctionExpression */:
86700                     return visitFunctionExpression(node);
86701                 default:
86702                     return ts.Debug.failBadSyntaxKind(node);
86703             }
86704         }
86705         /**
86706          * Visits a function declaration.
86707          *
86708          * This will be called when one of the following conditions are met:
86709          * - The function declaration is a generator function.
86710          * - The function declaration is contained within the body of a generator function.
86711          *
86712          * @param node The node to visit.
86713          */
86714         function visitFunctionDeclaration(node) {
86715             // Currently, we only support generators that were originally async functions.
86716             if (node.asteriskToken) {
86717                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
86718                 /*decorators*/ undefined, node.modifiers, 
86719                 /*asteriskToken*/ undefined, node.name, 
86720                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86721                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86722                 /*location*/ node), node);
86723             }
86724             else {
86725                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86726                 var savedInStatementContainingYield = inStatementContainingYield;
86727                 inGeneratorFunctionBody = false;
86728                 inStatementContainingYield = false;
86729                 node = ts.visitEachChild(node, visitor, context);
86730                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86731                 inStatementContainingYield = savedInStatementContainingYield;
86732             }
86733             if (inGeneratorFunctionBody) {
86734                 // Function declarations in a generator function body are hoisted
86735                 // to the top of the lexical scope and elided from the current statement.
86736                 hoistFunctionDeclaration(node);
86737                 return undefined;
86738             }
86739             else {
86740                 return node;
86741             }
86742         }
86743         /**
86744          * Visits a function expression.
86745          *
86746          * This will be called when one of the following conditions are met:
86747          * - The function expression is a generator function.
86748          * - The function expression is contained within the body of a generator function.
86749          *
86750          * @param node The node to visit.
86751          */
86752         function visitFunctionExpression(node) {
86753             // Currently, we only support generators that were originally async functions.
86754             if (node.asteriskToken) {
86755                 node = ts.setOriginalNode(ts.setTextRange(ts.createFunctionExpression(
86756                 /*modifiers*/ undefined, 
86757                 /*asteriskToken*/ undefined, node.name, 
86758                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86759                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
86760                 /*location*/ node), node);
86761             }
86762             else {
86763                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86764                 var savedInStatementContainingYield = inStatementContainingYield;
86765                 inGeneratorFunctionBody = false;
86766                 inStatementContainingYield = false;
86767                 node = ts.visitEachChild(node, visitor, context);
86768                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86769                 inStatementContainingYield = savedInStatementContainingYield;
86770             }
86771             return node;
86772         }
86773         /**
86774          * Visits a get or set accessor declaration.
86775          *
86776          * This will be called when one of the following conditions are met:
86777          * - The accessor is contained within the body of a generator function.
86778          *
86779          * @param node The node to visit.
86780          */
86781         function visitAccessorDeclaration(node) {
86782             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86783             var savedInStatementContainingYield = inStatementContainingYield;
86784             inGeneratorFunctionBody = false;
86785             inStatementContainingYield = false;
86786             node = ts.visitEachChild(node, visitor, context);
86787             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86788             inStatementContainingYield = savedInStatementContainingYield;
86789             return node;
86790         }
86791         /**
86792          * Transforms the body of a generator function declaration.
86793          *
86794          * @param node The function body to transform.
86795          */
86796         function transformGeneratorFunctionBody(body) {
86797             // Save existing generator state
86798             var statements = [];
86799             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
86800             var savedInStatementContainingYield = inStatementContainingYield;
86801             var savedBlocks = blocks;
86802             var savedBlockOffsets = blockOffsets;
86803             var savedBlockActions = blockActions;
86804             var savedBlockStack = blockStack;
86805             var savedLabelOffsets = labelOffsets;
86806             var savedLabelExpressions = labelExpressions;
86807             var savedNextLabelId = nextLabelId;
86808             var savedOperations = operations;
86809             var savedOperationArguments = operationArguments;
86810             var savedOperationLocations = operationLocations;
86811             var savedState = state;
86812             // Initialize generator state
86813             inGeneratorFunctionBody = true;
86814             inStatementContainingYield = false;
86815             blocks = undefined;
86816             blockOffsets = undefined;
86817             blockActions = undefined;
86818             blockStack = undefined;
86819             labelOffsets = undefined;
86820             labelExpressions = undefined;
86821             nextLabelId = 1;
86822             operations = undefined;
86823             operationArguments = undefined;
86824             operationLocations = undefined;
86825             state = ts.createTempVariable(/*recordTempVariable*/ undefined);
86826             // Build the generator
86827             resumeLexicalEnvironment();
86828             var statementOffset = ts.addPrologue(statements, body.statements, /*ensureUseStrict*/ false, visitor);
86829             transformAndEmitStatements(body.statements, statementOffset);
86830             var buildResult = build();
86831             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86832             statements.push(ts.createReturn(buildResult));
86833             // Restore previous generator state
86834             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
86835             inStatementContainingYield = savedInStatementContainingYield;
86836             blocks = savedBlocks;
86837             blockOffsets = savedBlockOffsets;
86838             blockActions = savedBlockActions;
86839             blockStack = savedBlockStack;
86840             labelOffsets = savedLabelOffsets;
86841             labelExpressions = savedLabelExpressions;
86842             nextLabelId = savedNextLabelId;
86843             operations = savedOperations;
86844             operationArguments = savedOperationArguments;
86845             operationLocations = savedOperationLocations;
86846             state = savedState;
86847             return ts.setTextRange(ts.createBlock(statements, body.multiLine), body);
86848         }
86849         /**
86850          * Visits a variable statement.
86851          *
86852          * This will be called when one of the following conditions are met:
86853          * - The variable statement is contained within the body of a generator function.
86854          *
86855          * @param node The node to visit.
86856          */
86857         function visitVariableStatement(node) {
86858             if (node.transformFlags & 262144 /* ContainsYield */) {
86859                 transformAndEmitVariableDeclarationList(node.declarationList);
86860                 return undefined;
86861             }
86862             else {
86863                 // Do not hoist custom prologues.
86864                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
86865                     return node;
86866                 }
86867                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
86868                     var variable = _a[_i];
86869                     hoistVariableDeclaration(variable.name);
86870                 }
86871                 var variables = ts.getInitializedVariables(node.declarationList);
86872                 if (variables.length === 0) {
86873                     return undefined;
86874                 }
86875                 return ts.setSourceMapRange(ts.createExpressionStatement(ts.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
86876             }
86877         }
86878         /**
86879          * Visits a binary expression.
86880          *
86881          * This will be called when one of the following conditions are met:
86882          * - The node contains a YieldExpression.
86883          *
86884          * @param node The node to visit.
86885          */
86886         function visitBinaryExpression(node) {
86887             var assoc = ts.getExpressionAssociativity(node);
86888             switch (assoc) {
86889                 case 0 /* Left */:
86890                     return visitLeftAssociativeBinaryExpression(node);
86891                 case 1 /* Right */:
86892                     return visitRightAssociativeBinaryExpression(node);
86893                 default:
86894                     return ts.Debug.assertNever(assoc);
86895             }
86896         }
86897         /**
86898          * Visits a right-associative binary expression containing `yield`.
86899          *
86900          * @param node The node to visit.
86901          */
86902         function visitRightAssociativeBinaryExpression(node) {
86903             var left = node.left, right = node.right;
86904             if (containsYield(right)) {
86905                 var target = void 0;
86906                 switch (left.kind) {
86907                     case 194 /* PropertyAccessExpression */:
86908                         // [source]
86909                         //      a.b = yield;
86910                         //
86911                         // [intermediate]
86912                         //  .local _a
86913                         //      _a = a;
86914                         //  .yield resumeLabel
86915                         //  .mark resumeLabel
86916                         //      _a.b = %sent%;
86917                         target = ts.updatePropertyAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
86918                         break;
86919                     case 195 /* ElementAccessExpression */:
86920                         // [source]
86921                         //      a[b] = yield;
86922                         //
86923                         // [intermediate]
86924                         //  .local _a, _b
86925                         //      _a = a;
86926                         //      _b = b;
86927                         //  .yield resumeLabel
86928                         //  .mark resumeLabel
86929                         //      _a[_b] = %sent%;
86930                         target = ts.updateElementAccess(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
86931                         break;
86932                     default:
86933                         target = ts.visitNode(left, visitor, ts.isExpression);
86934                         break;
86935                 }
86936                 var operator = node.operatorToken.kind;
86937                 if (ts.isCompoundAssignment(operator)) {
86938                     return ts.setTextRange(ts.createAssignment(target, ts.setTextRange(ts.createBinary(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
86939                 }
86940                 else {
86941                     return ts.updateBinary(node, target, ts.visitNode(right, visitor, ts.isExpression));
86942                 }
86943             }
86944             return ts.visitEachChild(node, visitor, context);
86945         }
86946         function visitLeftAssociativeBinaryExpression(node) {
86947             if (containsYield(node.right)) {
86948                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
86949                     return visitLogicalBinaryExpression(node);
86950                 }
86951                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
86952                     return visitCommaExpression(node);
86953                 }
86954                 // [source]
86955                 //      a() + (yield) + c()
86956                 //
86957                 // [intermediate]
86958                 //  .local _a
86959                 //      _a = a();
86960                 //  .yield resumeLabel
86961                 //      _a + %sent% + c()
86962                 var clone_6 = ts.getMutableClone(node);
86963                 clone_6.left = cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression));
86964                 clone_6.right = ts.visitNode(node.right, visitor, ts.isExpression);
86965                 return clone_6;
86966             }
86967             return ts.visitEachChild(node, visitor, context);
86968         }
86969         /**
86970          * Visits a logical binary expression containing `yield`.
86971          *
86972          * @param node A node to visit.
86973          */
86974         function visitLogicalBinaryExpression(node) {
86975             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
86976             // to be transformed as such:
86977             //
86978             // [source]
86979             //      x = a() && yield;
86980             //
86981             // [intermediate]
86982             //  .local _a
86983             //      _a = a();
86984             //  .brfalse resultLabel, (_a)
86985             //  .yield resumeLabel
86986             //  .mark resumeLabel
86987             //      _a = %sent%;
86988             //  .mark resultLabel
86989             //      x = _a;
86990             //
86991             // [source]
86992             //      x = a() || yield;
86993             //
86994             // [intermediate]
86995             //  .local _a
86996             //      _a = a();
86997             //  .brtrue resultLabel, (_a)
86998             //  .yield resumeLabel
86999             //  .mark resumeLabel
87000             //      _a = %sent%;
87001             //  .mark resultLabel
87002             //      x = _a;
87003             var resultLabel = defineLabel();
87004             var resultLocal = declareLocal();
87005             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
87006             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
87007                 // Logical `&&` shortcuts when the left-hand operand is falsey.
87008                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
87009             }
87010             else {
87011                 // Logical `||` shortcuts when the left-hand operand is truthy.
87012                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
87013             }
87014             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
87015             markLabel(resultLabel);
87016             return resultLocal;
87017         }
87018         /**
87019          * Visits a comma expression containing `yield`.
87020          *
87021          * @param node The node to visit.
87022          */
87023         function visitCommaExpression(node) {
87024             // [source]
87025             //      x = a(), yield, b();
87026             //
87027             // [intermediate]
87028             //      a();
87029             //  .yield resumeLabel
87030             //  .mark resumeLabel
87031             //      x = %sent%, b();
87032             var pendingExpressions = [];
87033             visit(node.left);
87034             visit(node.right);
87035             return ts.inlineExpressions(pendingExpressions);
87036             function visit(node) {
87037                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
87038                     visit(node.left);
87039                     visit(node.right);
87040                 }
87041                 else {
87042                     if (containsYield(node) && pendingExpressions.length > 0) {
87043                         emitWorker(1 /* Statement */, [ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions))]);
87044                         pendingExpressions = [];
87045                     }
87046                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
87047                 }
87048             }
87049         }
87050         /**
87051          * Visits a conditional expression containing `yield`.
87052          *
87053          * @param node The node to visit.
87054          */
87055         function visitConditionalExpression(node) {
87056             // [source]
87057             //      x = a() ? yield : b();
87058             //
87059             // [intermediate]
87060             //  .local _a
87061             //  .brfalse whenFalseLabel, (a())
87062             //  .yield resumeLabel
87063             //  .mark resumeLabel
87064             //      _a = %sent%;
87065             //  .br resultLabel
87066             //  .mark whenFalseLabel
87067             //      _a = b();
87068             //  .mark resultLabel
87069             //      x = _a;
87070             // We only need to perform a specific transformation if a `yield` expression exists
87071             // in either the `whenTrue` or `whenFalse` branches.
87072             // A `yield` in the condition will be handled by the normal visitor.
87073             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
87074                 var whenFalseLabel = defineLabel();
87075                 var resultLabel = defineLabel();
87076                 var resultLocal = declareLocal();
87077                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
87078                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
87079                 emitBreak(resultLabel);
87080                 markLabel(whenFalseLabel);
87081                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
87082                 markLabel(resultLabel);
87083                 return resultLocal;
87084             }
87085             return ts.visitEachChild(node, visitor, context);
87086         }
87087         /**
87088          * Visits a `yield` expression.
87089          *
87090          * @param node The node to visit.
87091          */
87092         function visitYieldExpression(node) {
87093             // [source]
87094             //      x = yield a();
87095             //
87096             // [intermediate]
87097             //  .yield resumeLabel, (a())
87098             //  .mark resumeLabel
87099             //      x = %sent%;
87100             var resumeLabel = defineLabel();
87101             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87102             if (node.asteriskToken) {
87103                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
87104                     ? ts.createValuesHelper(context, expression, /*location*/ node)
87105                     : expression;
87106                 emitYieldStar(iterator, /*location*/ node);
87107             }
87108             else {
87109                 emitYield(expression, /*location*/ node);
87110             }
87111             markLabel(resumeLabel);
87112             return createGeneratorResume(/*location*/ node);
87113         }
87114         /**
87115          * Visits an ArrayLiteralExpression that contains a YieldExpression.
87116          *
87117          * @param node The node to visit.
87118          */
87119         function visitArrayLiteralExpression(node) {
87120             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
87121         }
87122         /**
87123          * Visits an array of expressions containing one or more YieldExpression nodes
87124          * and returns an expression for the resulting value.
87125          *
87126          * @param elements The elements to visit.
87127          * @param multiLine Whether array literals created should be emitted on multiple lines.
87128          */
87129         function visitElements(elements, leadingElement, location, multiLine) {
87130             // [source]
87131             //      ar = [1, yield, 2];
87132             //
87133             // [intermediate]
87134             //  .local _a
87135             //      _a = [1];
87136             //  .yield resumeLabel
87137             //  .mark resumeLabel
87138             //      ar = _a.concat([%sent%, 2]);
87139             var numInitialElements = countInitialNodesWithoutYield(elements);
87140             var temp;
87141             if (numInitialElements > 0) {
87142                 temp = declareLocal();
87143                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
87144                 emitAssignment(temp, ts.createArrayLiteral(leadingElement
87145                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
87146                 leadingElement = undefined;
87147             }
87148             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
87149             return temp
87150                 ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87151                 : ts.setTextRange(ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
87152             function reduceElement(expressions, element) {
87153                 if (containsYield(element) && expressions.length > 0) {
87154                     var hasAssignedTemp = temp !== undefined;
87155                     if (!temp) {
87156                         temp = declareLocal();
87157                     }
87158                     emitAssignment(temp, hasAssignedTemp
87159                         ? ts.createArrayConcat(temp, [ts.createArrayLiteral(expressions, multiLine)])
87160                         : ts.createArrayLiteral(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
87161                     leadingElement = undefined;
87162                     expressions = [];
87163                 }
87164                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
87165                 return expressions;
87166             }
87167         }
87168         function visitObjectLiteralExpression(node) {
87169             // [source]
87170             //      o = {
87171             //          a: 1,
87172             //          b: yield,
87173             //          c: 2
87174             //      };
87175             //
87176             // [intermediate]
87177             //  .local _a
87178             //      _a = {
87179             //          a: 1
87180             //      };
87181             //  .yield resumeLabel
87182             //  .mark resumeLabel
87183             //      o = (_a.b = %sent%,
87184             //          _a.c = 2,
87185             //          _a);
87186             var properties = node.properties;
87187             var multiLine = node.multiLine;
87188             var numInitialProperties = countInitialNodesWithoutYield(properties);
87189             var temp = declareLocal();
87190             emitAssignment(temp, ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
87191             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
87192             expressions.push(multiLine ? ts.startOnNewLine(ts.getMutableClone(temp)) : temp);
87193             return ts.inlineExpressions(expressions);
87194             function reduceProperty(expressions, property) {
87195                 if (containsYield(property) && expressions.length > 0) {
87196                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(expressions)));
87197                     expressions = [];
87198                 }
87199                 var expression = ts.createExpressionForObjectLiteralElementLike(node, property, temp);
87200                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
87201                 if (visited) {
87202                     if (multiLine) {
87203                         ts.startOnNewLine(visited);
87204                     }
87205                     expressions.push(visited);
87206                 }
87207                 return expressions;
87208             }
87209         }
87210         /**
87211          * Visits an ElementAccessExpression that contains a YieldExpression.
87212          *
87213          * @param node The node to visit.
87214          */
87215         function visitElementAccessExpression(node) {
87216             if (containsYield(node.argumentExpression)) {
87217                 // [source]
87218                 //      a = x[yield];
87219                 //
87220                 // [intermediate]
87221                 //  .local _a
87222                 //      _a = x;
87223                 //  .yield resumeLabel
87224                 //  .mark resumeLabel
87225                 //      a = _a[%sent%]
87226                 var clone_7 = ts.getMutableClone(node);
87227                 clone_7.expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression));
87228                 clone_7.argumentExpression = ts.visitNode(node.argumentExpression, visitor, ts.isExpression);
87229                 return clone_7;
87230             }
87231             return ts.visitEachChild(node, visitor, context);
87232         }
87233         function visitCallExpression(node) {
87234             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
87235                 // [source]
87236                 //      a.b(1, yield, 2);
87237                 //
87238                 // [intermediate]
87239                 //  .local _a, _b, _c
87240                 //      _b = (_a = a).b;
87241                 //      _c = [1];
87242                 //  .yield resumeLabel
87243                 //  .mark resumeLabel
87244                 //      _b.apply(_a, _c.concat([%sent%, 2]));
87245                 var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
87246                 return ts.setOriginalNode(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments), 
87247                 /*location*/ node), node);
87248             }
87249             return ts.visitEachChild(node, visitor, context);
87250         }
87251         function visitNewExpression(node) {
87252             if (ts.forEach(node.arguments, containsYield)) {
87253                 // [source]
87254                 //      new a.b(1, yield, 2);
87255                 //
87256                 // [intermediate]
87257                 //  .local _a, _b, _c
87258                 //      _b = (_a = a.b).bind;
87259                 //      _c = [1];
87260                 //  .yield resumeLabel
87261                 //  .mark resumeLabel
87262                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
87263                 var _a = ts.createCallBinding(ts.createPropertyAccess(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
87264                 return ts.setOriginalNode(ts.setTextRange(ts.createNew(ts.createFunctionApply(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
87265                 /*leadingElement*/ ts.createVoidZero())), 
87266                 /*typeArguments*/ undefined, []), node), node);
87267             }
87268             return ts.visitEachChild(node, visitor, context);
87269         }
87270         function transformAndEmitStatements(statements, start) {
87271             if (start === void 0) { start = 0; }
87272             var numStatements = statements.length;
87273             for (var i = start; i < numStatements; i++) {
87274                 transformAndEmitStatement(statements[i]);
87275             }
87276         }
87277         function transformAndEmitEmbeddedStatement(node) {
87278             if (ts.isBlock(node)) {
87279                 transformAndEmitStatements(node.statements);
87280             }
87281             else {
87282                 transformAndEmitStatement(node);
87283             }
87284         }
87285         function transformAndEmitStatement(node) {
87286             var savedInStatementContainingYield = inStatementContainingYield;
87287             if (!inStatementContainingYield) {
87288                 inStatementContainingYield = containsYield(node);
87289             }
87290             transformAndEmitStatementWorker(node);
87291             inStatementContainingYield = savedInStatementContainingYield;
87292         }
87293         function transformAndEmitStatementWorker(node) {
87294             switch (node.kind) {
87295                 case 223 /* Block */:
87296                     return transformAndEmitBlock(node);
87297                 case 226 /* ExpressionStatement */:
87298                     return transformAndEmitExpressionStatement(node);
87299                 case 227 /* IfStatement */:
87300                     return transformAndEmitIfStatement(node);
87301                 case 228 /* DoStatement */:
87302                     return transformAndEmitDoStatement(node);
87303                 case 229 /* WhileStatement */:
87304                     return transformAndEmitWhileStatement(node);
87305                 case 230 /* ForStatement */:
87306                     return transformAndEmitForStatement(node);
87307                 case 231 /* ForInStatement */:
87308                     return transformAndEmitForInStatement(node);
87309                 case 233 /* ContinueStatement */:
87310                     return transformAndEmitContinueStatement(node);
87311                 case 234 /* BreakStatement */:
87312                     return transformAndEmitBreakStatement(node);
87313                 case 235 /* ReturnStatement */:
87314                     return transformAndEmitReturnStatement(node);
87315                 case 236 /* WithStatement */:
87316                     return transformAndEmitWithStatement(node);
87317                 case 237 /* SwitchStatement */:
87318                     return transformAndEmitSwitchStatement(node);
87319                 case 238 /* LabeledStatement */:
87320                     return transformAndEmitLabeledStatement(node);
87321                 case 239 /* ThrowStatement */:
87322                     return transformAndEmitThrowStatement(node);
87323                 case 240 /* TryStatement */:
87324                     return transformAndEmitTryStatement(node);
87325                 default:
87326                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87327             }
87328         }
87329         function transformAndEmitBlock(node) {
87330             if (containsYield(node)) {
87331                 transformAndEmitStatements(node.statements);
87332             }
87333             else {
87334                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87335             }
87336         }
87337         function transformAndEmitExpressionStatement(node) {
87338             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87339         }
87340         function transformAndEmitVariableDeclarationList(node) {
87341             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
87342                 var variable = _a[_i];
87343                 var name = ts.getSynthesizedClone(variable.name);
87344                 ts.setCommentRange(name, variable.name);
87345                 hoistVariableDeclaration(name);
87346             }
87347             var variables = ts.getInitializedVariables(node);
87348             var numVariables = variables.length;
87349             var variablesWritten = 0;
87350             var pendingExpressions = [];
87351             while (variablesWritten < numVariables) {
87352                 for (var i = variablesWritten; i < numVariables; i++) {
87353                     var variable = variables[i];
87354                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
87355                         break;
87356                     }
87357                     pendingExpressions.push(transformInitializedVariable(variable));
87358                 }
87359                 if (pendingExpressions.length) {
87360                     emitStatement(ts.createExpressionStatement(ts.inlineExpressions(pendingExpressions)));
87361                     variablesWritten += pendingExpressions.length;
87362                     pendingExpressions = [];
87363                 }
87364             }
87365             return undefined;
87366         }
87367         function transformInitializedVariable(node) {
87368             return ts.setSourceMapRange(ts.createAssignment(ts.setSourceMapRange(ts.getSynthesizedClone(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
87369         }
87370         function transformAndEmitIfStatement(node) {
87371             if (containsYield(node)) {
87372                 // [source]
87373                 //      if (x)
87374                 //          /*thenStatement*/
87375                 //      else
87376                 //          /*elseStatement*/
87377                 //
87378                 // [intermediate]
87379                 //  .brfalse elseLabel, (x)
87380                 //      /*thenStatement*/
87381                 //  .br endLabel
87382                 //  .mark elseLabel
87383                 //      /*elseStatement*/
87384                 //  .mark endLabel
87385                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
87386                     var endLabel = defineLabel();
87387                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
87388                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
87389                     transformAndEmitEmbeddedStatement(node.thenStatement);
87390                     if (node.elseStatement) {
87391                         emitBreak(endLabel);
87392                         markLabel(elseLabel);
87393                         transformAndEmitEmbeddedStatement(node.elseStatement);
87394                     }
87395                     markLabel(endLabel);
87396                 }
87397                 else {
87398                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87399                 }
87400             }
87401             else {
87402                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87403             }
87404         }
87405         function transformAndEmitDoStatement(node) {
87406             if (containsYield(node)) {
87407                 // [source]
87408                 //      do {
87409                 //          /*body*/
87410                 //      }
87411                 //      while (i < 10);
87412                 //
87413                 // [intermediate]
87414                 //  .loop conditionLabel, endLabel
87415                 //  .mark loopLabel
87416                 //      /*body*/
87417                 //  .mark conditionLabel
87418                 //  .brtrue loopLabel, (i < 10)
87419                 //  .endloop
87420                 //  .mark endLabel
87421                 var conditionLabel = defineLabel();
87422                 var loopLabel = defineLabel();
87423                 beginLoopBlock(/*continueLabel*/ conditionLabel);
87424                 markLabel(loopLabel);
87425                 transformAndEmitEmbeddedStatement(node.statement);
87426                 markLabel(conditionLabel);
87427                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87428                 endLoopBlock();
87429             }
87430             else {
87431                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87432             }
87433         }
87434         function visitDoStatement(node) {
87435             if (inStatementContainingYield) {
87436                 beginScriptLoopBlock();
87437                 node = ts.visitEachChild(node, visitor, context);
87438                 endLoopBlock();
87439                 return node;
87440             }
87441             else {
87442                 return ts.visitEachChild(node, visitor, context);
87443             }
87444         }
87445         function transformAndEmitWhileStatement(node) {
87446             if (containsYield(node)) {
87447                 // [source]
87448                 //      while (i < 10) {
87449                 //          /*body*/
87450                 //      }
87451                 //
87452                 // [intermediate]
87453                 //  .loop loopLabel, endLabel
87454                 //  .mark loopLabel
87455                 //  .brfalse endLabel, (i < 10)
87456                 //      /*body*/
87457                 //  .br loopLabel
87458                 //  .endloop
87459                 //  .mark endLabel
87460                 var loopLabel = defineLabel();
87461                 var endLabel = beginLoopBlock(loopLabel);
87462                 markLabel(loopLabel);
87463                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
87464                 transformAndEmitEmbeddedStatement(node.statement);
87465                 emitBreak(loopLabel);
87466                 endLoopBlock();
87467             }
87468             else {
87469                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87470             }
87471         }
87472         function visitWhileStatement(node) {
87473             if (inStatementContainingYield) {
87474                 beginScriptLoopBlock();
87475                 node = ts.visitEachChild(node, visitor, context);
87476                 endLoopBlock();
87477                 return node;
87478             }
87479             else {
87480                 return ts.visitEachChild(node, visitor, context);
87481             }
87482         }
87483         function transformAndEmitForStatement(node) {
87484             if (containsYield(node)) {
87485                 // [source]
87486                 //      for (var i = 0; i < 10; i++) {
87487                 //          /*body*/
87488                 //      }
87489                 //
87490                 // [intermediate]
87491                 //  .local i
87492                 //      i = 0;
87493                 //  .loop incrementLabel, endLoopLabel
87494                 //  .mark conditionLabel
87495                 //  .brfalse endLoopLabel, (i < 10)
87496                 //      /*body*/
87497                 //  .mark incrementLabel
87498                 //      i++;
87499                 //  .br conditionLabel
87500                 //  .endloop
87501                 //  .mark endLoopLabel
87502                 var conditionLabel = defineLabel();
87503                 var incrementLabel = defineLabel();
87504                 var endLabel = beginLoopBlock(incrementLabel);
87505                 if (node.initializer) {
87506                     var initializer = node.initializer;
87507                     if (ts.isVariableDeclarationList(initializer)) {
87508                         transformAndEmitVariableDeclarationList(initializer);
87509                     }
87510                     else {
87511                         emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
87512                     }
87513                 }
87514                 markLabel(conditionLabel);
87515                 if (node.condition) {
87516                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
87517                 }
87518                 transformAndEmitEmbeddedStatement(node.statement);
87519                 markLabel(incrementLabel);
87520                 if (node.incrementor) {
87521                     emitStatement(ts.setTextRange(ts.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
87522                 }
87523                 emitBreak(conditionLabel);
87524                 endLoopBlock();
87525             }
87526             else {
87527                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87528             }
87529         }
87530         function visitForStatement(node) {
87531             if (inStatementContainingYield) {
87532                 beginScriptLoopBlock();
87533             }
87534             var initializer = node.initializer;
87535             if (initializer && ts.isVariableDeclarationList(initializer)) {
87536                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87537                     var variable = _a[_i];
87538                     hoistVariableDeclaration(variable.name);
87539                 }
87540                 var variables = ts.getInitializedVariables(initializer);
87541                 node = ts.updateFor(node, variables.length > 0
87542                     ? ts.inlineExpressions(ts.map(variables, transformInitializedVariable))
87543                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87544             }
87545             else {
87546                 node = ts.visitEachChild(node, visitor, context);
87547             }
87548             if (inStatementContainingYield) {
87549                 endLoopBlock();
87550             }
87551             return node;
87552         }
87553         function transformAndEmitForInStatement(node) {
87554             // TODO(rbuckton): Source map locations
87555             if (containsYield(node)) {
87556                 // [source]
87557                 //      for (var p in o) {
87558                 //          /*body*/
87559                 //      }
87560                 //
87561                 // [intermediate]
87562                 //  .local _a, _b, _i
87563                 //      _a = [];
87564                 //      for (_b in o) _a.push(_b);
87565                 //      _i = 0;
87566                 //  .loop incrementLabel, endLoopLabel
87567                 //  .mark conditionLabel
87568                 //  .brfalse endLoopLabel, (_i < _a.length)
87569                 //      p = _a[_i];
87570                 //      /*body*/
87571                 //  .mark incrementLabel
87572                 //      _b++;
87573                 //  .br conditionLabel
87574                 //  .endloop
87575                 //  .mark endLoopLabel
87576                 var keysArray = declareLocal(); // _a
87577                 var key = declareLocal(); // _b
87578                 var keysIndex = ts.createLoopVariable(); // _i
87579                 var initializer = node.initializer;
87580                 hoistVariableDeclaration(keysIndex);
87581                 emitAssignment(keysArray, ts.createArrayLiteral());
87582                 emitStatement(ts.createForIn(key, ts.visitNode(node.expression, visitor, ts.isExpression), ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(keysArray, "push"), 
87583                 /*typeArguments*/ undefined, [key]))));
87584                 emitAssignment(keysIndex, ts.createLiteral(0));
87585                 var conditionLabel = defineLabel();
87586                 var incrementLabel = defineLabel();
87587                 var endLabel = beginLoopBlock(incrementLabel);
87588                 markLabel(conditionLabel);
87589                 emitBreakWhenFalse(endLabel, ts.createLessThan(keysIndex, ts.createPropertyAccess(keysArray, "length")));
87590                 var variable = void 0;
87591                 if (ts.isVariableDeclarationList(initializer)) {
87592                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87593                         var variable_1 = _a[_i];
87594                         hoistVariableDeclaration(variable_1.name);
87595                     }
87596                     variable = ts.getSynthesizedClone(initializer.declarations[0].name);
87597                 }
87598                 else {
87599                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
87600                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
87601                 }
87602                 emitAssignment(variable, ts.createElementAccess(keysArray, keysIndex));
87603                 transformAndEmitEmbeddedStatement(node.statement);
87604                 markLabel(incrementLabel);
87605                 emitStatement(ts.createExpressionStatement(ts.createPostfixIncrement(keysIndex)));
87606                 emitBreak(conditionLabel);
87607                 endLoopBlock();
87608             }
87609             else {
87610                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87611             }
87612         }
87613         function visitForInStatement(node) {
87614             // [source]
87615             //      for (var x in a) {
87616             //          /*body*/
87617             //      }
87618             //
87619             // [intermediate]
87620             //  .local x
87621             //  .loop
87622             //      for (x in a) {
87623             //          /*body*/
87624             //      }
87625             //  .endloop
87626             if (inStatementContainingYield) {
87627                 beginScriptLoopBlock();
87628             }
87629             var initializer = node.initializer;
87630             if (ts.isVariableDeclarationList(initializer)) {
87631                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
87632                     var variable = _a[_i];
87633                     hoistVariableDeclaration(variable.name);
87634                 }
87635                 node = ts.updateForIn(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock));
87636             }
87637             else {
87638                 node = ts.visitEachChild(node, visitor, context);
87639             }
87640             if (inStatementContainingYield) {
87641                 endLoopBlock();
87642             }
87643             return node;
87644         }
87645         function transformAndEmitContinueStatement(node) {
87646             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
87647             if (label > 0) {
87648                 emitBreak(label, /*location*/ node);
87649             }
87650             else {
87651                 // invalid continue without a containing loop. Leave the node as is, per #17875.
87652                 emitStatement(node);
87653             }
87654         }
87655         function visitContinueStatement(node) {
87656             if (inStatementContainingYield) {
87657                 var label = findContinueTarget(node.label && ts.idText(node.label));
87658                 if (label > 0) {
87659                     return createInlineBreak(label, /*location*/ node);
87660                 }
87661             }
87662             return ts.visitEachChild(node, visitor, context);
87663         }
87664         function transformAndEmitBreakStatement(node) {
87665             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
87666             if (label > 0) {
87667                 emitBreak(label, /*location*/ node);
87668             }
87669             else {
87670                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
87671                 emitStatement(node);
87672             }
87673         }
87674         function visitBreakStatement(node) {
87675             if (inStatementContainingYield) {
87676                 var label = findBreakTarget(node.label && ts.idText(node.label));
87677                 if (label > 0) {
87678                     return createInlineBreak(label, /*location*/ node);
87679                 }
87680             }
87681             return ts.visitEachChild(node, visitor, context);
87682         }
87683         function transformAndEmitReturnStatement(node) {
87684             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87685             /*location*/ node);
87686         }
87687         function visitReturnStatement(node) {
87688             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
87689             /*location*/ node);
87690         }
87691         function transformAndEmitWithStatement(node) {
87692             if (containsYield(node)) {
87693                 // [source]
87694                 //      with (x) {
87695                 //          /*body*/
87696                 //      }
87697                 //
87698                 // [intermediate]
87699                 //  .with (x)
87700                 //      /*body*/
87701                 //  .endwith
87702                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
87703                 transformAndEmitEmbeddedStatement(node.statement);
87704                 endWithBlock();
87705             }
87706             else {
87707                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87708             }
87709         }
87710         function transformAndEmitSwitchStatement(node) {
87711             if (containsYield(node.caseBlock)) {
87712                 // [source]
87713                 //      switch (x) {
87714                 //          case a:
87715                 //              /*caseStatements*/
87716                 //          case b:
87717                 //              /*caseStatements*/
87718                 //          default:
87719                 //              /*defaultStatements*/
87720                 //      }
87721                 //
87722                 // [intermediate]
87723                 //  .local _a
87724                 //  .switch endLabel
87725                 //      _a = x;
87726                 //      switch (_a) {
87727                 //          case a:
87728                 //  .br clauseLabels[0]
87729                 //      }
87730                 //      switch (_a) {
87731                 //          case b:
87732                 //  .br clauseLabels[1]
87733                 //      }
87734                 //  .br clauseLabels[2]
87735                 //  .mark clauseLabels[0]
87736                 //      /*caseStatements*/
87737                 //  .mark clauseLabels[1]
87738                 //      /*caseStatements*/
87739                 //  .mark clauseLabels[2]
87740                 //      /*caseStatements*/
87741                 //  .endswitch
87742                 //  .mark endLabel
87743                 var caseBlock = node.caseBlock;
87744                 var numClauses = caseBlock.clauses.length;
87745                 var endLabel = beginSwitchBlock();
87746                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
87747                 // Create labels for each clause and find the index of the first default clause.
87748                 var clauseLabels = [];
87749                 var defaultClauseIndex = -1;
87750                 for (var i = 0; i < numClauses; i++) {
87751                     var clause = caseBlock.clauses[i];
87752                     clauseLabels.push(defineLabel());
87753                     if (clause.kind === 278 /* DefaultClause */ && defaultClauseIndex === -1) {
87754                         defaultClauseIndex = i;
87755                     }
87756                 }
87757                 // Emit switch statements for each run of case clauses either from the first case
87758                 // clause or the next case clause with a `yield` in its expression, up to the next
87759                 // case clause with a `yield` in its expression.
87760                 var clausesWritten = 0;
87761                 var pendingClauses = [];
87762                 while (clausesWritten < numClauses) {
87763                     var defaultClausesSkipped = 0;
87764                     for (var i = clausesWritten; i < numClauses; i++) {
87765                         var clause = caseBlock.clauses[i];
87766                         if (clause.kind === 277 /* CaseClause */) {
87767                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
87768                                 break;
87769                             }
87770                             pendingClauses.push(ts.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
87771                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
87772                             ]));
87773                         }
87774                         else {
87775                             defaultClausesSkipped++;
87776                         }
87777                     }
87778                     if (pendingClauses.length) {
87779                         emitStatement(ts.createSwitch(expression, ts.createCaseBlock(pendingClauses)));
87780                         clausesWritten += pendingClauses.length;
87781                         pendingClauses = [];
87782                     }
87783                     if (defaultClausesSkipped > 0) {
87784                         clausesWritten += defaultClausesSkipped;
87785                         defaultClausesSkipped = 0;
87786                     }
87787                 }
87788                 if (defaultClauseIndex >= 0) {
87789                     emitBreak(clauseLabels[defaultClauseIndex]);
87790                 }
87791                 else {
87792                     emitBreak(endLabel);
87793                 }
87794                 for (var i = 0; i < numClauses; i++) {
87795                     markLabel(clauseLabels[i]);
87796                     transformAndEmitStatements(caseBlock.clauses[i].statements);
87797                 }
87798                 endSwitchBlock();
87799             }
87800             else {
87801                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87802             }
87803         }
87804         function visitSwitchStatement(node) {
87805             if (inStatementContainingYield) {
87806                 beginScriptSwitchBlock();
87807             }
87808             node = ts.visitEachChild(node, visitor, context);
87809             if (inStatementContainingYield) {
87810                 endSwitchBlock();
87811             }
87812             return node;
87813         }
87814         function transformAndEmitLabeledStatement(node) {
87815             if (containsYield(node)) {
87816                 // [source]
87817                 //      x: {
87818                 //          /*body*/
87819                 //      }
87820                 //
87821                 // [intermediate]
87822                 //  .labeled "x", endLabel
87823                 //      /*body*/
87824                 //  .endlabeled
87825                 //  .mark endLabel
87826                 beginLabeledBlock(ts.idText(node.label));
87827                 transformAndEmitEmbeddedStatement(node.statement);
87828                 endLabeledBlock();
87829             }
87830             else {
87831                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
87832             }
87833         }
87834         function visitLabeledStatement(node) {
87835             if (inStatementContainingYield) {
87836                 beginScriptLabeledBlock(ts.idText(node.label));
87837             }
87838             node = ts.visitEachChild(node, visitor, context);
87839             if (inStatementContainingYield) {
87840                 endLabeledBlock();
87841             }
87842             return node;
87843         }
87844         function transformAndEmitThrowStatement(node) {
87845             emitThrow(ts.visitNode(node.expression, visitor, ts.isExpression), 
87846             /*location*/ node);
87847         }
87848         function transformAndEmitTryStatement(node) {
87849             if (containsYield(node)) {
87850                 // [source]
87851                 //      try {
87852                 //          /*tryBlock*/
87853                 //      }
87854                 //      catch (e) {
87855                 //          /*catchBlock*/
87856                 //      }
87857                 //      finally {
87858                 //          /*finallyBlock*/
87859                 //      }
87860                 //
87861                 // [intermediate]
87862                 //  .local _a
87863                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
87864                 //  .mark tryLabel
87865                 //  .nop
87866                 //      /*tryBlock*/
87867                 //  .br endLabel
87868                 //  .catch
87869                 //  .mark catchLabel
87870                 //      _a = %error%;
87871                 //      /*catchBlock*/
87872                 //  .br endLabel
87873                 //  .finally
87874                 //  .mark finallyLabel
87875                 //      /*finallyBlock*/
87876                 //  .endfinally
87877                 //  .endtry
87878                 //  .mark endLabel
87879                 beginExceptionBlock();
87880                 transformAndEmitEmbeddedStatement(node.tryBlock);
87881                 if (node.catchClause) {
87882                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
87883                     transformAndEmitEmbeddedStatement(node.catchClause.block);
87884                 }
87885                 if (node.finallyBlock) {
87886                     beginFinallyBlock();
87887                     transformAndEmitEmbeddedStatement(node.finallyBlock);
87888                 }
87889                 endExceptionBlock();
87890             }
87891             else {
87892                 emitStatement(ts.visitEachChild(node, visitor, context));
87893             }
87894         }
87895         function containsYield(node) {
87896             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
87897         }
87898         function countInitialNodesWithoutYield(nodes) {
87899             var numNodes = nodes.length;
87900             for (var i = 0; i < numNodes; i++) {
87901                 if (containsYield(nodes[i])) {
87902                     return i;
87903                 }
87904             }
87905             return -1;
87906         }
87907         function onSubstituteNode(hint, node) {
87908             node = previousOnSubstituteNode(hint, node);
87909             if (hint === 1 /* Expression */) {
87910                 return substituteExpression(node);
87911             }
87912             return node;
87913         }
87914         function substituteExpression(node) {
87915             if (ts.isIdentifier(node)) {
87916                 return substituteExpressionIdentifier(node);
87917             }
87918             return node;
87919         }
87920         function substituteExpressionIdentifier(node) {
87921             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
87922                 var original = ts.getOriginalNode(node);
87923                 if (ts.isIdentifier(original) && original.parent) {
87924                     var declaration = resolver.getReferencedValueDeclaration(original);
87925                     if (declaration) {
87926                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
87927                         if (name) {
87928                             var clone_8 = ts.getMutableClone(name);
87929                             ts.setSourceMapRange(clone_8, node);
87930                             ts.setCommentRange(clone_8, node);
87931                             return clone_8;
87932                         }
87933                     }
87934                 }
87935             }
87936             return node;
87937         }
87938         function cacheExpression(node) {
87939             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
87940                 return node;
87941             }
87942             var temp = ts.createTempVariable(hoistVariableDeclaration);
87943             emitAssignment(temp, node, /*location*/ node);
87944             return temp;
87945         }
87946         function declareLocal(name) {
87947             var temp = name
87948                 ? ts.createUniqueName(name)
87949                 : ts.createTempVariable(/*recordTempVariable*/ undefined);
87950             hoistVariableDeclaration(temp);
87951             return temp;
87952         }
87953         /**
87954          * Defines a label, uses as the target of a Break operation.
87955          */
87956         function defineLabel() {
87957             if (!labelOffsets) {
87958                 labelOffsets = [];
87959             }
87960             var label = nextLabelId;
87961             nextLabelId++;
87962             labelOffsets[label] = -1;
87963             return label;
87964         }
87965         /**
87966          * Marks the current operation with the specified label.
87967          */
87968         function markLabel(label) {
87969             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
87970             labelOffsets[label] = operations ? operations.length : 0;
87971         }
87972         /**
87973          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
87974          *
87975          * @param block Information about the block.
87976          */
87977         function beginBlock(block) {
87978             if (!blocks) {
87979                 blocks = [];
87980                 blockActions = [];
87981                 blockOffsets = [];
87982                 blockStack = [];
87983             }
87984             var index = blockActions.length;
87985             blockActions[index] = 0 /* Open */;
87986             blockOffsets[index] = operations ? operations.length : 0;
87987             blocks[index] = block;
87988             blockStack.push(block);
87989             return index;
87990         }
87991         /**
87992          * Ends the current block operation.
87993          */
87994         function endBlock() {
87995             var block = peekBlock();
87996             if (block === undefined)
87997                 return ts.Debug.fail("beginBlock was never called.");
87998             var index = blockActions.length;
87999             blockActions[index] = 1 /* Close */;
88000             blockOffsets[index] = operations ? operations.length : 0;
88001             blocks[index] = block;
88002             blockStack.pop();
88003             return block;
88004         }
88005         /**
88006          * Gets the current open block.
88007          */
88008         function peekBlock() {
88009             return ts.lastOrUndefined(blockStack);
88010         }
88011         /**
88012          * Gets the kind of the current open block.
88013          */
88014         function peekBlockKind() {
88015             var block = peekBlock();
88016             return block && block.kind;
88017         }
88018         /**
88019          * Begins a code block for a generated `with` statement.
88020          *
88021          * @param expression An identifier representing expression for the `with` block.
88022          */
88023         function beginWithBlock(expression) {
88024             var startLabel = defineLabel();
88025             var endLabel = defineLabel();
88026             markLabel(startLabel);
88027             beginBlock({
88028                 kind: 1 /* With */,
88029                 expression: expression,
88030                 startLabel: startLabel,
88031                 endLabel: endLabel
88032             });
88033         }
88034         /**
88035          * Ends a code block for a generated `with` statement.
88036          */
88037         function endWithBlock() {
88038             ts.Debug.assert(peekBlockKind() === 1 /* With */);
88039             var block = endBlock();
88040             markLabel(block.endLabel);
88041         }
88042         /**
88043          * Begins a code block for a generated `try` statement.
88044          */
88045         function beginExceptionBlock() {
88046             var startLabel = defineLabel();
88047             var endLabel = defineLabel();
88048             markLabel(startLabel);
88049             beginBlock({
88050                 kind: 0 /* Exception */,
88051                 state: 0 /* Try */,
88052                 startLabel: startLabel,
88053                 endLabel: endLabel
88054             });
88055             emitNop();
88056             return endLabel;
88057         }
88058         /**
88059          * Enters the `catch` clause of a generated `try` statement.
88060          *
88061          * @param variable The catch variable.
88062          */
88063         function beginCatchBlock(variable) {
88064             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88065             // generated identifiers should already be unique within a file
88066             var name;
88067             if (ts.isGeneratedIdentifier(variable.name)) {
88068                 name = variable.name;
88069                 hoistVariableDeclaration(variable.name);
88070             }
88071             else {
88072                 var text = ts.idText(variable.name);
88073                 name = declareLocal(text);
88074                 if (!renamedCatchVariables) {
88075                     renamedCatchVariables = ts.createMap();
88076                     renamedCatchVariableDeclarations = [];
88077                     context.enableSubstitution(75 /* Identifier */);
88078                 }
88079                 renamedCatchVariables.set(text, true);
88080                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
88081             }
88082             var exception = peekBlock();
88083             ts.Debug.assert(exception.state < 1 /* Catch */);
88084             var endLabel = exception.endLabel;
88085             emitBreak(endLabel);
88086             var catchLabel = defineLabel();
88087             markLabel(catchLabel);
88088             exception.state = 1 /* Catch */;
88089             exception.catchVariable = name;
88090             exception.catchLabel = catchLabel;
88091             emitAssignment(name, ts.createCall(ts.createPropertyAccess(state, "sent"), /*typeArguments*/ undefined, []));
88092             emitNop();
88093         }
88094         /**
88095          * Enters the `finally` block of a generated `try` statement.
88096          */
88097         function beginFinallyBlock() {
88098             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88099             var exception = peekBlock();
88100             ts.Debug.assert(exception.state < 2 /* Finally */);
88101             var endLabel = exception.endLabel;
88102             emitBreak(endLabel);
88103             var finallyLabel = defineLabel();
88104             markLabel(finallyLabel);
88105             exception.state = 2 /* Finally */;
88106             exception.finallyLabel = finallyLabel;
88107         }
88108         /**
88109          * Ends the code block for a generated `try` statement.
88110          */
88111         function endExceptionBlock() {
88112             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
88113             var exception = endBlock();
88114             var state = exception.state;
88115             if (state < 2 /* Finally */) {
88116                 emitBreak(exception.endLabel);
88117             }
88118             else {
88119                 emitEndfinally();
88120             }
88121             markLabel(exception.endLabel);
88122             emitNop();
88123             exception.state = 3 /* Done */;
88124         }
88125         /**
88126          * Begins a code block that supports `break` or `continue` statements that are defined in
88127          * the source tree and not from generated code.
88128          *
88129          * @param labelText Names from containing labeled statements.
88130          */
88131         function beginScriptLoopBlock() {
88132             beginBlock({
88133                 kind: 3 /* Loop */,
88134                 isScript: true,
88135                 breakLabel: -1,
88136                 continueLabel: -1
88137             });
88138         }
88139         /**
88140          * Begins a code block that supports `break` or `continue` statements that are defined in
88141          * generated code. Returns a label used to mark the operation to which to jump when a
88142          * `break` statement targets this block.
88143          *
88144          * @param continueLabel A Label used to mark the operation to which to jump when a
88145          *                      `continue` statement targets this block.
88146          */
88147         function beginLoopBlock(continueLabel) {
88148             var breakLabel = defineLabel();
88149             beginBlock({
88150                 kind: 3 /* Loop */,
88151                 isScript: false,
88152                 breakLabel: breakLabel,
88153                 continueLabel: continueLabel,
88154             });
88155             return breakLabel;
88156         }
88157         /**
88158          * Ends a code block that supports `break` or `continue` statements that are defined in
88159          * generated code or in the source tree.
88160          */
88161         function endLoopBlock() {
88162             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
88163             var block = endBlock();
88164             var breakLabel = block.breakLabel;
88165             if (!block.isScript) {
88166                 markLabel(breakLabel);
88167             }
88168         }
88169         /**
88170          * Begins a code block that supports `break` statements that are defined in the source
88171          * tree and not from generated code.
88172          *
88173          */
88174         function beginScriptSwitchBlock() {
88175             beginBlock({
88176                 kind: 2 /* Switch */,
88177                 isScript: true,
88178                 breakLabel: -1
88179             });
88180         }
88181         /**
88182          * Begins a code block that supports `break` statements that are defined in generated code.
88183          * Returns a label used to mark the operation to which to jump when a `break` statement
88184          * targets this block.
88185          */
88186         function beginSwitchBlock() {
88187             var breakLabel = defineLabel();
88188             beginBlock({
88189                 kind: 2 /* Switch */,
88190                 isScript: false,
88191                 breakLabel: breakLabel,
88192             });
88193             return breakLabel;
88194         }
88195         /**
88196          * Ends a code block that supports `break` statements that are defined in generated code.
88197          */
88198         function endSwitchBlock() {
88199             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
88200             var block = endBlock();
88201             var breakLabel = block.breakLabel;
88202             if (!block.isScript) {
88203                 markLabel(breakLabel);
88204             }
88205         }
88206         function beginScriptLabeledBlock(labelText) {
88207             beginBlock({
88208                 kind: 4 /* Labeled */,
88209                 isScript: true,
88210                 labelText: labelText,
88211                 breakLabel: -1
88212             });
88213         }
88214         function beginLabeledBlock(labelText) {
88215             var breakLabel = defineLabel();
88216             beginBlock({
88217                 kind: 4 /* Labeled */,
88218                 isScript: false,
88219                 labelText: labelText,
88220                 breakLabel: breakLabel
88221             });
88222         }
88223         function endLabeledBlock() {
88224             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
88225             var block = endBlock();
88226             if (!block.isScript) {
88227                 markLabel(block.breakLabel);
88228             }
88229         }
88230         /**
88231          * Indicates whether the provided block supports `break` statements.
88232          *
88233          * @param block A code block.
88234          */
88235         function supportsUnlabeledBreak(block) {
88236             return block.kind === 2 /* Switch */
88237                 || block.kind === 3 /* Loop */;
88238         }
88239         /**
88240          * Indicates whether the provided block supports `break` statements with labels.
88241          *
88242          * @param block A code block.
88243          */
88244         function supportsLabeledBreakOrContinue(block) {
88245             return block.kind === 4 /* Labeled */;
88246         }
88247         /**
88248          * Indicates whether the provided block supports `continue` statements.
88249          *
88250          * @param block A code block.
88251          */
88252         function supportsUnlabeledContinue(block) {
88253             return block.kind === 3 /* Loop */;
88254         }
88255         function hasImmediateContainingLabeledBlock(labelText, start) {
88256             for (var j = start; j >= 0; j--) {
88257                 var containingBlock = blockStack[j];
88258                 if (supportsLabeledBreakOrContinue(containingBlock)) {
88259                     if (containingBlock.labelText === labelText) {
88260                         return true;
88261                     }
88262                 }
88263                 else {
88264                     break;
88265                 }
88266             }
88267             return false;
88268         }
88269         /**
88270          * Finds the label that is the target for a `break` statement.
88271          *
88272          * @param labelText An optional name of a containing labeled statement.
88273          */
88274         function findBreakTarget(labelText) {
88275             if (blockStack) {
88276                 if (labelText) {
88277                     for (var i = blockStack.length - 1; i >= 0; i--) {
88278                         var block = blockStack[i];
88279                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
88280                             return block.breakLabel;
88281                         }
88282                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88283                             return block.breakLabel;
88284                         }
88285                     }
88286                 }
88287                 else {
88288                     for (var i = blockStack.length - 1; i >= 0; i--) {
88289                         var block = blockStack[i];
88290                         if (supportsUnlabeledBreak(block)) {
88291                             return block.breakLabel;
88292                         }
88293                     }
88294                 }
88295             }
88296             return 0;
88297         }
88298         /**
88299          * Finds the label that is the target for a `continue` statement.
88300          *
88301          * @param labelText An optional name of a containing labeled statement.
88302          */
88303         function findContinueTarget(labelText) {
88304             if (blockStack) {
88305                 if (labelText) {
88306                     for (var i = blockStack.length - 1; i >= 0; i--) {
88307                         var block = blockStack[i];
88308                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
88309                             return block.continueLabel;
88310                         }
88311                     }
88312                 }
88313                 else {
88314                     for (var i = blockStack.length - 1; i >= 0; i--) {
88315                         var block = blockStack[i];
88316                         if (supportsUnlabeledContinue(block)) {
88317                             return block.continueLabel;
88318                         }
88319                     }
88320                 }
88321             }
88322             return 0;
88323         }
88324         /**
88325          * Creates an expression that can be used to indicate the value for a label.
88326          *
88327          * @param label A label.
88328          */
88329         function createLabel(label) {
88330             if (label !== undefined && label > 0) {
88331                 if (labelExpressions === undefined) {
88332                     labelExpressions = [];
88333                 }
88334                 var expression = ts.createLiteral(-1);
88335                 if (labelExpressions[label] === undefined) {
88336                     labelExpressions[label] = [expression];
88337                 }
88338                 else {
88339                     labelExpressions[label].push(expression);
88340                 }
88341                 return expression;
88342             }
88343             return ts.createOmittedExpression();
88344         }
88345         /**
88346          * Creates a numeric literal for the provided instruction.
88347          */
88348         function createInstruction(instruction) {
88349             var literal = ts.createLiteral(instruction);
88350             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
88351             return literal;
88352         }
88353         /**
88354          * Creates a statement that can be used indicate a Break operation to the provided label.
88355          *
88356          * @param label A label.
88357          * @param location An optional source map location for the statement.
88358          */
88359         function createInlineBreak(label, location) {
88360             ts.Debug.assertLessThan(0, label, "Invalid label");
88361             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88362                 createInstruction(3 /* Break */),
88363                 createLabel(label)
88364             ])), location);
88365         }
88366         /**
88367          * Creates a statement that can be used indicate a Return operation.
88368          *
88369          * @param expression The expression for the return statement.
88370          * @param location An optional source map location for the statement.
88371          */
88372         function createInlineReturn(expression, location) {
88373             return ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88374                 ? [createInstruction(2 /* Return */), expression]
88375                 : [createInstruction(2 /* Return */)])), location);
88376         }
88377         /**
88378          * Creates an expression that can be used to resume from a Yield operation.
88379          */
88380         function createGeneratorResume(location) {
88381             return ts.setTextRange(ts.createCall(ts.createPropertyAccess(state, "sent"), 
88382             /*typeArguments*/ undefined, []), location);
88383         }
88384         /**
88385          * Emits an empty instruction.
88386          */
88387         function emitNop() {
88388             emitWorker(0 /* Nop */);
88389         }
88390         /**
88391          * Emits a Statement.
88392          *
88393          * @param node A statement.
88394          */
88395         function emitStatement(node) {
88396             if (node) {
88397                 emitWorker(1 /* Statement */, [node]);
88398             }
88399             else {
88400                 emitNop();
88401             }
88402         }
88403         /**
88404          * Emits an Assignment operation.
88405          *
88406          * @param left The left-hand side of the assignment.
88407          * @param right The right-hand side of the assignment.
88408          * @param location An optional source map location for the assignment.
88409          */
88410         function emitAssignment(left, right, location) {
88411             emitWorker(2 /* Assign */, [left, right], location);
88412         }
88413         /**
88414          * Emits a Break operation to the specified label.
88415          *
88416          * @param label A label.
88417          * @param location An optional source map location for the assignment.
88418          */
88419         function emitBreak(label, location) {
88420             emitWorker(3 /* Break */, [label], location);
88421         }
88422         /**
88423          * Emits a Break operation to the specified label when a condition evaluates to a truthy
88424          * value at runtime.
88425          *
88426          * @param label A label.
88427          * @param condition The condition.
88428          * @param location An optional source map location for the assignment.
88429          */
88430         function emitBreakWhenTrue(label, condition, location) {
88431             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
88432         }
88433         /**
88434          * Emits a Break to the specified label when a condition evaluates to a falsey value at
88435          * runtime.
88436          *
88437          * @param label A label.
88438          * @param condition The condition.
88439          * @param location An optional source map location for the assignment.
88440          */
88441         function emitBreakWhenFalse(label, condition, location) {
88442             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
88443         }
88444         /**
88445          * Emits a YieldStar operation for the provided expression.
88446          *
88447          * @param expression An optional value for the yield operation.
88448          * @param location An optional source map location for the assignment.
88449          */
88450         function emitYieldStar(expression, location) {
88451             emitWorker(7 /* YieldStar */, [expression], location);
88452         }
88453         /**
88454          * Emits a Yield operation for the provided expression.
88455          *
88456          * @param expression An optional value for the yield operation.
88457          * @param location An optional source map location for the assignment.
88458          */
88459         function emitYield(expression, location) {
88460             emitWorker(6 /* Yield */, [expression], location);
88461         }
88462         /**
88463          * Emits a Return operation for the provided expression.
88464          *
88465          * @param expression An optional value for the operation.
88466          * @param location An optional source map location for the assignment.
88467          */
88468         function emitReturn(expression, location) {
88469             emitWorker(8 /* Return */, [expression], location);
88470         }
88471         /**
88472          * Emits a Throw operation for the provided expression.
88473          *
88474          * @param expression A value for the operation.
88475          * @param location An optional source map location for the assignment.
88476          */
88477         function emitThrow(expression, location) {
88478             emitWorker(9 /* Throw */, [expression], location);
88479         }
88480         /**
88481          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
88482          */
88483         function emitEndfinally() {
88484             emitWorker(10 /* Endfinally */);
88485         }
88486         /**
88487          * Emits an operation.
88488          *
88489          * @param code The OpCode for the operation.
88490          * @param args The optional arguments for the operation.
88491          */
88492         function emitWorker(code, args, location) {
88493             if (operations === undefined) {
88494                 operations = [];
88495                 operationArguments = [];
88496                 operationLocations = [];
88497             }
88498             if (labelOffsets === undefined) {
88499                 // mark entry point
88500                 markLabel(defineLabel());
88501             }
88502             var operationIndex = operations.length;
88503             operations[operationIndex] = code;
88504             operationArguments[operationIndex] = args;
88505             operationLocations[operationIndex] = location;
88506         }
88507         /**
88508          * Builds the generator function body.
88509          */
88510         function build() {
88511             blockIndex = 0;
88512             labelNumber = 0;
88513             labelNumbers = undefined;
88514             lastOperationWasAbrupt = false;
88515             lastOperationWasCompletion = false;
88516             clauses = undefined;
88517             statements = undefined;
88518             exceptionBlockStack = undefined;
88519             currentExceptionBlock = undefined;
88520             withBlockStack = undefined;
88521             var buildResult = buildStatements();
88522             return createGeneratorHelper(context, ts.setEmitFlags(ts.createFunctionExpression(
88523             /*modifiers*/ undefined, 
88524             /*asteriskToken*/ undefined, 
88525             /*name*/ undefined, 
88526             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
88527             /*type*/ undefined, ts.createBlock(buildResult, 
88528             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
88529         }
88530         /**
88531          * Builds the statements for the generator function body.
88532          */
88533         function buildStatements() {
88534             if (operations) {
88535                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
88536                     writeOperation(operationIndex);
88537                 }
88538                 flushFinalLabel(operations.length);
88539             }
88540             else {
88541                 flushFinalLabel(0);
88542             }
88543             if (clauses) {
88544                 var labelExpression = ts.createPropertyAccess(state, "label");
88545                 var switchStatement = ts.createSwitch(labelExpression, ts.createCaseBlock(clauses));
88546                 return [ts.startOnNewLine(switchStatement)];
88547             }
88548             if (statements) {
88549                 return statements;
88550             }
88551             return [];
88552         }
88553         /**
88554          * Flush the current label and advance to a new label.
88555          */
88556         function flushLabel() {
88557             if (!statements) {
88558                 return;
88559             }
88560             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
88561             lastOperationWasAbrupt = false;
88562             lastOperationWasCompletion = false;
88563             labelNumber++;
88564         }
88565         /**
88566          * Flush the final label of the generator function body.
88567          */
88568         function flushFinalLabel(operationIndex) {
88569             if (isFinalLabelReachable(operationIndex)) {
88570                 tryEnterLabel(operationIndex);
88571                 withBlockStack = undefined;
88572                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
88573             }
88574             if (statements && clauses) {
88575                 appendLabel(/*markLabelEnd*/ false);
88576             }
88577             updateLabelExpressions();
88578         }
88579         /**
88580          * Tests whether the final label of the generator function body
88581          * is reachable by user code.
88582          */
88583         function isFinalLabelReachable(operationIndex) {
88584             // if the last operation was *not* a completion (return/throw) then
88585             // the final label is reachable.
88586             if (!lastOperationWasCompletion) {
88587                 return true;
88588             }
88589             // if there are no labels defined or referenced, then the final label is
88590             // not reachable.
88591             if (!labelOffsets || !labelExpressions) {
88592                 return false;
88593             }
88594             // if the label for this offset is referenced, then the final label
88595             // is reachable.
88596             for (var label = 0; label < labelOffsets.length; label++) {
88597                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
88598                     return true;
88599                 }
88600             }
88601             return false;
88602         }
88603         /**
88604          * Appends a case clause for the last label and sets the new label.
88605          *
88606          * @param markLabelEnd Indicates that the transition between labels was a fall-through
88607          *                     from a previous case clause and the change in labels should be
88608          *                     reflected on the `state` object.
88609          */
88610         function appendLabel(markLabelEnd) {
88611             if (!clauses) {
88612                 clauses = [];
88613             }
88614             if (statements) {
88615                 if (withBlockStack) {
88616                     // The previous label was nested inside one or more `with` blocks, so we
88617                     // surround the statements in generated `with` blocks to create the same environment.
88618                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
88619                         var withBlock = withBlockStack[i];
88620                         statements = [ts.createWith(withBlock.expression, ts.createBlock(statements))];
88621                     }
88622                 }
88623                 if (currentExceptionBlock) {
88624                     // The previous label was nested inside of an exception block, so we must
88625                     // indicate entry into a protected region by pushing the label numbers
88626                     // for each block in the protected region.
88627                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
88628                     statements.unshift(ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createPropertyAccess(state, "trys"), "push"), 
88629                     /*typeArguments*/ undefined, [
88630                         ts.createArrayLiteral([
88631                             createLabel(startLabel),
88632                             createLabel(catchLabel),
88633                             createLabel(finallyLabel),
88634                             createLabel(endLabel)
88635                         ])
88636                     ])));
88637                     currentExceptionBlock = undefined;
88638                 }
88639                 if (markLabelEnd) {
88640                     // The case clause for the last label falls through to this label, so we
88641                     // add an assignment statement to reflect the change in labels.
88642                     statements.push(ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(state, "label"), ts.createLiteral(labelNumber + 1))));
88643                 }
88644             }
88645             clauses.push(ts.createCaseClause(ts.createLiteral(labelNumber), statements || []));
88646             statements = undefined;
88647         }
88648         /**
88649          * Tries to enter into a new label at the current operation index.
88650          */
88651         function tryEnterLabel(operationIndex) {
88652             if (!labelOffsets) {
88653                 return;
88654             }
88655             for (var label = 0; label < labelOffsets.length; label++) {
88656                 if (labelOffsets[label] === operationIndex) {
88657                     flushLabel();
88658                     if (labelNumbers === undefined) {
88659                         labelNumbers = [];
88660                     }
88661                     if (labelNumbers[labelNumber] === undefined) {
88662                         labelNumbers[labelNumber] = [label];
88663                     }
88664                     else {
88665                         labelNumbers[labelNumber].push(label);
88666                     }
88667                 }
88668             }
88669         }
88670         /**
88671          * Updates literal expressions for labels with actual label numbers.
88672          */
88673         function updateLabelExpressions() {
88674             if (labelExpressions !== undefined && labelNumbers !== undefined) {
88675                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
88676                     var labels = labelNumbers[labelNumber_1];
88677                     if (labels !== undefined) {
88678                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
88679                             var label = labels_1[_i];
88680                             var expressions = labelExpressions[label];
88681                             if (expressions !== undefined) {
88682                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
88683                                     var expression = expressions_1[_a];
88684                                     expression.text = String(labelNumber_1);
88685                                 }
88686                             }
88687                         }
88688                     }
88689                 }
88690             }
88691         }
88692         /**
88693          * Tries to enter or leave a code block.
88694          */
88695         function tryEnterOrLeaveBlock(operationIndex) {
88696             if (blocks) {
88697                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
88698                     var block = blocks[blockIndex];
88699                     var blockAction = blockActions[blockIndex];
88700                     switch (block.kind) {
88701                         case 0 /* Exception */:
88702                             if (blockAction === 0 /* Open */) {
88703                                 if (!exceptionBlockStack) {
88704                                     exceptionBlockStack = [];
88705                                 }
88706                                 if (!statements) {
88707                                     statements = [];
88708                                 }
88709                                 exceptionBlockStack.push(currentExceptionBlock);
88710                                 currentExceptionBlock = block;
88711                             }
88712                             else if (blockAction === 1 /* Close */) {
88713                                 currentExceptionBlock = exceptionBlockStack.pop();
88714                             }
88715                             break;
88716                         case 1 /* With */:
88717                             if (blockAction === 0 /* Open */) {
88718                                 if (!withBlockStack) {
88719                                     withBlockStack = [];
88720                                 }
88721                                 withBlockStack.push(block);
88722                             }
88723                             else if (blockAction === 1 /* Close */) {
88724                                 withBlockStack.pop();
88725                             }
88726                             break;
88727                         // default: do nothing
88728                     }
88729                 }
88730             }
88731         }
88732         /**
88733          * Writes an operation as a statement to the current label's statement list.
88734          *
88735          * @param operation The OpCode of the operation
88736          */
88737         function writeOperation(operationIndex) {
88738             tryEnterLabel(operationIndex);
88739             tryEnterOrLeaveBlock(operationIndex);
88740             // early termination, nothing else to process in this label
88741             if (lastOperationWasAbrupt) {
88742                 return;
88743             }
88744             lastOperationWasAbrupt = false;
88745             lastOperationWasCompletion = false;
88746             var opcode = operations[operationIndex];
88747             if (opcode === 0 /* Nop */) {
88748                 return;
88749             }
88750             else if (opcode === 10 /* Endfinally */) {
88751                 return writeEndfinally();
88752             }
88753             var args = operationArguments[operationIndex];
88754             if (opcode === 1 /* Statement */) {
88755                 return writeStatement(args[0]);
88756             }
88757             var location = operationLocations[operationIndex];
88758             switch (opcode) {
88759                 case 2 /* Assign */:
88760                     return writeAssign(args[0], args[1], location);
88761                 case 3 /* Break */:
88762                     return writeBreak(args[0], location);
88763                 case 4 /* BreakWhenTrue */:
88764                     return writeBreakWhenTrue(args[0], args[1], location);
88765                 case 5 /* BreakWhenFalse */:
88766                     return writeBreakWhenFalse(args[0], args[1], location);
88767                 case 6 /* Yield */:
88768                     return writeYield(args[0], location);
88769                 case 7 /* YieldStar */:
88770                     return writeYieldStar(args[0], location);
88771                 case 8 /* Return */:
88772                     return writeReturn(args[0], location);
88773                 case 9 /* Throw */:
88774                     return writeThrow(args[0], location);
88775             }
88776         }
88777         /**
88778          * Writes a statement to the current label's statement list.
88779          *
88780          * @param statement A statement to write.
88781          */
88782         function writeStatement(statement) {
88783             if (statement) {
88784                 if (!statements) {
88785                     statements = [statement];
88786                 }
88787                 else {
88788                     statements.push(statement);
88789                 }
88790             }
88791         }
88792         /**
88793          * Writes an Assign operation to the current label's statement list.
88794          *
88795          * @param left The left-hand side of the assignment.
88796          * @param right The right-hand side of the assignment.
88797          * @param operationLocation The source map location for the operation.
88798          */
88799         function writeAssign(left, right, operationLocation) {
88800             writeStatement(ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(left, right)), operationLocation));
88801         }
88802         /**
88803          * Writes a Throw operation to the current label's statement list.
88804          *
88805          * @param expression The value to throw.
88806          * @param operationLocation The source map location for the operation.
88807          */
88808         function writeThrow(expression, operationLocation) {
88809             lastOperationWasAbrupt = true;
88810             lastOperationWasCompletion = true;
88811             writeStatement(ts.setTextRange(ts.createThrow(expression), operationLocation));
88812         }
88813         /**
88814          * Writes a Return operation to the current label's statement list.
88815          *
88816          * @param expression The value to return.
88817          * @param operationLocation The source map location for the operation.
88818          */
88819         function writeReturn(expression, operationLocation) {
88820             lastOperationWasAbrupt = true;
88821             lastOperationWasCompletion = true;
88822             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88823                 ? [createInstruction(2 /* Return */), expression]
88824                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88825         }
88826         /**
88827          * Writes a Break operation to the current label's statement list.
88828          *
88829          * @param label The label for the Break.
88830          * @param operationLocation The source map location for the operation.
88831          */
88832         function writeBreak(label, operationLocation) {
88833             lastOperationWasAbrupt = true;
88834             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88835                 createInstruction(3 /* Break */),
88836                 createLabel(label)
88837             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88838         }
88839         /**
88840          * Writes a BreakWhenTrue operation to the current label's statement list.
88841          *
88842          * @param label The label for the Break.
88843          * @param condition The condition for the Break.
88844          * @param operationLocation The source map location for the operation.
88845          */
88846         function writeBreakWhenTrue(label, condition, operationLocation) {
88847             writeStatement(ts.setEmitFlags(ts.createIf(condition, ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88848                 createInstruction(3 /* Break */),
88849                 createLabel(label)
88850             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88851         }
88852         /**
88853          * Writes a BreakWhenFalse operation to the current label's statement list.
88854          *
88855          * @param label The label for the Break.
88856          * @param condition The condition for the Break.
88857          * @param operationLocation The source map location for the operation.
88858          */
88859         function writeBreakWhenFalse(label, condition, operationLocation) {
88860             writeStatement(ts.setEmitFlags(ts.createIf(ts.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88861                 createInstruction(3 /* Break */),
88862                 createLabel(label)
88863             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
88864         }
88865         /**
88866          * Writes a Yield operation to the current label's statement list.
88867          *
88868          * @param expression The expression to yield.
88869          * @param operationLocation The source map location for the operation.
88870          */
88871         function writeYield(expression, operationLocation) {
88872             lastOperationWasAbrupt = true;
88873             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral(expression
88874                 ? [createInstruction(4 /* Yield */), expression]
88875                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
88876         }
88877         /**
88878          * Writes a YieldStar instruction to the current label's statement list.
88879          *
88880          * @param expression The expression to yield.
88881          * @param operationLocation The source map location for the operation.
88882          */
88883         function writeYieldStar(expression, operationLocation) {
88884             lastOperationWasAbrupt = true;
88885             writeStatement(ts.setEmitFlags(ts.setTextRange(ts.createReturn(ts.createArrayLiteral([
88886                 createInstruction(5 /* YieldStar */),
88887                 expression
88888             ])), operationLocation), 384 /* NoTokenSourceMaps */));
88889         }
88890         /**
88891          * Writes an Endfinally instruction to the current label's statement list.
88892          */
88893         function writeEndfinally() {
88894             lastOperationWasAbrupt = true;
88895             writeStatement(ts.createReturn(ts.createArrayLiteral([
88896                 createInstruction(7 /* Endfinally */)
88897             ])));
88898         }
88899     }
88900     ts.transformGenerators = transformGenerators;
88901     function createGeneratorHelper(context, body) {
88902         context.requestEmitHelper(ts.generatorHelper);
88903         return ts.createCall(ts.getUnscopedHelperName("__generator"), 
88904         /*typeArguments*/ undefined, [ts.createThis(), body]);
88905     }
88906     // The __generator helper is used by down-level transformations to emulate the runtime
88907     // semantics of an ES2015 generator function. When called, this helper returns an
88908     // object that implements the Iterator protocol, in that it has `next`, `return`, and
88909     // `throw` methods that step through the generator when invoked.
88910     //
88911     // parameters:
88912     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
88913     //  @param body     A function that acts as the transformed generator body.
88914     //
88915     // variables:
88916     //  _       Persistent state for the generator that is shared between the helper and the
88917     //          generator body. The state object has the following members:
88918     //            sent() - A method that returns or throws the current completion value.
88919     //            label  - The next point at which to resume evaluation of the generator body.
88920     //            trys   - A stack of protected regions (try/catch/finally blocks).
88921     //            ops    - A stack of pending instructions when inside of a finally block.
88922     //  f       A value indicating whether the generator is executing.
88923     //  y       An iterator to delegate for a yield*.
88924     //  t       A temporary variable that holds one of the following values (note that these
88925     //          cases do not overlap):
88926     //          - The completion value when resuming from a `yield` or `yield*`.
88927     //          - The error value for a catch block.
88928     //          - The current protected region (array of try/catch/finally/end labels).
88929     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
88930     //            of a `yield*`.
88931     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
88932     //
88933     // functions:
88934     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
88935     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
88936     //              completed.
88937     //
88938     // The __generator helper understands a limited set of instructions:
88939     //  0: next(value?)     - Start or resume the generator with the specified value.
88940     //  1: throw(error)     - Resume the generator with an exception. If the generator is
88941     //                        suspended inside of one or more protected regions, evaluates
88942     //                        any intervening finally blocks between the current label and
88943     //                        the nearest catch block or function boundary. If uncaught, the
88944     //                        exception is thrown to the caller.
88945     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
88946     //                        suspended inside of one or more protected regions, evaluates any
88947     //                        intervening finally blocks.
88948     //  3: break(label)     - Jump to the specified label. If the label is outside of the
88949     //                        current protected region, evaluates any intervening finally
88950     //                        blocks.
88951     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
88952     //                        resumed, the generator will continue at the next label.
88953     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
88954     //                        delegation completes, the generator will continue at the next
88955     //                        label.
88956     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
88957     //                        the current label is inside of one or more protected regions,
88958     //                        evaluates any intervening finally blocks between the current
88959     //                        label and the nearest catch block or function boundary. If
88960     //                        uncaught, the exception is thrown to the caller.
88961     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
88962     //                        entering a finally block.
88963     //
88964     // For examples of how these are used, see the comments in ./transformers/generators.ts
88965     ts.generatorHelper = {
88966         name: "typescript:generator",
88967         importName: "__generator",
88968         scoped: false,
88969         priority: 6,
88970         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            };"
88971     };
88972 })(ts || (ts = {}));
88973 /*@internal*/
88974 var ts;
88975 (function (ts) {
88976     function transformModule(context) {
88977         function getTransformModuleDelegate(moduleKind) {
88978             switch (moduleKind) {
88979                 case ts.ModuleKind.AMD: return transformAMDModule;
88980                 case ts.ModuleKind.UMD: return transformUMDModule;
88981                 default: return transformCommonJSModule;
88982             }
88983         }
88984         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
88985         var compilerOptions = context.getCompilerOptions();
88986         var resolver = context.getEmitResolver();
88987         var host = context.getEmitHost();
88988         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
88989         var moduleKind = ts.getEmitModuleKind(compilerOptions);
88990         var previousOnSubstituteNode = context.onSubstituteNode;
88991         var previousOnEmitNode = context.onEmitNode;
88992         context.onSubstituteNode = onSubstituteNode;
88993         context.onEmitNode = onEmitNode;
88994         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
88995         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
88996         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
88997         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
88998         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
88999         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
89000         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
89001         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
89002         var currentSourceFile; // The current file.
89003         var currentModuleInfo; // The ExternalModuleInfo for the current file.
89004         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
89005         var needUMDDynamicImportHelper;
89006         return ts.chainBundle(transformSourceFile);
89007         /**
89008          * Transforms the module aspects of a SourceFile.
89009          *
89010          * @param node The SourceFile node.
89011          */
89012         function transformSourceFile(node) {
89013             if (node.isDeclarationFile ||
89014                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
89015                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
89016                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) {
89017                 return node;
89018             }
89019             currentSourceFile = node;
89020             currentModuleInfo = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
89021             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
89022             // Perform the transformation.
89023             var transformModule = getTransformModuleDelegate(moduleKind);
89024             var updated = transformModule(node);
89025             currentSourceFile = undefined;
89026             currentModuleInfo = undefined;
89027             needUMDDynamicImportHelper = false;
89028             return ts.aggregateTransformFlags(updated);
89029         }
89030         function shouldEmitUnderscoreUnderscoreESModule() {
89031             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
89032                 return true;
89033             }
89034             return false;
89035         }
89036         /**
89037          * Transforms a SourceFile into a CommonJS module.
89038          *
89039          * @param node The SourceFile node.
89040          */
89041         function transformCommonJSModule(node) {
89042             startLexicalEnvironment();
89043             var statements = [];
89044             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
89045             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
89046             if (shouldEmitUnderscoreUnderscoreESModule()) {
89047                 ts.append(statements, createUnderscoreUnderscoreESModule());
89048             }
89049             if (ts.length(currentModuleInfo.exportedNames)) {
89050                 ts.append(statements, ts.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(ts.idText(nextId))), prev); }, ts.createVoidZero())));
89051             }
89052             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89053             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89054             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
89055             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89056             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
89057             ts.addEmitHelpers(updated, context.readEmitHelpers());
89058             return updated;
89059         }
89060         /**
89061          * Transforms a SourceFile into an AMD module.
89062          *
89063          * @param node The SourceFile node.
89064          */
89065         function transformAMDModule(node) {
89066             var define = ts.createIdentifier("define");
89067             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89068             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
89069             // An AMD define function has the following shape:
89070             //
89071             //     define(id?, dependencies?, factory);
89072             //
89073             // This has the shape of the following:
89074             //
89075             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
89076             //
89077             // The location of the alias in the parameter list in the factory function needs to
89078             // match the position of the module name in the dependency list.
89079             //
89080             // To ensure this is true in cases of modules with no aliases, e.g.:
89081             //
89082             //     import "module"
89083             //
89084             // or
89085             //
89086             //     /// <amd-dependency path= "a.css" />
89087             //
89088             // we need to add modules without alias names to the end of the dependencies list
89089             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89090             // Create an updated SourceFile:
89091             //
89092             //     define(moduleName?, ["module1", "module2"], function ...
89093             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89094                 ts.createExpressionStatement(ts.createCall(define, 
89095                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89096                     // Add the dependency array argument:
89097                     //
89098                     //     ["require", "exports", module1", "module2", ...]
89099                     ts.createArrayLiteral(jsonSourceFile ? ts.emptyArray : __spreadArrays([
89100                         ts.createLiteral("require"),
89101                         ts.createLiteral("exports")
89102                     ], aliasedModuleNames, unaliasedModuleNames)),
89103                     // Add the module body function argument:
89104                     //
89105                     //     function (require, exports, module1, module2) ...
89106                     jsonSourceFile ?
89107                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : ts.createObjectLiteral() :
89108                         ts.createFunctionExpression(
89109                         /*modifiers*/ undefined, 
89110                         /*asteriskToken*/ undefined, 
89111                         /*name*/ undefined, 
89112                         /*typeParameters*/ undefined, __spreadArrays([
89113                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89114                             ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89115                         ], importAliasNames), 
89116                         /*type*/ undefined, transformAsynchronousModuleBody(node))
89117                 ])))
89118             ]), 
89119             /*location*/ node.statements));
89120             ts.addEmitHelpers(updated, context.readEmitHelpers());
89121             return updated;
89122         }
89123         /**
89124          * Transforms a SourceFile into a UMD module.
89125          *
89126          * @param node The SourceFile node.
89127          */
89128         function transformUMDModule(node) {
89129             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
89130             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
89131             var umdHeader = ts.createFunctionExpression(
89132             /*modifiers*/ undefined, 
89133             /*asteriskToken*/ undefined, 
89134             /*name*/ undefined, 
89135             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
89136             /*type*/ undefined, ts.setTextRange(ts.createBlock([
89137                 ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("module"), "object"), ts.createTypeCheck(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), "object")), ts.createBlock([
89138                     ts.createVariableStatement(
89139                     /*modifiers*/ undefined, [
89140                         ts.createVariableDeclaration("v", 
89141                         /*type*/ undefined, ts.createCall(ts.createIdentifier("factory"), 
89142                         /*typeArguments*/ undefined, [
89143                             ts.createIdentifier("require"),
89144                             ts.createIdentifier("exports")
89145                         ]))
89146                     ]),
89147                     ts.setEmitFlags(ts.createIf(ts.createStrictInequality(ts.createIdentifier("v"), ts.createIdentifier("undefined")), ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), ts.createIdentifier("v")))), 1 /* SingleLine */)
89148                 ]), ts.createIf(ts.createLogicalAnd(ts.createTypeCheck(ts.createIdentifier("define"), "function"), ts.createPropertyAccess(ts.createIdentifier("define"), "amd")), ts.createBlock([
89149                     ts.createExpressionStatement(ts.createCall(ts.createIdentifier("define"), 
89150                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
89151                         ts.createArrayLiteral(__spreadArrays([
89152                             ts.createLiteral("require"),
89153                             ts.createLiteral("exports")
89154                         ], aliasedModuleNames, unaliasedModuleNames)),
89155                         ts.createIdentifier("factory")
89156                     ])))
89157                 ])))
89158             ], 
89159             /*multiLine*/ true), 
89160             /*location*/ undefined));
89161             // Create an updated SourceFile:
89162             //
89163             //  (function (factory) {
89164             //      if (typeof module === "object" && typeof module.exports === "object") {
89165             //          var v = factory(require, exports);
89166             //          if (v !== undefined) module.exports = v;
89167             //      }
89168             //      else if (typeof define === 'function' && define.amd) {
89169             //          define(["require", "exports"], factory);
89170             //      }
89171             //  })(function ...)
89172             var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
89173                 ts.createExpressionStatement(ts.createCall(umdHeader, 
89174                 /*typeArguments*/ undefined, [
89175                     // Add the module body function argument:
89176                     //
89177                     //     function (require, exports) ...
89178                     ts.createFunctionExpression(
89179                     /*modifiers*/ undefined, 
89180                     /*asteriskToken*/ undefined, 
89181                     /*name*/ undefined, 
89182                     /*typeParameters*/ undefined, __spreadArrays([
89183                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
89184                         ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
89185                     ], importAliasNames), 
89186                     /*type*/ undefined, transformAsynchronousModuleBody(node))
89187                 ]))
89188             ]), 
89189             /*location*/ node.statements));
89190             ts.addEmitHelpers(updated, context.readEmitHelpers());
89191             return updated;
89192         }
89193         /**
89194          * Collect the additional asynchronous dependencies for the module.
89195          *
89196          * @param node The source file.
89197          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
89198          */
89199         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
89200             // names of modules with corresponding parameter in the factory function
89201             var aliasedModuleNames = [];
89202             // names of modules with no corresponding parameters in factory function
89203             var unaliasedModuleNames = [];
89204             // names of the parameters in the factory function; these
89205             // parameters need to match the indexes of the corresponding
89206             // module names in aliasedModuleNames.
89207             var importAliasNames = [];
89208             // Fill in amd-dependency tags
89209             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
89210                 var amdDependency = _a[_i];
89211                 if (amdDependency.name) {
89212                     aliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89213                     importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
89214                 }
89215                 else {
89216                     unaliasedModuleNames.push(ts.createLiteral(amdDependency.path));
89217                 }
89218             }
89219             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
89220                 var importNode = _c[_b];
89221                 // Find the name of the external module
89222                 var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89223                 // Find the name of the module alias, if there is one
89224                 var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile);
89225                 // It is possible that externalModuleName is undefined if it is not string literal.
89226                 // This can happen in the invalid import syntax.
89227                 // E.g : "import * from alias from 'someLib';"
89228                 if (externalModuleName) {
89229                     if (includeNonAmdDependencies && importAliasName) {
89230                         // Set emitFlags on the name of the classDeclaration
89231                         // This is so that when printer will not substitute the identifier
89232                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
89233                         aliasedModuleNames.push(externalModuleName);
89234                         importAliasNames.push(ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
89235                     }
89236                     else {
89237                         unaliasedModuleNames.push(externalModuleName);
89238                     }
89239                 }
89240             }
89241             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
89242         }
89243         function getAMDImportExpressionForImport(node) {
89244             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) {
89245                 return undefined;
89246             }
89247             var name = ts.getLocalNameForExternalImport(node, currentSourceFile); // TODO: GH#18217
89248             var expr = getHelperExpressionForImport(node, name);
89249             if (expr === name) {
89250                 return undefined;
89251             }
89252             return ts.createExpressionStatement(ts.createAssignment(name, expr));
89253         }
89254         /**
89255          * Transforms a SourceFile into an AMD or UMD module body.
89256          *
89257          * @param node The SourceFile node.
89258          */
89259         function transformAsynchronousModuleBody(node) {
89260             startLexicalEnvironment();
89261             var statements = [];
89262             var statementOffset = ts.addPrologue(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
89263             if (shouldEmitUnderscoreUnderscoreESModule()) {
89264                 ts.append(statements, createUnderscoreUnderscoreESModule());
89265             }
89266             if (ts.length(currentModuleInfo.exportedNames)) {
89267                 ts.append(statements, ts.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.createIdentifier(ts.idText(nextId))), prev); }, ts.createVoidZero())));
89268             }
89269             // Visit each statement of the module body.
89270             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
89271             if (moduleKind === ts.ModuleKind.AMD) {
89272                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
89273             }
89274             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
89275             // Append the 'export =' statement if provided.
89276             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
89277             // End the lexical environment for the module body
89278             // and merge any new lexical declarations.
89279             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89280             var body = ts.createBlock(statements, /*multiLine*/ true);
89281             if (needUMDDynamicImportHelper) {
89282                 ts.addEmitHelper(body, dynamicImportUMDHelper);
89283             }
89284             return body;
89285         }
89286         /**
89287          * Adds the down-level representation of `export=` to the statement list if one exists
89288          * in the source file.
89289          *
89290          * @param statements The Statement list to modify.
89291          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
89292          * return statement.
89293          */
89294         function addExportEqualsIfNeeded(statements, emitAsReturn) {
89295             if (currentModuleInfo.exportEquals) {
89296                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
89297                 if (expressionResult) {
89298                     if (emitAsReturn) {
89299                         var statement = ts.createReturn(expressionResult);
89300                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89301                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
89302                         statements.push(statement);
89303                     }
89304                     else {
89305                         var statement = ts.createExpressionStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), expressionResult));
89306                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
89307                         ts.setEmitFlags(statement, 1536 /* NoComments */);
89308                         statements.push(statement);
89309                     }
89310                 }
89311             }
89312         }
89313         //
89314         // Top-Level Source Element Visitors
89315         //
89316         /**
89317          * Visits a node at the top level of the source file.
89318          *
89319          * @param node The node to visit.
89320          */
89321         function sourceElementVisitor(node) {
89322             switch (node.kind) {
89323                 case 254 /* ImportDeclaration */:
89324                     return visitImportDeclaration(node);
89325                 case 253 /* ImportEqualsDeclaration */:
89326                     return visitImportEqualsDeclaration(node);
89327                 case 260 /* ExportDeclaration */:
89328                     return visitExportDeclaration(node);
89329                 case 259 /* ExportAssignment */:
89330                     return visitExportAssignment(node);
89331                 case 225 /* VariableStatement */:
89332                     return visitVariableStatement(node);
89333                 case 244 /* FunctionDeclaration */:
89334                     return visitFunctionDeclaration(node);
89335                 case 245 /* ClassDeclaration */:
89336                     return visitClassDeclaration(node);
89337                 case 328 /* MergeDeclarationMarker */:
89338                     return visitMergeDeclarationMarker(node);
89339                 case 329 /* EndOfDeclarationMarker */:
89340                     return visitEndOfDeclarationMarker(node);
89341                 default:
89342                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89343             }
89344         }
89345         function moduleExpressionElementVisitor(node) {
89346             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
89347             // as export/import statements are only transformed at the top level of a file.
89348             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
89349                 return node;
89350             }
89351             if (ts.isImportCall(node)) {
89352                 return visitImportCallExpression(node);
89353             }
89354             else if (ts.isDestructuringAssignment(node)) {
89355                 return visitDestructuringAssignment(node);
89356             }
89357             else {
89358                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89359             }
89360         }
89361         function destructuringNeedsFlattening(node) {
89362             if (ts.isObjectLiteralExpression(node)) {
89363                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
89364                     var elem = _a[_i];
89365                     switch (elem.kind) {
89366                         case 281 /* PropertyAssignment */:
89367                             if (destructuringNeedsFlattening(elem.initializer)) {
89368                                 return true;
89369                             }
89370                             break;
89371                         case 282 /* ShorthandPropertyAssignment */:
89372                             if (destructuringNeedsFlattening(elem.name)) {
89373                                 return true;
89374                             }
89375                             break;
89376                         case 283 /* SpreadAssignment */:
89377                             if (destructuringNeedsFlattening(elem.expression)) {
89378                                 return true;
89379                             }
89380                             break;
89381                         case 161 /* MethodDeclaration */:
89382                         case 163 /* GetAccessor */:
89383                         case 164 /* SetAccessor */:
89384                             return false;
89385                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
89386                     }
89387                 }
89388             }
89389             else if (ts.isArrayLiteralExpression(node)) {
89390                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
89391                     var elem = _c[_b];
89392                     if (ts.isSpreadElement(elem)) {
89393                         if (destructuringNeedsFlattening(elem.expression)) {
89394                             return true;
89395                         }
89396                     }
89397                     else if (destructuringNeedsFlattening(elem)) {
89398                         return true;
89399                     }
89400                 }
89401             }
89402             else if (ts.isIdentifier(node)) {
89403                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
89404             }
89405             return false;
89406         }
89407         function visitDestructuringAssignment(node) {
89408             if (destructuringNeedsFlattening(node.left)) {
89409                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
89410             }
89411             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
89412         }
89413         function visitImportCallExpression(node) {
89414             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
89415             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
89416             switch (compilerOptions.module) {
89417                 case ts.ModuleKind.AMD:
89418                     return createImportCallExpressionAMD(argument, containsLexicalThis);
89419                 case ts.ModuleKind.UMD:
89420                     return createImportCallExpressionUMD(argument, containsLexicalThis);
89421                 case ts.ModuleKind.CommonJS:
89422                 default:
89423                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
89424             }
89425         }
89426         function createImportCallExpressionUMD(arg, containsLexicalThis) {
89427             // (function (factory) {
89428             //      ... (regular UMD)
89429             // }
89430             // })(function (require, exports, useSyncRequire) {
89431             //      "use strict";
89432             //      Object.defineProperty(exports, "__esModule", { value: true });
89433             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
89434             //      var __resolved = new Promise(function (resolve) { resolve(); });
89435             //      .....
89436             //      __syncRequire
89437             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
89438             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89439             // });
89440             needUMDDynamicImportHelper = true;
89441             if (ts.isSimpleCopiableExpression(arg)) {
89442                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? ts.createLiteral(arg) : ts.setEmitFlags(ts.setTextRange(ts.getSynthesizedClone(arg), arg), 1536 /* NoComments */);
89443                 return ts.createConditional(
89444                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89445                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
89446                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
89447             }
89448             else {
89449                 var temp = ts.createTempVariable(hoistVariableDeclaration);
89450                 return ts.createComma(ts.createAssignment(temp, arg), ts.createConditional(
89451                 /*condition*/ ts.createIdentifier("__syncRequire"), 
89452                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
89453                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
89454             }
89455         }
89456         function createImportCallExpressionAMD(arg, containsLexicalThis) {
89457             // improt("./blah")
89458             // emit as
89459             // define(["require", "exports", "blah"], function (require, exports) {
89460             //     ...
89461             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
89462             // });
89463             var resolve = ts.createUniqueName("resolve");
89464             var reject = ts.createUniqueName("reject");
89465             var parameters = [
89466                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
89467                 ts.createParameter(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
89468             ];
89469             var body = ts.createBlock([
89470                 ts.createExpressionStatement(ts.createCall(ts.createIdentifier("require"), 
89471                 /*typeArguments*/ undefined, [ts.createArrayLiteral([arg || ts.createOmittedExpression()]), resolve, reject]))
89472             ]);
89473             var func;
89474             if (languageVersion >= 2 /* ES2015 */) {
89475                 func = ts.createArrowFunction(
89476                 /*modifiers*/ undefined, 
89477                 /*typeParameters*/ undefined, parameters, 
89478                 /*type*/ undefined, 
89479                 /*equalsGreaterThanToken*/ undefined, body);
89480             }
89481             else {
89482                 func = ts.createFunctionExpression(
89483                 /*modifiers*/ undefined, 
89484                 /*asteriskToken*/ undefined, 
89485                 /*name*/ undefined, 
89486                 /*typeParameters*/ undefined, parameters, 
89487                 /*type*/ undefined, body);
89488                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89489                 // that this new function expression indicates it captures 'this' so that the
89490                 // es2015 transformer will properly substitute 'this' with '_this'.
89491                 if (containsLexicalThis) {
89492                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89493                 }
89494             }
89495             var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
89496             if (compilerOptions.esModuleInterop) {
89497                 context.requestEmitHelper(ts.importStarHelper);
89498                 return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getUnscopedHelperName("__importStar")]);
89499             }
89500             return promise;
89501         }
89502         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
89503             // import("./blah")
89504             // emit as
89505             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
89506             // We have to wrap require in then callback so that require is done in asynchronously
89507             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
89508             var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
89509             var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
89510             if (compilerOptions.esModuleInterop) {
89511                 context.requestEmitHelper(ts.importStarHelper);
89512                 requireCall = ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]);
89513             }
89514             var func;
89515             if (languageVersion >= 2 /* ES2015 */) {
89516                 func = ts.createArrowFunction(
89517                 /*modifiers*/ undefined, 
89518                 /*typeParameters*/ undefined, 
89519                 /*parameters*/ [], 
89520                 /*type*/ undefined, 
89521                 /*equalsGreaterThanToken*/ undefined, requireCall);
89522             }
89523             else {
89524                 func = ts.createFunctionExpression(
89525                 /*modifiers*/ undefined, 
89526                 /*asteriskToken*/ undefined, 
89527                 /*name*/ undefined, 
89528                 /*typeParameters*/ undefined, 
89529                 /*parameters*/ [], 
89530                 /*type*/ undefined, ts.createBlock([ts.createReturn(requireCall)]));
89531                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
89532                 // that this new function expression indicates it captures 'this' so that the
89533                 // es2015 transformer will properly substitute 'this' with '_this'.
89534                 if (containsLexicalThis) {
89535                     ts.setEmitFlags(func, 8 /* CapturesThis */);
89536                 }
89537             }
89538             return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
89539         }
89540         function getHelperExpressionForExport(node, innerExpr) {
89541             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89542                 return innerExpr;
89543             }
89544             if (ts.getExportNeedsImportStarHelper(node)) {
89545                 context.requestEmitHelper(ts.importStarHelper);
89546                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89547             }
89548             return innerExpr;
89549         }
89550         function getHelperExpressionForImport(node, innerExpr) {
89551             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
89552                 return innerExpr;
89553             }
89554             if (ts.getImportNeedsImportStarHelper(node)) {
89555                 context.requestEmitHelper(ts.importStarHelper);
89556                 return ts.createCall(ts.getUnscopedHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]);
89557             }
89558             if (ts.getImportNeedsImportDefaultHelper(node)) {
89559                 context.requestEmitHelper(ts.importDefaultHelper);
89560                 return ts.createCall(ts.getUnscopedHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]);
89561             }
89562             return innerExpr;
89563         }
89564         /**
89565          * Visits an ImportDeclaration node.
89566          *
89567          * @param node The node to visit.
89568          */
89569         function visitImportDeclaration(node) {
89570             var statements;
89571             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
89572             if (moduleKind !== ts.ModuleKind.AMD) {
89573                 if (!node.importClause) {
89574                     // import "mod";
89575                     return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createRequireCall(node)), node), node);
89576                 }
89577                 else {
89578                     var variables = [];
89579                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
89580                         // import * as n from "mod";
89581                         variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89582                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89583                     }
89584                     else {
89585                         // import d from "mod";
89586                         // import { x, y } from "mod";
89587                         // import d, { x, y } from "mod";
89588                         // import d, * as n from "mod";
89589                         variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), 
89590                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
89591                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
89592                             variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89593                             /*type*/ undefined, ts.getGeneratedNameForNode(node)));
89594                         }
89595                     }
89596                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89597                     /*modifiers*/ undefined, ts.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
89598                     /*location*/ node), 
89599                     /*original*/ node));
89600                 }
89601             }
89602             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
89603                 // import d, * as n from "mod";
89604                 statements = ts.append(statements, ts.createVariableStatement(
89605                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
89606                     ts.setOriginalNode(ts.setTextRange(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), 
89607                     /*type*/ undefined, ts.getGeneratedNameForNode(node)), 
89608                     /*location*/ node), 
89609                     /*original*/ node)
89610                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
89611             }
89612             if (hasAssociatedEndOfDeclarationMarker(node)) {
89613                 // Defer exports until we encounter an EndOfDeclarationMarker node
89614                 var id = ts.getOriginalNodeId(node);
89615                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
89616             }
89617             else {
89618                 statements = appendExportsOfImportDeclaration(statements, node);
89619             }
89620             return ts.singleOrMany(statements);
89621         }
89622         /**
89623          * Creates a `require()` call to import an external module.
89624          *
89625          * @param importNode The declararation to import.
89626          */
89627         function createRequireCall(importNode) {
89628             var moduleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions);
89629             var args = [];
89630             if (moduleName) {
89631                 args.push(moduleName);
89632             }
89633             return ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, args);
89634         }
89635         /**
89636          * Visits an ImportEqualsDeclaration node.
89637          *
89638          * @param node The node to visit.
89639          */
89640         function visitImportEqualsDeclaration(node) {
89641             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
89642             var statements;
89643             if (moduleKind !== ts.ModuleKind.AMD) {
89644                 if (ts.hasModifier(node, 1 /* Export */)) {
89645                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
89646                 }
89647                 else {
89648                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89649                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89650                         ts.createVariableDeclaration(ts.getSynthesizedClone(node.name), 
89651                         /*type*/ undefined, createRequireCall(node))
89652                     ], 
89653                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
89654                 }
89655             }
89656             else {
89657                 if (ts.hasModifier(node, 1 /* Export */)) {
89658                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(node), ts.getLocalName(node))), node), node));
89659                 }
89660             }
89661             if (hasAssociatedEndOfDeclarationMarker(node)) {
89662                 // Defer exports until we encounter an EndOfDeclarationMarker node
89663                 var id = ts.getOriginalNodeId(node);
89664                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
89665             }
89666             else {
89667                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
89668             }
89669             return ts.singleOrMany(statements);
89670         }
89671         /**
89672          * Visits an ExportDeclaration node.
89673          *
89674          * @param The node to visit.
89675          */
89676         function visitExportDeclaration(node) {
89677             if (!node.moduleSpecifier) {
89678                 // Elide export declarations with no module specifier as they are handled
89679                 // elsewhere.
89680                 return undefined;
89681             }
89682             var generatedName = ts.getGeneratedNameForNode(node);
89683             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
89684                 var statements = [];
89685                 // export { x, y } from "mod";
89686                 if (moduleKind !== ts.ModuleKind.AMD) {
89687                     statements.push(ts.setOriginalNode(ts.setTextRange(ts.createVariableStatement(
89688                     /*modifiers*/ undefined, ts.createVariableDeclarationList([
89689                         ts.createVariableDeclaration(generatedName, 
89690                         /*type*/ undefined, createRequireCall(node))
89691                     ])), 
89692                     /*location*/ node), 
89693                     /* original */ node));
89694                 }
89695                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
89696                     var specifier = _a[_i];
89697                     if (languageVersion === 0 /* ES3 */) {
89698                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createCreateBindingHelper(context, generatedName, ts.createLiteral(specifier.propertyName || specifier.name), specifier.propertyName ? ts.createLiteral(specifier.name) : undefined)), specifier), specifier));
89699                     }
89700                     else {
89701                         var exportedValue = ts.createPropertyAccess(generatedName, specifier.propertyName || specifier.name);
89702                         statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
89703                     }
89704                 }
89705                 return ts.singleOrMany(statements);
89706             }
89707             else if (node.exportClause) {
89708                 var statements = [];
89709                 // export * as ns from "mod";
89710                 statements.push(ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportExpression(ts.getSynthesizedClone(node.exportClause.name), moduleKind !== ts.ModuleKind.AMD ?
89711                     getHelperExpressionForExport(node, createRequireCall(node)) :
89712                     ts.createIdentifier(ts.idText(node.exportClause.name)))), node), node));
89713                 return ts.singleOrMany(statements);
89714             }
89715             else {
89716                 // export * from "mod";
89717                 return ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(createExportStarHelper(context, moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
89718             }
89719         }
89720         /**
89721          * Visits an ExportAssignment node.
89722          *
89723          * @param node The node to visit.
89724          */
89725         function visitExportAssignment(node) {
89726             if (node.isExportEquals) {
89727                 return undefined;
89728             }
89729             var statements;
89730             var original = node.original;
89731             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
89732                 // Defer exports until we encounter an EndOfDeclarationMarker node
89733                 var id = ts.getOriginalNodeId(node);
89734                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89735             }
89736             else {
89737                 statements = appendExportStatement(statements, ts.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
89738             }
89739             return ts.singleOrMany(statements);
89740         }
89741         /**
89742          * Visits a FunctionDeclaration node.
89743          *
89744          * @param node The node to visit.
89745          */
89746         function visitFunctionDeclaration(node) {
89747             var statements;
89748             if (ts.hasModifier(node, 1 /* Export */)) {
89749                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createFunctionDeclaration(
89750                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89751                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
89752                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
89753                 /*location*/ node), 
89754                 /*original*/ node));
89755             }
89756             else {
89757                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89758             }
89759             if (hasAssociatedEndOfDeclarationMarker(node)) {
89760                 // Defer exports until we encounter an EndOfDeclarationMarker node
89761                 var id = ts.getOriginalNodeId(node);
89762                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89763             }
89764             else {
89765                 statements = appendExportsOfHoistedDeclaration(statements, node);
89766             }
89767             return ts.singleOrMany(statements);
89768         }
89769         /**
89770          * Visits a ClassDeclaration node.
89771          *
89772          * @param node The node to visit.
89773          */
89774         function visitClassDeclaration(node) {
89775             var statements;
89776             if (ts.hasModifier(node, 1 /* Export */)) {
89777                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createClassDeclaration(
89778                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
89779                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
89780             }
89781             else {
89782                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89783             }
89784             if (hasAssociatedEndOfDeclarationMarker(node)) {
89785                 // Defer exports until we encounter an EndOfDeclarationMarker node
89786                 var id = ts.getOriginalNodeId(node);
89787                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
89788             }
89789             else {
89790                 statements = appendExportsOfHoistedDeclaration(statements, node);
89791             }
89792             return ts.singleOrMany(statements);
89793         }
89794         /**
89795          * Visits a VariableStatement node.
89796          *
89797          * @param node The node to visit.
89798          */
89799         function visitVariableStatement(node) {
89800             var statements;
89801             var variables;
89802             var expressions;
89803             if (ts.hasModifier(node, 1 /* Export */)) {
89804                 var modifiers = void 0;
89805                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
89806                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89807                     var variable = _a[_i];
89808                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
89809                         if (!modifiers) {
89810                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
89811                         }
89812                         variables = ts.append(variables, variable);
89813                     }
89814                     else if (variable.initializer) {
89815                         expressions = ts.append(expressions, transformInitializedVariable(variable));
89816                     }
89817                 }
89818                 if (variables) {
89819                     statements = ts.append(statements, ts.updateVariableStatement(node, modifiers, ts.updateVariableDeclarationList(node.declarationList, variables)));
89820                 }
89821                 if (expressions) {
89822                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node), node));
89823                 }
89824             }
89825             else {
89826                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
89827             }
89828             if (hasAssociatedEndOfDeclarationMarker(node)) {
89829                 // Defer exports until we encounter an EndOfDeclarationMarker node
89830                 var id = ts.getOriginalNodeId(node);
89831                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
89832             }
89833             else {
89834                 statements = appendExportsOfVariableStatement(statements, node);
89835             }
89836             return ts.singleOrMany(statements);
89837         }
89838         function createAllExportExpressions(name, value, location) {
89839             var exportedNames = getExports(name);
89840             if (exportedNames) {
89841                 // For each additional export of the declaration, apply an export assignment.
89842                 var expression = ts.isExportName(name) ? value : ts.createAssignment(name, value);
89843                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
89844                     var exportName = exportedNames_1[_i];
89845                     // Mark the node to prevent triggering substitution.
89846                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
89847                     expression = createExportExpression(exportName, expression, /*location*/ location);
89848                 }
89849                 return expression;
89850             }
89851             return ts.createAssignment(name, value);
89852         }
89853         /**
89854          * Transforms an exported variable with an initializer into an expression.
89855          *
89856          * @param node The node to transform.
89857          */
89858         function transformInitializedVariable(node) {
89859             if (ts.isBindingPattern(node.name)) {
89860                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
89861                 /*visitor*/ undefined, context, 0 /* All */, 
89862                 /*needsValue*/ false, createAllExportExpressions);
89863             }
89864             else {
89865                 return ts.createAssignment(ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), node.name), 
89866                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : ts.createVoidZero());
89867             }
89868         }
89869         /**
89870          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
89871          * and transformed declaration.
89872          *
89873          * @param node The node to visit.
89874          */
89875         function visitMergeDeclarationMarker(node) {
89876             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
89877             // declaration we do not emit a leading variable declaration. To preserve the
89878             // begin/end semantics of the declararation and to properly handle exports
89879             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
89880             //
89881             // To balance the declaration, add the exports of the elided variable
89882             // statement.
89883             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
89884                 var id = ts.getOriginalNodeId(node);
89885                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
89886             }
89887             return node;
89888         }
89889         /**
89890          * Determines whether a node has an associated EndOfDeclarationMarker.
89891          *
89892          * @param node The node to test.
89893          */
89894         function hasAssociatedEndOfDeclarationMarker(node) {
89895             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
89896         }
89897         /**
89898          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
89899          * declaration.
89900          *
89901          * @param node The node to visit.
89902          */
89903         function visitEndOfDeclarationMarker(node) {
89904             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
89905             // end of the transformed declaration. We use this marker to emit any deferred exports
89906             // of the declaration.
89907             var id = ts.getOriginalNodeId(node);
89908             var statements = deferredExports[id];
89909             if (statements) {
89910                 delete deferredExports[id];
89911                 return ts.append(statements, node);
89912             }
89913             return node;
89914         }
89915         /**
89916          * Appends the exports of an ImportDeclaration to a statement list, returning the
89917          * statement list.
89918          *
89919          * @param statements A statement list to which the down-level export statements are to be
89920          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89921          * appended.
89922          * @param decl The declaration whose exports are to be recorded.
89923          */
89924         function appendExportsOfImportDeclaration(statements, decl) {
89925             if (currentModuleInfo.exportEquals) {
89926                 return statements;
89927             }
89928             var importClause = decl.importClause;
89929             if (!importClause) {
89930                 return statements;
89931             }
89932             if (importClause.name) {
89933                 statements = appendExportsOfDeclaration(statements, importClause);
89934             }
89935             var namedBindings = importClause.namedBindings;
89936             if (namedBindings) {
89937                 switch (namedBindings.kind) {
89938                     case 256 /* NamespaceImport */:
89939                         statements = appendExportsOfDeclaration(statements, namedBindings);
89940                         break;
89941                     case 257 /* NamedImports */:
89942                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
89943                             var importBinding = _a[_i];
89944                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
89945                         }
89946                         break;
89947                 }
89948             }
89949             return statements;
89950         }
89951         /**
89952          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
89953          * statement list.
89954          *
89955          * @param statements A statement list to which the down-level export statements are to be
89956          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89957          * appended.
89958          * @param decl The declaration whose exports are to be recorded.
89959          */
89960         function appendExportsOfImportEqualsDeclaration(statements, decl) {
89961             if (currentModuleInfo.exportEquals) {
89962                 return statements;
89963             }
89964             return appendExportsOfDeclaration(statements, decl);
89965         }
89966         /**
89967          * Appends the exports of a VariableStatement to a statement list, returning the statement
89968          * list.
89969          *
89970          * @param statements A statement list to which the down-level export statements are to be
89971          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89972          * appended.
89973          * @param node The VariableStatement whose exports are to be recorded.
89974          */
89975         function appendExportsOfVariableStatement(statements, node) {
89976             if (currentModuleInfo.exportEquals) {
89977                 return statements;
89978             }
89979             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89980                 var decl = _a[_i];
89981                 statements = appendExportsOfBindingElement(statements, decl);
89982             }
89983             return statements;
89984         }
89985         /**
89986          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
89987          * returning the statement list.
89988          *
89989          * @param statements A statement list to which the down-level export statements are to be
89990          * appended. If `statements` is `undefined`, a new array is allocated if statements are
89991          * appended.
89992          * @param decl The declaration whose exports are to be recorded.
89993          */
89994         function appendExportsOfBindingElement(statements, decl) {
89995             if (currentModuleInfo.exportEquals) {
89996                 return statements;
89997             }
89998             if (ts.isBindingPattern(decl.name)) {
89999                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
90000                     var element = _a[_i];
90001                     if (!ts.isOmittedExpression(element)) {
90002                         statements = appendExportsOfBindingElement(statements, element);
90003                     }
90004                 }
90005             }
90006             else if (!ts.isGeneratedIdentifier(decl.name)) {
90007                 statements = appendExportsOfDeclaration(statements, decl);
90008             }
90009             return statements;
90010         }
90011         /**
90012          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
90013          * returning the statement list.
90014          *
90015          * @param statements A statement list to which the down-level export statements are to be
90016          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90017          * appended.
90018          * @param decl The declaration whose exports are to be recorded.
90019          */
90020         function appendExportsOfHoistedDeclaration(statements, decl) {
90021             if (currentModuleInfo.exportEquals) {
90022                 return statements;
90023             }
90024             if (ts.hasModifier(decl, 1 /* Export */)) {
90025                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createIdentifier("default") : ts.getDeclarationName(decl);
90026                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl), /*location*/ decl);
90027             }
90028             if (decl.name) {
90029                 statements = appendExportsOfDeclaration(statements, decl);
90030             }
90031             return statements;
90032         }
90033         /**
90034          * Appends the exports of a declaration to a statement list, returning the statement list.
90035          *
90036          * @param statements A statement list to which the down-level export statements are to be
90037          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90038          * appended.
90039          * @param decl The declaration to export.
90040          */
90041         function appendExportsOfDeclaration(statements, decl, liveBinding) {
90042             var name = ts.getDeclarationName(decl);
90043             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
90044             if (exportSpecifiers) {
90045                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
90046                     var exportSpecifier = exportSpecifiers_1[_i];
90047                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
90048                 }
90049             }
90050             return statements;
90051         }
90052         /**
90053          * Appends the down-level representation of an export to a statement list, returning the
90054          * statement list.
90055          *
90056          * @param statements A statement list to which the down-level export statements are to be
90057          * appended. If `statements` is `undefined`, a new array is allocated if statements are
90058          * appended.
90059          * @param exportName The name of the export.
90060          * @param expression The expression to export.
90061          * @param location The location to use for source maps and comments for the export.
90062          * @param allowComments Whether to allow comments on the export.
90063          */
90064         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
90065             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
90066             return statements;
90067         }
90068         function createUnderscoreUnderscoreESModule() {
90069             var statement;
90070             if (languageVersion === 0 /* ES3 */) {
90071                 statement = ts.createExpressionStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(/*value*/ true)));
90072             }
90073             else {
90074                 statement = ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90075                 /*typeArguments*/ undefined, [
90076                     ts.createIdentifier("exports"),
90077                     ts.createLiteral("__esModule"),
90078                     ts.createObjectLiteral([
90079                         ts.createPropertyAssignment("value", ts.createLiteral(/*value*/ true))
90080                     ])
90081                 ]));
90082             }
90083             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
90084             return statement;
90085         }
90086         /**
90087          * Creates a call to the current file's export function to export a value.
90088          *
90089          * @param name The bound name of the export.
90090          * @param value The exported value.
90091          * @param location The location to use for source maps and comments for the export.
90092          * @param allowComments An optional value indicating whether to emit comments for the statement.
90093          */
90094         function createExportStatement(name, value, location, allowComments, liveBinding) {
90095             var statement = ts.setTextRange(ts.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
90096             ts.startOnNewLine(statement);
90097             if (!allowComments) {
90098                 ts.setEmitFlags(statement, 1536 /* NoComments */);
90099             }
90100             return statement;
90101         }
90102         /**
90103          * Creates a call to the current file's export function to export a value.
90104          *
90105          * @param name The bound name of the export.
90106          * @param value The exported value.
90107          * @param location The location to use for source maps and comments for the export.
90108          */
90109         function createExportExpression(name, value, location, liveBinding) {
90110             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), 
90111             /*typeArguments*/ undefined, [
90112                 ts.createIdentifier("exports"),
90113                 ts.createLiteral(name),
90114                 ts.createObjectLiteral([
90115                     ts.createPropertyAssignment("enumerable", ts.createLiteral(/*value*/ true)),
90116                     ts.createPropertyAssignment("get", ts.createFunctionExpression(
90117                     /*modifiers*/ undefined, 
90118                     /*asteriskToken*/ undefined, 
90119                     /*name*/ undefined, 
90120                     /*typeParameters*/ undefined, 
90121                     /*parameters*/ [], 
90122                     /*type*/ undefined, ts.createBlock([ts.createReturn(value)])))
90123                 ])
90124             ]) : ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(name)), value), location);
90125         }
90126         //
90127         // Modifier Visitors
90128         //
90129         /**
90130          * Visit nodes to elide module-specific modifiers.
90131          *
90132          * @param node The node to visit.
90133          */
90134         function modifierVisitor(node) {
90135             // Elide module-specific modifiers.
90136             switch (node.kind) {
90137                 case 89 /* ExportKeyword */:
90138                 case 84 /* DefaultKeyword */:
90139                     return undefined;
90140             }
90141             return node;
90142         }
90143         //
90144         // Emit Notification
90145         //
90146         /**
90147          * Hook for node emit notifications.
90148          *
90149          * @param hint A hint as to the intended usage of the node.
90150          * @param node The node to emit.
90151          * @param emit A callback used to emit the node in the printer.
90152          */
90153         function onEmitNode(hint, node, emitCallback) {
90154             if (node.kind === 290 /* SourceFile */) {
90155                 currentSourceFile = node;
90156                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
90157                 noSubstitution = [];
90158                 previousOnEmitNode(hint, node, emitCallback);
90159                 currentSourceFile = undefined;
90160                 currentModuleInfo = undefined;
90161                 noSubstitution = undefined;
90162             }
90163             else {
90164                 previousOnEmitNode(hint, node, emitCallback);
90165             }
90166         }
90167         //
90168         // Substitutions
90169         //
90170         /**
90171          * Hooks node substitutions.
90172          *
90173          * @param hint A hint as to the intended usage of the node.
90174          * @param node The node to substitute.
90175          */
90176         function onSubstituteNode(hint, node) {
90177             node = previousOnSubstituteNode(hint, node);
90178             if (node.id && noSubstitution[node.id]) {
90179                 return node;
90180             }
90181             if (hint === 1 /* Expression */) {
90182                 return substituteExpression(node);
90183             }
90184             else if (ts.isShorthandPropertyAssignment(node)) {
90185                 return substituteShorthandPropertyAssignment(node);
90186             }
90187             return node;
90188         }
90189         /**
90190          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
90191          * or exported symbol.
90192          *
90193          * @param node The node to substitute.
90194          */
90195         function substituteShorthandPropertyAssignment(node) {
90196             var name = node.name;
90197             var exportedOrImportedName = substituteExpressionIdentifier(name);
90198             if (exportedOrImportedName !== name) {
90199                 // A shorthand property with an assignment initializer is probably part of a
90200                 // destructuring assignment
90201                 if (node.objectAssignmentInitializer) {
90202                     var initializer = ts.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
90203                     return ts.setTextRange(ts.createPropertyAssignment(name, initializer), node);
90204                 }
90205                 return ts.setTextRange(ts.createPropertyAssignment(name, exportedOrImportedName), node);
90206             }
90207             return node;
90208         }
90209         /**
90210          * Substitution for an Expression that may contain an imported or exported symbol.
90211          *
90212          * @param node The node to substitute.
90213          */
90214         function substituteExpression(node) {
90215             switch (node.kind) {
90216                 case 75 /* Identifier */:
90217                     return substituteExpressionIdentifier(node);
90218                 case 209 /* BinaryExpression */:
90219                     return substituteBinaryExpression(node);
90220                 case 208 /* PostfixUnaryExpression */:
90221                 case 207 /* PrefixUnaryExpression */:
90222                     return substituteUnaryExpression(node);
90223             }
90224             return node;
90225         }
90226         /**
90227          * Substitution for an Identifier expression that may contain an imported or exported
90228          * symbol.
90229          *
90230          * @param node The node to substitute.
90231          */
90232         function substituteExpressionIdentifier(node) {
90233             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
90234                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
90235                 if (externalHelpersModuleName) {
90236                     return ts.createPropertyAccess(externalHelpersModuleName, node);
90237                 }
90238                 return node;
90239             }
90240             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
90241                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
90242                 if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
90243                     return ts.setTextRange(ts.createPropertyAccess(ts.createIdentifier("exports"), ts.getSynthesizedClone(node)), 
90244                     /*location*/ node);
90245                 }
90246                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
90247                 if (importDeclaration) {
90248                     if (ts.isImportClause(importDeclaration)) {
90249                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
90250                         /*location*/ node);
90251                     }
90252                     else if (ts.isImportSpecifier(importDeclaration)) {
90253                         var name = importDeclaration.propertyName || importDeclaration.name;
90254                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(name)), 
90255                         /*location*/ node);
90256                     }
90257                 }
90258             }
90259             return node;
90260         }
90261         /**
90262          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
90263          *
90264          * @param node The node to substitute.
90265          */
90266         function substituteBinaryExpression(node) {
90267             // When we see an assignment expression whose left-hand side is an exported symbol,
90268             // we should ensure all exports of that symbol are updated with the correct value.
90269             //
90270             // - We do not substitute generated identifiers for any reason.
90271             // - We do not substitute identifiers tagged with the LocalName flag.
90272             // - We do not substitute identifiers that were originally the name of an enum or
90273             //   namespace due to how they are transformed in TypeScript.
90274             // - We only substitute identifiers that are exported at the top level.
90275             if (ts.isAssignmentOperator(node.operatorToken.kind)
90276                 && ts.isIdentifier(node.left)
90277                 && !ts.isGeneratedIdentifier(node.left)
90278                 && !ts.isLocalName(node.left)
90279                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
90280                 var exportedNames = getExports(node.left);
90281                 if (exportedNames) {
90282                     // For each additional export of the declaration, apply an export assignment.
90283                     var expression = node;
90284                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
90285                         var exportName = exportedNames_2[_i];
90286                         // Mark the node to prevent triggering this rule again.
90287                         noSubstitution[ts.getNodeId(expression)] = true;
90288                         expression = createExportExpression(exportName, expression, /*location*/ node);
90289                     }
90290                     return expression;
90291                 }
90292             }
90293             return node;
90294         }
90295         /**
90296          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
90297          *
90298          * @param node The node to substitute.
90299          */
90300         function substituteUnaryExpression(node) {
90301             // When we see a prefix or postfix increment expression whose operand is an exported
90302             // symbol, we should ensure all exports of that symbol are updated with the correct
90303             // value.
90304             //
90305             // - We do not substitute generated identifiers for any reason.
90306             // - We do not substitute identifiers tagged with the LocalName flag.
90307             // - We do not substitute identifiers that were originally the name of an enum or
90308             //   namespace due to how they are transformed in TypeScript.
90309             // - We only substitute identifiers that are exported at the top level.
90310             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
90311                 && ts.isIdentifier(node.operand)
90312                 && !ts.isGeneratedIdentifier(node.operand)
90313                 && !ts.isLocalName(node.operand)
90314                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
90315                 var exportedNames = getExports(node.operand);
90316                 if (exportedNames) {
90317                     var expression = node.kind === 208 /* PostfixUnaryExpression */
90318                         ? ts.setTextRange(ts.createBinary(node.operand, ts.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), ts.createLiteral(1)), 
90319                         /*location*/ node)
90320                         : node;
90321                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
90322                         var exportName = exportedNames_3[_i];
90323                         // Mark the node to prevent triggering this rule again.
90324                         noSubstitution[ts.getNodeId(expression)] = true;
90325                         expression = createExportExpression(exportName, expression);
90326                     }
90327                     return expression;
90328                 }
90329             }
90330             return node;
90331         }
90332         /**
90333          * Gets the additional exports of a name.
90334          *
90335          * @param name The name.
90336          */
90337         function getExports(name) {
90338             if (!ts.isGeneratedIdentifier(name)) {
90339                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
90340                     || resolver.getReferencedValueDeclaration(name);
90341                 if (valueDeclaration) {
90342                     return currentModuleInfo
90343                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
90344                 }
90345             }
90346         }
90347     }
90348     ts.transformModule = transformModule;
90349     ts.createBindingHelper = {
90350         name: "typescript:commonjscreatebinding",
90351         importName: "__createBinding",
90352         scoped: false,
90353         priority: 1,
90354         text: "\nvar __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}));"
90355     };
90356     function createCreateBindingHelper(context, module, inputName, outputName) {
90357         context.requestEmitHelper(ts.createBindingHelper);
90358         return ts.createCall(ts.getUnscopedHelperName("__createBinding"), /*typeArguments*/ undefined, __spreadArrays([ts.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
90359     }
90360     ts.setModuleDefaultHelper = {
90361         name: "typescript:commonjscreatevalue",
90362         importName: "__setModuleDefault",
90363         scoped: false,
90364         priority: 1,
90365         text: "\nvar __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});"
90366     };
90367     // emit output for the __export helper function
90368     var exportStarHelper = {
90369         name: "typescript:export-star",
90370         importName: "__exportStar",
90371         scoped: false,
90372         dependencies: [ts.createBindingHelper],
90373         priority: 2,
90374         text: "\n            var __exportStar = (this && this.__exportStar) || function(m, exports) {\n                for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);\n            };"
90375     };
90376     function createExportStarHelper(context, module) {
90377         context.requestEmitHelper(exportStarHelper);
90378         return ts.createCall(ts.getUnscopedHelperName("__exportStar"), /*typeArguments*/ undefined, [module, ts.createIdentifier("exports")]);
90379     }
90380     // emit helper for dynamic import
90381     var dynamicImportUMDHelper = {
90382         name: "typescript:dynamicimport-sync-require",
90383         scoped: true,
90384         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
90385     };
90386     // emit helper for `import * as Name from "foo"`
90387     ts.importStarHelper = {
90388         name: "typescript:commonjsimportstar",
90389         importName: "__importStar",
90390         scoped: false,
90391         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
90392         priority: 2,
90393         text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n    if (mod && mod.__esModule) return mod;\n    var result = {};\n    if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n    __setModuleDefault(result, mod);\n    return result;\n};"
90394     };
90395     // emit helper for `import Name from "foo"`
90396     ts.importDefaultHelper = {
90397         name: "typescript:commonjsimportdefault",
90398         importName: "__importDefault",
90399         scoped: false,
90400         text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n    return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};"
90401     };
90402 })(ts || (ts = {}));
90403 /*@internal*/
90404 var ts;
90405 (function (ts) {
90406     function transformSystemModule(context) {
90407         var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
90408         var compilerOptions = context.getCompilerOptions();
90409         var resolver = context.getEmitResolver();
90410         var host = context.getEmitHost();
90411         var previousOnSubstituteNode = context.onSubstituteNode;
90412         var previousOnEmitNode = context.onEmitNode;
90413         context.onSubstituteNode = onSubstituteNode;
90414         context.onEmitNode = onEmitNode;
90415         context.enableSubstitution(75 /* Identifier */); // Substitutes expression identifiers for imported symbols.
90416         context.enableSubstitution(282 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
90417         context.enableSubstitution(209 /* BinaryExpression */); // Substitutes assignments to exported symbols.
90418         context.enableSubstitution(207 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
90419         context.enableSubstitution(208 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
90420         context.enableSubstitution(219 /* MetaProperty */); // Substitutes 'import.meta'
90421         context.enableEmitNotification(290 /* SourceFile */); // Restore state when substituting nodes in a file.
90422         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
90423         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
90424         var exportFunctionsMap = []; // The export function associated with a source file.
90425         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
90426         var contextObjectMap = []; // The context object associated with a source file.
90427         var currentSourceFile; // The current file.
90428         var moduleInfo; // ExternalModuleInfo for the current file.
90429         var exportFunction; // The export function for the current file.
90430         var contextObject; // The context object for the current file.
90431         var hoistedStatements;
90432         var enclosingBlockScopedContainer;
90433         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
90434         return ts.chainBundle(transformSourceFile);
90435         /**
90436          * Transforms the module aspects of a SourceFile.
90437          *
90438          * @param node The SourceFile node.
90439          */
90440         function transformSourceFile(node) {
90441             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
90442                 return node;
90443             }
90444             var id = ts.getOriginalNodeId(node);
90445             currentSourceFile = node;
90446             enclosingBlockScopedContainer = node;
90447             // System modules have the following shape:
90448             //
90449             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
90450             //
90451             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
90452             // is used to publish exported values. 'exports' returns its 'value' argument so in
90453             // most cases expressions that mutate exported values can be rewritten as:
90454             //
90455             //     expr -> exports('name', expr)
90456             //
90457             // The only exception in this rule is postfix unary operators,
90458             // see comment to 'substitutePostfixUnaryExpression' for more details
90459             // Collect information about the external module and dependency groups.
90460             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(node, resolver, compilerOptions);
90461             // Make sure that the name of the 'exports' function does not conflict with
90462             // existing identifiers.
90463             exportFunction = ts.createUniqueName("exports");
90464             exportFunctionsMap[id] = exportFunction;
90465             contextObject = contextObjectMap[id] = ts.createUniqueName("context");
90466             // Add the body of the module.
90467             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
90468             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
90469             var moduleBodyFunction = ts.createFunctionExpression(
90470             /*modifiers*/ undefined, 
90471             /*asteriskToken*/ undefined, 
90472             /*name*/ undefined, 
90473             /*typeParameters*/ undefined, [
90474                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
90475                 ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
90476             ], 
90477             /*type*/ undefined, moduleBodyBlock);
90478             // Write the call to `System.register`
90479             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
90480             // So the helper will be emit at the correct position instead of at the top of the source-file
90481             var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions);
90482             var dependencies = ts.createArrayLiteral(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
90483             var updated = ts.setEmitFlags(ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([
90484                 ts.createExpressionStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), 
90485                 /*typeArguments*/ undefined, moduleName
90486                     ? [moduleName, dependencies, moduleBodyFunction]
90487                     : [dependencies, moduleBodyFunction]))
90488             ]), node.statements)), 1024 /* NoTrailingComments */);
90489             if (!(compilerOptions.outFile || compilerOptions.out)) {
90490                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
90491             }
90492             if (noSubstitution) {
90493                 noSubstitutionMap[id] = noSubstitution;
90494                 noSubstitution = undefined;
90495             }
90496             currentSourceFile = undefined;
90497             moduleInfo = undefined;
90498             exportFunction = undefined;
90499             contextObject = undefined;
90500             hoistedStatements = undefined;
90501             enclosingBlockScopedContainer = undefined;
90502             return ts.aggregateTransformFlags(updated);
90503         }
90504         /**
90505          * Collects the dependency groups for this files imports.
90506          *
90507          * @param externalImports The imports for the file.
90508          */
90509         function collectDependencyGroups(externalImports) {
90510             var groupIndices = ts.createMap();
90511             var dependencyGroups = [];
90512             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
90513                 var externalImport = externalImports_1[_i];
90514                 var externalModuleName = ts.getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
90515                 if (externalModuleName) {
90516                     var text = externalModuleName.text;
90517                     var groupIndex = groupIndices.get(text);
90518                     if (groupIndex !== undefined) {
90519                         // deduplicate/group entries in dependency list by the dependency name
90520                         dependencyGroups[groupIndex].externalImports.push(externalImport);
90521                     }
90522                     else {
90523                         groupIndices.set(text, dependencyGroups.length);
90524                         dependencyGroups.push({
90525                             name: externalModuleName,
90526                             externalImports: [externalImport]
90527                         });
90528                     }
90529                 }
90530             }
90531             return dependencyGroups;
90532         }
90533         /**
90534          * Adds the statements for the module body function for the source file.
90535          *
90536          * @param node The source file for the module.
90537          * @param dependencyGroups The grouped dependencies of the module.
90538          */
90539         function createSystemModuleBody(node, dependencyGroups) {
90540             // Shape of the body in system modules:
90541             //
90542             //  function (exports) {
90543             //      <list of local aliases for imports>
90544             //      <hoisted variable declarations>
90545             //      <hoisted function declarations>
90546             //      return {
90547             //          setters: [
90548             //              <list of setter function for imports>
90549             //          ],
90550             //          execute: function() {
90551             //              <module statements>
90552             //          }
90553             //      }
90554             //      <temp declarations>
90555             //  }
90556             //
90557             // i.e:
90558             //
90559             //   import {x} from 'file1'
90560             //   var y = 1;
90561             //   export function foo() { return y + x(); }
90562             //   console.log(y);
90563             //
90564             // Will be transformed to:
90565             //
90566             //  function(exports) {
90567             //      function foo() { return y + file_1.x(); }
90568             //      exports("foo", foo);
90569             //      var file_1, y;
90570             //      return {
90571             //          setters: [
90572             //              function(v) { file_1 = v }
90573             //          ],
90574             //          execute(): function() {
90575             //              y = 1;
90576             //              console.log(y);
90577             //          }
90578             //      };
90579             //  }
90580             var statements = [];
90581             // We start a new lexical environment in this function body, but *not* in the
90582             // body of the execute function. This allows us to emit temporary declarations
90583             // only in the outer module body and not in the inner one.
90584             startLexicalEnvironment();
90585             // Add any prologue directives.
90586             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
90587             var statementOffset = ts.addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
90588             // var __moduleName = context_1 && context_1.id;
90589             statements.push(ts.createVariableStatement(
90590             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90591                 ts.createVariableDeclaration("__moduleName", 
90592                 /*type*/ undefined, ts.createLogicalAnd(contextObject, ts.createPropertyAccess(contextObject, "id")))
90593             ])));
90594             // Visit the synthetic external helpers import declaration if present
90595             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
90596             // Visit the statements of the source file, emitting any transformations into
90597             // the `executeStatements` array. We do this *before* we fill the `setters` array
90598             // as we both emit transformations as well as aggregate some data used when creating
90599             // setters. This allows us to reduce the number of times we need to loop through the
90600             // statements of the source file.
90601             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
90602             // Emit early exports for function declarations.
90603             ts.addRange(statements, hoistedStatements);
90604             // We emit hoisted variables early to align roughly with our previous emit output.
90605             // Two key differences in this approach are:
90606             // - Temporary variables will appear at the top rather than at the bottom of the file
90607             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
90608             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
90609             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
90610                 ts.createModifiersFromModifierFlags(256 /* Async */) :
90611                 undefined;
90612             var moduleObject = ts.createObjectLiteral([
90613                 ts.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
90614                 ts.createPropertyAssignment("execute", ts.createFunctionExpression(modifiers, 
90615                 /*asteriskToken*/ undefined, 
90616                 /*name*/ undefined, 
90617                 /*typeParameters*/ undefined, 
90618                 /*parameters*/ [], 
90619                 /*type*/ undefined, ts.createBlock(executeStatements, /*multiLine*/ true)))
90620             ]);
90621             moduleObject.multiLine = true;
90622             statements.push(ts.createReturn(moduleObject));
90623             return ts.createBlock(statements, /*multiLine*/ true);
90624         }
90625         /**
90626          * Adds an exportStar function to a statement list if it is needed for the file.
90627          *
90628          * @param statements A statement list.
90629          */
90630         function addExportStarIfNeeded(statements) {
90631             if (!moduleInfo.hasExportStarsToExportValues) {
90632                 return;
90633             }
90634             // when resolving exports local exported entries/indirect exported entries in the module
90635             // should always win over entries with similar names that were added via star exports
90636             // to support this we store names of local/indirect exported entries in a set.
90637             // this set is used to filter names brought by star expors.
90638             // local names set should only be added if we have anything exported
90639             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
90640                 // no exported declarations (export var ...) or export specifiers (export {x})
90641                 // check if we have any non star export declarations.
90642                 var hasExportDeclarationWithExportClause = false;
90643                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
90644                     var externalImport = _a[_i];
90645                     if (externalImport.kind === 260 /* ExportDeclaration */ && externalImport.exportClause) {
90646                         hasExportDeclarationWithExportClause = true;
90647                         break;
90648                     }
90649                 }
90650                 if (!hasExportDeclarationWithExportClause) {
90651                     // we still need to emit exportStar helper
90652                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
90653                     statements.push(exportStarFunction_1);
90654                     return exportStarFunction_1.name;
90655                 }
90656             }
90657             var exportedNames = [];
90658             if (moduleInfo.exportedNames) {
90659                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
90660                     var exportedLocalName = _c[_b];
90661                     if (exportedLocalName.escapedText === "default") {
90662                         continue;
90663                     }
90664                     // write name of exported declaration, i.e 'export var x...'
90665                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(exportedLocalName), ts.createTrue()));
90666                 }
90667             }
90668             for (var _d = 0, _e = moduleInfo.externalImports; _d < _e.length; _d++) {
90669                 var externalImport = _e[_d];
90670                 if (externalImport.kind !== 260 /* ExportDeclaration */) {
90671                     continue;
90672                 }
90673                 if (!externalImport.exportClause) {
90674                     // export * from ...
90675                     continue;
90676                 }
90677                 if (ts.isNamedExports(externalImport.exportClause)) {
90678                     for (var _f = 0, _g = externalImport.exportClause.elements; _f < _g.length; _f++) {
90679                         var element = _g[_f];
90680                         // write name of indirectly exported entry, i.e. 'export {x} from ...'
90681                         exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(element.name || element.propertyName)), ts.createTrue()));
90682                     }
90683                 }
90684                 else {
90685                     exportedNames.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(externalImport.exportClause.name)), ts.createTrue()));
90686                 }
90687             }
90688             var exportedNamesStorageRef = ts.createUniqueName("exportedNames");
90689             statements.push(ts.createVariableStatement(
90690             /*modifiers*/ undefined, ts.createVariableDeclarationList([
90691                 ts.createVariableDeclaration(exportedNamesStorageRef, 
90692                 /*type*/ undefined, ts.createObjectLiteral(exportedNames, /*multiline*/ true))
90693             ])));
90694             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
90695             statements.push(exportStarFunction);
90696             return exportStarFunction.name;
90697         }
90698         /**
90699          * Creates an exportStar function for the file, with an optional set of excluded local
90700          * names.
90701          *
90702          * @param localNames An optional reference to an object containing a set of excluded local
90703          * names.
90704          */
90705         function createExportStarFunction(localNames) {
90706             var exportStarFunction = ts.createUniqueName("exportStar");
90707             var m = ts.createIdentifier("m");
90708             var n = ts.createIdentifier("n");
90709             var exports = ts.createIdentifier("exports");
90710             var condition = ts.createStrictInequality(n, ts.createLiteral("default"));
90711             if (localNames) {
90712                 condition = ts.createLogicalAnd(condition, ts.createLogicalNot(ts.createCall(ts.createPropertyAccess(localNames, "hasOwnProperty"), 
90713                 /*typeArguments*/ undefined, [n])));
90714             }
90715             return ts.createFunctionDeclaration(
90716             /*decorators*/ undefined, 
90717             /*modifiers*/ undefined, 
90718             /*asteriskToken*/ undefined, exportStarFunction, 
90719             /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
90720             /*type*/ undefined, ts.createBlock([
90721                 ts.createVariableStatement(
90722                 /*modifiers*/ undefined, ts.createVariableDeclarationList([
90723                     ts.createVariableDeclaration(exports, 
90724                     /*type*/ undefined, ts.createObjectLiteral([]))
90725                 ])),
90726                 ts.createForIn(ts.createVariableDeclarationList([
90727                     ts.createVariableDeclaration(n, /*type*/ undefined)
90728                 ]), m, ts.createBlock([
90729                     ts.setEmitFlags(ts.createIf(condition, ts.createExpressionStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 1 /* SingleLine */)
90730                 ])),
90731                 ts.createExpressionStatement(ts.createCall(exportFunction, 
90732                 /*typeArguments*/ undefined, [exports]))
90733             ], /*multiline*/ true));
90734         }
90735         /**
90736          * Creates an array setter callbacks for each dependency group.
90737          *
90738          * @param exportStarFunction A reference to an exportStarFunction for the file.
90739          * @param dependencyGroups An array of grouped dependencies.
90740          */
90741         function createSettersArray(exportStarFunction, dependencyGroups) {
90742             var setters = [];
90743             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
90744                 var group_2 = dependencyGroups_1[_i];
90745                 // derive a unique name for parameter from the first named entry in the group
90746                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(i, currentSourceFile); });
90747                 var parameterName = localName ? ts.getGeneratedNameForNode(localName) : ts.createUniqueName("");
90748                 var statements = [];
90749                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
90750                     var entry = _b[_a];
90751                     var importVariableName = ts.getLocalNameForExternalImport(entry, currentSourceFile); // TODO: GH#18217
90752                     switch (entry.kind) {
90753                         case 254 /* ImportDeclaration */:
90754                             if (!entry.importClause) {
90755                                 // 'import "..."' case
90756                                 // module is imported only for side-effects, no emit required
90757                                 break;
90758                             }
90759                         // falls through
90760                         case 253 /* ImportEqualsDeclaration */:
90761                             ts.Debug.assert(importVariableName !== undefined);
90762                             // save import into the local
90763                             statements.push(ts.createExpressionStatement(ts.createAssignment(importVariableName, parameterName)));
90764                             break;
90765                         case 260 /* ExportDeclaration */:
90766                             ts.Debug.assert(importVariableName !== undefined);
90767                             if (entry.exportClause) {
90768                                 if (ts.isNamedExports(entry.exportClause)) {
90769                                     //  export {a, b as c} from 'foo'
90770                                     //
90771                                     // emit as:
90772                                     //
90773                                     //  exports_({
90774                                     //     "a": _["a"],
90775                                     //     "c": _["b"]
90776                                     //  });
90777                                     var properties = [];
90778                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
90779                                         var e = _d[_c];
90780                                         properties.push(ts.createPropertyAssignment(ts.createLiteral(ts.idText(e.name)), ts.createElementAccess(parameterName, ts.createLiteral(ts.idText(e.propertyName || e.name)))));
90781                                     }
90782                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90783                                     /*typeArguments*/ undefined, [ts.createObjectLiteral(properties, /*multiline*/ true)])));
90784                                 }
90785                                 else {
90786                                     statements.push(ts.createExpressionStatement(ts.createCall(exportFunction, 
90787                                     /*typeArguments*/ undefined, [
90788                                         ts.createLiteral(ts.idText(entry.exportClause.name)),
90789                                         parameterName
90790                                     ])));
90791                                 }
90792                             }
90793                             else {
90794                                 //  export * from 'foo'
90795                                 //
90796                                 // emit as:
90797                                 //
90798                                 //  exportStar(foo_1_1);
90799                                 statements.push(ts.createExpressionStatement(ts.createCall(exportStarFunction, 
90800                                 /*typeArguments*/ undefined, [parameterName])));
90801                             }
90802                             break;
90803                     }
90804                 }
90805                 setters.push(ts.createFunctionExpression(
90806                 /*modifiers*/ undefined, 
90807                 /*asteriskToken*/ undefined, 
90808                 /*name*/ undefined, 
90809                 /*typeParameters*/ undefined, [ts.createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
90810                 /*type*/ undefined, ts.createBlock(statements, /*multiLine*/ true)));
90811             }
90812             return ts.createArrayLiteral(setters, /*multiLine*/ true);
90813         }
90814         //
90815         // Top-level Source Element Visitors
90816         //
90817         /**
90818          * Visit source elements at the top-level of a module.
90819          *
90820          * @param node The node to visit.
90821          */
90822         function sourceElementVisitor(node) {
90823             switch (node.kind) {
90824                 case 254 /* ImportDeclaration */:
90825                     return visitImportDeclaration(node);
90826                 case 253 /* ImportEqualsDeclaration */:
90827                     return visitImportEqualsDeclaration(node);
90828                 case 260 /* ExportDeclaration */:
90829                     return visitExportDeclaration(node);
90830                 case 259 /* ExportAssignment */:
90831                     return visitExportAssignment(node);
90832                 default:
90833                     return nestedElementVisitor(node);
90834             }
90835         }
90836         /**
90837          * Visits an ImportDeclaration node.
90838          *
90839          * @param node The node to visit.
90840          */
90841         function visitImportDeclaration(node) {
90842             var statements;
90843             if (node.importClause) {
90844                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90845             }
90846             if (hasAssociatedEndOfDeclarationMarker(node)) {
90847                 // Defer exports until we encounter an EndOfDeclarationMarker node
90848                 var id = ts.getOriginalNodeId(node);
90849                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
90850             }
90851             else {
90852                 statements = appendExportsOfImportDeclaration(statements, node);
90853             }
90854             return ts.singleOrMany(statements);
90855         }
90856         function visitExportDeclaration(node) {
90857             ts.Debug.assertIsDefined(node);
90858             return undefined;
90859         }
90860         /**
90861          * Visits an ImportEqualsDeclaration node.
90862          *
90863          * @param node The node to visit.
90864          */
90865         function visitImportEqualsDeclaration(node) {
90866             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
90867             var statements;
90868             hoistVariableDeclaration(ts.getLocalNameForExternalImport(node, currentSourceFile)); // TODO: GH#18217
90869             if (hasAssociatedEndOfDeclarationMarker(node)) {
90870                 // Defer exports until we encounter an EndOfDeclarationMarker node
90871                 var id = ts.getOriginalNodeId(node);
90872                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
90873             }
90874             else {
90875                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
90876             }
90877             return ts.singleOrMany(statements);
90878         }
90879         /**
90880          * Visits an ExportAssignment node.
90881          *
90882          * @param node The node to visit.
90883          */
90884         function visitExportAssignment(node) {
90885             if (node.isExportEquals) {
90886                 // Elide `export=` as it is illegal in a SystemJS module.
90887                 return undefined;
90888             }
90889             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
90890             var original = node.original;
90891             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
90892                 // Defer exports until we encounter an EndOfDeclarationMarker node
90893                 var id = ts.getOriginalNodeId(node);
90894                 deferredExports[id] = appendExportStatement(deferredExports[id], ts.createIdentifier("default"), expression, /*allowComments*/ true);
90895             }
90896             else {
90897                 return createExportStatement(ts.createIdentifier("default"), expression, /*allowComments*/ true);
90898             }
90899         }
90900         /**
90901          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
90902          *
90903          * @param node The node to visit.
90904          */
90905         function visitFunctionDeclaration(node) {
90906             if (ts.hasModifier(node, 1 /* Export */)) {
90907                 hoistedStatements = ts.append(hoistedStatements, ts.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, ts.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
90908                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
90909                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
90910             }
90911             else {
90912                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
90913             }
90914             if (hasAssociatedEndOfDeclarationMarker(node)) {
90915                 // Defer exports until we encounter an EndOfDeclarationMarker node
90916                 var id = ts.getOriginalNodeId(node);
90917                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90918             }
90919             else {
90920                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
90921             }
90922             return undefined;
90923         }
90924         /**
90925          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
90926          *
90927          * @param node The node to visit.
90928          */
90929         function visitClassDeclaration(node) {
90930             var statements;
90931             // Hoist the name of the class declaration to the outer module body function.
90932             var name = ts.getLocalName(node);
90933             hoistVariableDeclaration(name);
90934             // Rewrite the class declaration into an assignment of a class expression.
90935             statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.createAssignment(name, ts.setTextRange(ts.createClassExpression(
90936             /*modifiers*/ undefined, node.name, 
90937             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
90938             if (hasAssociatedEndOfDeclarationMarker(node)) {
90939                 // Defer exports until we encounter an EndOfDeclarationMarker node
90940                 var id = ts.getOriginalNodeId(node);
90941                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
90942             }
90943             else {
90944                 statements = appendExportsOfHoistedDeclaration(statements, node);
90945             }
90946             return ts.singleOrMany(statements);
90947         }
90948         /**
90949          * Visits a variable statement, hoisting declared names to the top-level module body.
90950          * Each declaration is rewritten into an assignment expression.
90951          *
90952          * @param node The node to visit.
90953          */
90954         function visitVariableStatement(node) {
90955             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
90956                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
90957             }
90958             var expressions;
90959             var isExportedDeclaration = ts.hasModifier(node, 1 /* Export */);
90960             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
90961             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
90962                 var variable = _a[_i];
90963                 if (variable.initializer) {
90964                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
90965                 }
90966                 else {
90967                     hoistBindingElement(variable);
90968                 }
90969             }
90970             var statements;
90971             if (expressions) {
90972                 statements = ts.append(statements, ts.setTextRange(ts.createExpressionStatement(ts.inlineExpressions(expressions)), node));
90973             }
90974             if (isMarkedDeclaration) {
90975                 // Defer exports until we encounter an EndOfDeclarationMarker node
90976                 var id = ts.getOriginalNodeId(node);
90977                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
90978             }
90979             else {
90980                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
90981             }
90982             return ts.singleOrMany(statements);
90983         }
90984         /**
90985          * Hoists the declared names of a VariableDeclaration or BindingElement.
90986          *
90987          * @param node The declaration to hoist.
90988          */
90989         function hoistBindingElement(node) {
90990             if (ts.isBindingPattern(node.name)) {
90991                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
90992                     var element = _a[_i];
90993                     if (!ts.isOmittedExpression(element)) {
90994                         hoistBindingElement(element);
90995                     }
90996                 }
90997             }
90998             else {
90999                 hoistVariableDeclaration(ts.getSynthesizedClone(node.name));
91000             }
91001         }
91002         /**
91003          * Determines whether a VariableDeclarationList should be hoisted.
91004          *
91005          * @param node The node to test.
91006          */
91007         function shouldHoistVariableDeclarationList(node) {
91008             // hoist only non-block scoped declarations or block scoped declarations parented by source file
91009             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
91010                 && (enclosingBlockScopedContainer.kind === 290 /* SourceFile */
91011                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
91012         }
91013         /**
91014          * Transform an initialized variable declaration into an expression.
91015          *
91016          * @param node The node to transform.
91017          * @param isExportedDeclaration A value indicating whether the variable is exported.
91018          */
91019         function transformInitializedVariable(node, isExportedDeclaration) {
91020             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
91021             return ts.isBindingPattern(node.name)
91022                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91023                 /*needsValue*/ false, createAssignment)
91024                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
91025         }
91026         /**
91027          * Creates an assignment expression for an exported variable declaration.
91028          *
91029          * @param name The name of the variable.
91030          * @param value The value of the variable's initializer.
91031          * @param location The source map location for the assignment.
91032          */
91033         function createExportedVariableAssignment(name, value, location) {
91034             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
91035         }
91036         /**
91037          * Creates an assignment expression for a non-exported variable declaration.
91038          *
91039          * @param name The name of the variable.
91040          * @param value The value of the variable's initializer.
91041          * @param location The source map location for the assignment.
91042          */
91043         function createNonExportedVariableAssignment(name, value, location) {
91044             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
91045         }
91046         /**
91047          * Creates an assignment expression for a variable declaration.
91048          *
91049          * @param name The name of the variable.
91050          * @param value The value of the variable's initializer.
91051          * @param location The source map location for the assignment.
91052          * @param isExportedDeclaration A value indicating whether the variable is exported.
91053          */
91054         function createVariableAssignment(name, value, location, isExportedDeclaration) {
91055             hoistVariableDeclaration(ts.getSynthesizedClone(name));
91056             return isExportedDeclaration
91057                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location)))
91058                 : preventSubstitution(ts.setTextRange(ts.createAssignment(name, value), location));
91059         }
91060         /**
91061          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
91062          * and transformed declaration.
91063          *
91064          * @param node The node to visit.
91065          */
91066         function visitMergeDeclarationMarker(node) {
91067             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
91068             // declaration we do not emit a leading variable declaration. To preserve the
91069             // begin/end semantics of the declararation and to properly handle exports
91070             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
91071             //
91072             // To balance the declaration, we defer the exports of the elided variable
91073             // statement until we visit this declaration's `EndOfDeclarationMarker`.
91074             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 225 /* VariableStatement */) {
91075                 var id = ts.getOriginalNodeId(node);
91076                 var isExportedDeclaration = ts.hasModifier(node.original, 1 /* Export */);
91077                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
91078             }
91079             return node;
91080         }
91081         /**
91082          * Determines whether a node has an associated EndOfDeclarationMarker.
91083          *
91084          * @param node The node to test.
91085          */
91086         function hasAssociatedEndOfDeclarationMarker(node) {
91087             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
91088         }
91089         /**
91090          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
91091          * declaration.
91092          *
91093          * @param node The node to visit.
91094          */
91095         function visitEndOfDeclarationMarker(node) {
91096             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
91097             // end of the transformed declaration. We use this marker to emit any deferred exports
91098             // of the declaration.
91099             var id = ts.getOriginalNodeId(node);
91100             var statements = deferredExports[id];
91101             if (statements) {
91102                 delete deferredExports[id];
91103                 return ts.append(statements, node);
91104             }
91105             else {
91106                 var original = ts.getOriginalNode(node);
91107                 if (ts.isModuleOrEnumDeclaration(original)) {
91108                     return ts.append(appendExportsOfDeclaration(statements, original), node);
91109                 }
91110             }
91111             return node;
91112         }
91113         /**
91114          * Appends the exports of an ImportDeclaration to a statement list, returning the
91115          * statement list.
91116          *
91117          * @param statements A statement list to which the down-level export statements are to be
91118          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91119          * appended.
91120          * @param decl The declaration whose exports are to be recorded.
91121          */
91122         function appendExportsOfImportDeclaration(statements, decl) {
91123             if (moduleInfo.exportEquals) {
91124                 return statements;
91125             }
91126             var importClause = decl.importClause;
91127             if (!importClause) {
91128                 return statements;
91129             }
91130             if (importClause.name) {
91131                 statements = appendExportsOfDeclaration(statements, importClause);
91132             }
91133             var namedBindings = importClause.namedBindings;
91134             if (namedBindings) {
91135                 switch (namedBindings.kind) {
91136                     case 256 /* NamespaceImport */:
91137                         statements = appendExportsOfDeclaration(statements, namedBindings);
91138                         break;
91139                     case 257 /* NamedImports */:
91140                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
91141                             var importBinding = _a[_i];
91142                             statements = appendExportsOfDeclaration(statements, importBinding);
91143                         }
91144                         break;
91145                 }
91146             }
91147             return statements;
91148         }
91149         /**
91150          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
91151          * statement list.
91152          *
91153          * @param statements A statement list to which the down-level export statements are to be
91154          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91155          * appended.
91156          * @param decl The declaration whose exports are to be recorded.
91157          */
91158         function appendExportsOfImportEqualsDeclaration(statements, decl) {
91159             if (moduleInfo.exportEquals) {
91160                 return statements;
91161             }
91162             return appendExportsOfDeclaration(statements, decl);
91163         }
91164         /**
91165          * Appends the exports of a VariableStatement to a statement list, returning the statement
91166          * list.
91167          *
91168          * @param statements A statement list to which the down-level export statements are to be
91169          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91170          * appended.
91171          * @param node The VariableStatement whose exports are to be recorded.
91172          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
91173          * `nodes` declaration list.
91174          */
91175         function appendExportsOfVariableStatement(statements, node, exportSelf) {
91176             if (moduleInfo.exportEquals) {
91177                 return statements;
91178             }
91179             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91180                 var decl = _a[_i];
91181                 if (decl.initializer || exportSelf) {
91182                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
91183                 }
91184             }
91185             return statements;
91186         }
91187         /**
91188          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
91189          * returning the statement list.
91190          *
91191          * @param statements A statement list to which the down-level export statements are to be
91192          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91193          * appended.
91194          * @param decl The declaration whose exports are to be recorded.
91195          * @param exportSelf A value indicating whether to also export the declaration itself.
91196          */
91197         function appendExportsOfBindingElement(statements, decl, exportSelf) {
91198             if (moduleInfo.exportEquals) {
91199                 return statements;
91200             }
91201             if (ts.isBindingPattern(decl.name)) {
91202                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
91203                     var element = _a[_i];
91204                     if (!ts.isOmittedExpression(element)) {
91205                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
91206                     }
91207                 }
91208             }
91209             else if (!ts.isGeneratedIdentifier(decl.name)) {
91210                 var excludeName = void 0;
91211                 if (exportSelf) {
91212                     statements = appendExportStatement(statements, decl.name, ts.getLocalName(decl));
91213                     excludeName = ts.idText(decl.name);
91214                 }
91215                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91216             }
91217             return statements;
91218         }
91219         /**
91220          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
91221          * returning the statement list.
91222          *
91223          * @param statements A statement list to which the down-level export statements are to be
91224          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91225          * appended.
91226          * @param decl The declaration whose exports are to be recorded.
91227          */
91228         function appendExportsOfHoistedDeclaration(statements, decl) {
91229             if (moduleInfo.exportEquals) {
91230                 return statements;
91231             }
91232             var excludeName;
91233             if (ts.hasModifier(decl, 1 /* Export */)) {
91234                 var exportName = ts.hasModifier(decl, 512 /* Default */) ? ts.createLiteral("default") : decl.name;
91235                 statements = appendExportStatement(statements, exportName, ts.getLocalName(decl));
91236                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
91237             }
91238             if (decl.name) {
91239                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
91240             }
91241             return statements;
91242         }
91243         /**
91244          * Appends the exports of a declaration to a statement list, returning the statement list.
91245          *
91246          * @param statements A statement list to which the down-level export statements are to be
91247          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91248          * appended.
91249          * @param decl The declaration to export.
91250          * @param excludeName An optional name to exclude from exports.
91251          */
91252         function appendExportsOfDeclaration(statements, decl, excludeName) {
91253             if (moduleInfo.exportEquals) {
91254                 return statements;
91255             }
91256             var name = ts.getDeclarationName(decl);
91257             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
91258             if (exportSpecifiers) {
91259                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
91260                     var exportSpecifier = exportSpecifiers_2[_i];
91261                     if (exportSpecifier.name.escapedText !== excludeName) {
91262                         statements = appendExportStatement(statements, exportSpecifier.name, name);
91263                     }
91264                 }
91265             }
91266             return statements;
91267         }
91268         /**
91269          * Appends the down-level representation of an export to a statement list, returning the
91270          * statement list.
91271          *
91272          * @param statements A statement list to which the down-level export statements are to be
91273          * appended. If `statements` is `undefined`, a new array is allocated if statements are
91274          * appended.
91275          * @param exportName The name of the export.
91276          * @param expression The expression to export.
91277          * @param allowComments Whether to allow comments on the export.
91278          */
91279         function appendExportStatement(statements, exportName, expression, allowComments) {
91280             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
91281             return statements;
91282         }
91283         /**
91284          * Creates a call to the current file's export function to export a value.
91285          *
91286          * @param name The bound name of the export.
91287          * @param value The exported value.
91288          * @param allowComments An optional value indicating whether to emit comments for the statement.
91289          */
91290         function createExportStatement(name, value, allowComments) {
91291             var statement = ts.createExpressionStatement(createExportExpression(name, value));
91292             ts.startOnNewLine(statement);
91293             if (!allowComments) {
91294                 ts.setEmitFlags(statement, 1536 /* NoComments */);
91295             }
91296             return statement;
91297         }
91298         /**
91299          * Creates a call to the current file's export function to export a value.
91300          *
91301          * @param name The bound name of the export.
91302          * @param value The exported value.
91303          */
91304         function createExportExpression(name, value) {
91305             var exportName = ts.isIdentifier(name) ? ts.createLiteral(name) : name;
91306             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
91307             return ts.setCommentRange(ts.createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
91308         }
91309         //
91310         // Top-Level or Nested Source Element Visitors
91311         //
91312         /**
91313          * Visit nested elements at the top-level of a module.
91314          *
91315          * @param node The node to visit.
91316          */
91317         function nestedElementVisitor(node) {
91318             switch (node.kind) {
91319                 case 225 /* VariableStatement */:
91320                     return visitVariableStatement(node);
91321                 case 244 /* FunctionDeclaration */:
91322                     return visitFunctionDeclaration(node);
91323                 case 245 /* ClassDeclaration */:
91324                     return visitClassDeclaration(node);
91325                 case 230 /* ForStatement */:
91326                     return visitForStatement(node);
91327                 case 231 /* ForInStatement */:
91328                     return visitForInStatement(node);
91329                 case 232 /* ForOfStatement */:
91330                     return visitForOfStatement(node);
91331                 case 228 /* DoStatement */:
91332                     return visitDoStatement(node);
91333                 case 229 /* WhileStatement */:
91334                     return visitWhileStatement(node);
91335                 case 238 /* LabeledStatement */:
91336                     return visitLabeledStatement(node);
91337                 case 236 /* WithStatement */:
91338                     return visitWithStatement(node);
91339                 case 237 /* SwitchStatement */:
91340                     return visitSwitchStatement(node);
91341                 case 251 /* CaseBlock */:
91342                     return visitCaseBlock(node);
91343                 case 277 /* CaseClause */:
91344                     return visitCaseClause(node);
91345                 case 278 /* DefaultClause */:
91346                     return visitDefaultClause(node);
91347                 case 240 /* TryStatement */:
91348                     return visitTryStatement(node);
91349                 case 280 /* CatchClause */:
91350                     return visitCatchClause(node);
91351                 case 223 /* Block */:
91352                     return visitBlock(node);
91353                 case 328 /* MergeDeclarationMarker */:
91354                     return visitMergeDeclarationMarker(node);
91355                 case 329 /* EndOfDeclarationMarker */:
91356                     return visitEndOfDeclarationMarker(node);
91357                 default:
91358                     return destructuringAndImportCallVisitor(node);
91359             }
91360         }
91361         /**
91362          * Visits the body of a ForStatement to hoist declarations.
91363          *
91364          * @param node The node to visit.
91365          */
91366         function visitForStatement(node) {
91367             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91368             enclosingBlockScopedContainer = node;
91369             node = ts.updateFor(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
91370             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91371             return node;
91372         }
91373         /**
91374          * Visits the body of a ForInStatement to hoist declarations.
91375          *
91376          * @param node The node to visit.
91377          */
91378         function visitForInStatement(node) {
91379             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91380             enclosingBlockScopedContainer = node;
91381             node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91382             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91383             return node;
91384         }
91385         /**
91386          * Visits the body of a ForOfStatement to hoist declarations.
91387          *
91388          * @param node The node to visit.
91389          */
91390         function visitForOfStatement(node) {
91391             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91392             enclosingBlockScopedContainer = node;
91393             node = ts.updateForOf(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91394             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91395             return node;
91396         }
91397         /**
91398          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
91399          * ForOfStatement.
91400          *
91401          * @param node The node to test.
91402          */
91403         function shouldHoistForInitializer(node) {
91404             return ts.isVariableDeclarationList(node)
91405                 && shouldHoistVariableDeclarationList(node);
91406         }
91407         /**
91408          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
91409          *
91410          * @param node The node to visit.
91411          */
91412         function visitForInitializer(node) {
91413             if (shouldHoistForInitializer(node)) {
91414                 var expressions = void 0;
91415                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
91416                     var variable = _a[_i];
91417                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
91418                     if (!variable.initializer) {
91419                         hoistBindingElement(variable);
91420                     }
91421                 }
91422                 return expressions ? ts.inlineExpressions(expressions) : ts.createOmittedExpression();
91423             }
91424             else {
91425                 return ts.visitEachChild(node, nestedElementVisitor, context);
91426             }
91427         }
91428         /**
91429          * Visits the body of a DoStatement to hoist declarations.
91430          *
91431          * @param node The node to visit.
91432          */
91433         function visitDoStatement(node) {
91434             return ts.updateDo(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
91435         }
91436         /**
91437          * Visits the body of a WhileStatement to hoist declarations.
91438          *
91439          * @param node The node to visit.
91440          */
91441         function visitWhileStatement(node) {
91442             return ts.updateWhile(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91443         }
91444         /**
91445          * Visits the body of a LabeledStatement to hoist declarations.
91446          *
91447          * @param node The node to visit.
91448          */
91449         function visitLabeledStatement(node) {
91450             return ts.updateLabel(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91451         }
91452         /**
91453          * Visits the body of a WithStatement to hoist declarations.
91454          *
91455          * @param node The node to visit.
91456          */
91457         function visitWithStatement(node) {
91458             return ts.updateWith(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));
91459         }
91460         /**
91461          * Visits the body of a SwitchStatement to hoist declarations.
91462          *
91463          * @param node The node to visit.
91464          */
91465         function visitSwitchStatement(node) {
91466             return ts.updateSwitch(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
91467         }
91468         /**
91469          * Visits the body of a CaseBlock to hoist declarations.
91470          *
91471          * @param node The node to visit.
91472          */
91473         function visitCaseBlock(node) {
91474             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91475             enclosingBlockScopedContainer = node;
91476             node = ts.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
91477             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91478             return node;
91479         }
91480         /**
91481          * Visits the body of a CaseClause to hoist declarations.
91482          *
91483          * @param node The node to visit.
91484          */
91485         function visitCaseClause(node) {
91486             return ts.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
91487         }
91488         /**
91489          * Visits the body of a DefaultClause to hoist declarations.
91490          *
91491          * @param node The node to visit.
91492          */
91493         function visitDefaultClause(node) {
91494             return ts.visitEachChild(node, nestedElementVisitor, context);
91495         }
91496         /**
91497          * Visits the body of a TryStatement to hoist declarations.
91498          *
91499          * @param node The node to visit.
91500          */
91501         function visitTryStatement(node) {
91502             return ts.visitEachChild(node, nestedElementVisitor, context);
91503         }
91504         /**
91505          * Visits the body of a CatchClause to hoist declarations.
91506          *
91507          * @param node The node to visit.
91508          */
91509         function visitCatchClause(node) {
91510             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91511             enclosingBlockScopedContainer = node;
91512             node = ts.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
91513             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91514             return node;
91515         }
91516         /**
91517          * Visits the body of a Block to hoist declarations.
91518          *
91519          * @param node The node to visit.
91520          */
91521         function visitBlock(node) {
91522             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
91523             enclosingBlockScopedContainer = node;
91524             node = ts.visitEachChild(node, nestedElementVisitor, context);
91525             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
91526             return node;
91527         }
91528         //
91529         // Destructuring Assignment Visitors
91530         //
91531         /**
91532          * Visit nodes to flatten destructuring assignments to exported symbols.
91533          *
91534          * @param node The node to visit.
91535          */
91536         function destructuringAndImportCallVisitor(node) {
91537             if (ts.isDestructuringAssignment(node)) {
91538                 return visitDestructuringAssignment(node);
91539             }
91540             else if (ts.isImportCall(node)) {
91541                 return visitImportCallExpression(node);
91542             }
91543             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
91544                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91545             }
91546             else {
91547                 return node;
91548             }
91549         }
91550         function visitImportCallExpression(node) {
91551             // import("./blah")
91552             // emit as
91553             // System.register([], function (_export, _context) {
91554             //     return {
91555             //         setters: [],
91556             //         execute: () => {
91557             //             _context.import('./blah');
91558             //         }
91559             //     };
91560             // });
91561             return ts.createCall(ts.createPropertyAccess(contextObject, ts.createIdentifier("import")), 
91562             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
91563         }
91564         /**
91565          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
91566          *
91567          * @param node The node to visit.
91568          */
91569         function visitDestructuringAssignment(node) {
91570             if (hasExportedReferenceInDestructuringTarget(node.left)) {
91571                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
91572                 /*needsValue*/ true);
91573             }
91574             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
91575         }
91576         /**
91577          * Determines whether the target of a destructuring assigment refers to an exported symbol.
91578          *
91579          * @param node The destructuring target.
91580          */
91581         function hasExportedReferenceInDestructuringTarget(node) {
91582             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
91583                 return hasExportedReferenceInDestructuringTarget(node.left);
91584             }
91585             else if (ts.isSpreadElement(node)) {
91586                 return hasExportedReferenceInDestructuringTarget(node.expression);
91587             }
91588             else if (ts.isObjectLiteralExpression(node)) {
91589                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
91590             }
91591             else if (ts.isArrayLiteralExpression(node)) {
91592                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
91593             }
91594             else if (ts.isShorthandPropertyAssignment(node)) {
91595                 return hasExportedReferenceInDestructuringTarget(node.name);
91596             }
91597             else if (ts.isPropertyAssignment(node)) {
91598                 return hasExportedReferenceInDestructuringTarget(node.initializer);
91599             }
91600             else if (ts.isIdentifier(node)) {
91601                 var container = resolver.getReferencedExportContainer(node);
91602                 return container !== undefined && container.kind === 290 /* SourceFile */;
91603             }
91604             else {
91605                 return false;
91606             }
91607         }
91608         //
91609         // Modifier Visitors
91610         //
91611         /**
91612          * Visit nodes to elide module-specific modifiers.
91613          *
91614          * @param node The node to visit.
91615          */
91616         function modifierVisitor(node) {
91617             switch (node.kind) {
91618                 case 89 /* ExportKeyword */:
91619                 case 84 /* DefaultKeyword */:
91620                     return undefined;
91621             }
91622             return node;
91623         }
91624         //
91625         // Emit Notification
91626         //
91627         /**
91628          * Hook for node emit notifications.
91629          *
91630          * @param hint A hint as to the intended usage of the node.
91631          * @param node The node to emit.
91632          * @param emitCallback A callback used to emit the node in the printer.
91633          */
91634         function onEmitNode(hint, node, emitCallback) {
91635             if (node.kind === 290 /* SourceFile */) {
91636                 var id = ts.getOriginalNodeId(node);
91637                 currentSourceFile = node;
91638                 moduleInfo = moduleInfoMap[id];
91639                 exportFunction = exportFunctionsMap[id];
91640                 noSubstitution = noSubstitutionMap[id];
91641                 contextObject = contextObjectMap[id];
91642                 if (noSubstitution) {
91643                     delete noSubstitutionMap[id];
91644                 }
91645                 previousOnEmitNode(hint, node, emitCallback);
91646                 currentSourceFile = undefined;
91647                 moduleInfo = undefined;
91648                 exportFunction = undefined;
91649                 contextObject = undefined;
91650                 noSubstitution = undefined;
91651             }
91652             else {
91653                 previousOnEmitNode(hint, node, emitCallback);
91654             }
91655         }
91656         //
91657         // Substitutions
91658         //
91659         /**
91660          * Hooks node substitutions.
91661          *
91662          * @param hint A hint as to the intended usage of the node.
91663          * @param node The node to substitute.
91664          */
91665         function onSubstituteNode(hint, node) {
91666             node = previousOnSubstituteNode(hint, node);
91667             if (isSubstitutionPrevented(node)) {
91668                 return node;
91669             }
91670             if (hint === 1 /* Expression */) {
91671                 return substituteExpression(node);
91672             }
91673             else if (hint === 4 /* Unspecified */) {
91674                 return substituteUnspecified(node);
91675             }
91676             return node;
91677         }
91678         /**
91679          * Substitute the node, if necessary.
91680          *
91681          * @param node The node to substitute.
91682          */
91683         function substituteUnspecified(node) {
91684             switch (node.kind) {
91685                 case 282 /* ShorthandPropertyAssignment */:
91686                     return substituteShorthandPropertyAssignment(node);
91687             }
91688             return node;
91689         }
91690         /**
91691          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
91692          *
91693          * @param node The node to substitute.
91694          */
91695         function substituteShorthandPropertyAssignment(node) {
91696             var name = node.name;
91697             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
91698                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
91699                 if (importDeclaration) {
91700                     if (ts.isImportClause(importDeclaration)) {
91701                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), 
91702                         /*location*/ node);
91703                     }
91704                     else if (ts.isImportSpecifier(importDeclaration)) {
91705                         return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), 
91706                         /*location*/ node);
91707                     }
91708                 }
91709             }
91710             return node;
91711         }
91712         /**
91713          * Substitute the expression, if necessary.
91714          *
91715          * @param node The node to substitute.
91716          */
91717         function substituteExpression(node) {
91718             switch (node.kind) {
91719                 case 75 /* Identifier */:
91720                     return substituteExpressionIdentifier(node);
91721                 case 209 /* BinaryExpression */:
91722                     return substituteBinaryExpression(node);
91723                 case 207 /* PrefixUnaryExpression */:
91724                 case 208 /* PostfixUnaryExpression */:
91725                     return substituteUnaryExpression(node);
91726                 case 219 /* MetaProperty */:
91727                     return substituteMetaProperty(node);
91728             }
91729             return node;
91730         }
91731         /**
91732          * Substitution for an Identifier expression that may contain an imported or exported symbol.
91733          *
91734          * @param node The node to substitute.
91735          */
91736         function substituteExpressionIdentifier(node) {
91737             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
91738                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
91739                 if (externalHelpersModuleName) {
91740                     return ts.createPropertyAccess(externalHelpersModuleName, node);
91741                 }
91742                 return node;
91743             }
91744             // When we see an identifier in an expression position that
91745             // points to an imported symbol, we should substitute a qualified
91746             // reference to the imported symbol if one is needed.
91747             //
91748             // - We do not substitute generated identifiers for any reason.
91749             // - We do not substitute identifiers tagged with the LocalName flag.
91750             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
91751                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
91752                 if (importDeclaration) {
91753                     if (ts.isImportClause(importDeclaration)) {
91754                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default")), 
91755                         /*location*/ node);
91756                     }
91757                     else if (ts.isImportSpecifier(importDeclaration)) {
91758                         return ts.setTextRange(ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)), 
91759                         /*location*/ node);
91760                     }
91761                 }
91762             }
91763             return node;
91764         }
91765         /**
91766          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
91767          *
91768          * @param node The node to substitute.
91769          */
91770         function substituteBinaryExpression(node) {
91771             // When we see an assignment expression whose left-hand side is an exported symbol,
91772             // we should ensure all exports of that symbol are updated with the correct value.
91773             //
91774             // - We do not substitute generated identifiers for any reason.
91775             // - We do not substitute identifiers tagged with the LocalName flag.
91776             // - We do not substitute identifiers that were originally the name of an enum or
91777             //   namespace due to how they are transformed in TypeScript.
91778             // - We only substitute identifiers that are exported at the top level.
91779             if (ts.isAssignmentOperator(node.operatorToken.kind)
91780                 && ts.isIdentifier(node.left)
91781                 && !ts.isGeneratedIdentifier(node.left)
91782                 && !ts.isLocalName(node.left)
91783                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
91784                 var exportedNames = getExports(node.left);
91785                 if (exportedNames) {
91786                     // For each additional export of the declaration, apply an export assignment.
91787                     var expression = node;
91788                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
91789                         var exportName = exportedNames_4[_i];
91790                         expression = createExportExpression(exportName, preventSubstitution(expression));
91791                     }
91792                     return expression;
91793                 }
91794             }
91795             return node;
91796         }
91797         /**
91798          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
91799          *
91800          * @param node The node to substitute.
91801          */
91802         function substituteUnaryExpression(node) {
91803             // When we see a prefix or postfix increment expression whose operand is an exported
91804             // symbol, we should ensure all exports of that symbol are updated with the correct
91805             // value.
91806             //
91807             // - We do not substitute generated identifiers for any reason.
91808             // - We do not substitute identifiers tagged with the LocalName flag.
91809             // - We do not substitute identifiers that were originally the name of an enum or
91810             //   namespace due to how they are transformed in TypeScript.
91811             // - We only substitute identifiers that are exported at the top level.
91812             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
91813                 && ts.isIdentifier(node.operand)
91814                 && !ts.isGeneratedIdentifier(node.operand)
91815                 && !ts.isLocalName(node.operand)
91816                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
91817                 var exportedNames = getExports(node.operand);
91818                 if (exportedNames) {
91819                     var expression = node.kind === 208 /* PostfixUnaryExpression */
91820                         ? ts.setTextRange(ts.createPrefix(node.operator, node.operand), node)
91821                         : node;
91822                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
91823                         var exportName = exportedNames_5[_i];
91824                         expression = createExportExpression(exportName, preventSubstitution(expression));
91825                     }
91826                     if (node.kind === 208 /* PostfixUnaryExpression */) {
91827                         expression = node.operator === 45 /* PlusPlusToken */
91828                             ? ts.createSubtract(preventSubstitution(expression), ts.createLiteral(1))
91829                             : ts.createAdd(preventSubstitution(expression), ts.createLiteral(1));
91830                     }
91831                     return expression;
91832                 }
91833             }
91834             return node;
91835         }
91836         function substituteMetaProperty(node) {
91837             if (ts.isImportMeta(node)) {
91838                 return ts.createPropertyAccess(contextObject, ts.createIdentifier("meta"));
91839             }
91840             return node;
91841         }
91842         /**
91843          * Gets the exports of a name.
91844          *
91845          * @param name The name.
91846          */
91847         function getExports(name) {
91848             var exportedNames;
91849             if (!ts.isGeneratedIdentifier(name)) {
91850                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
91851                     || resolver.getReferencedValueDeclaration(name);
91852                 if (valueDeclaration) {
91853                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
91854                     if (exportContainer && exportContainer.kind === 290 /* SourceFile */) {
91855                         exportedNames = ts.append(exportedNames, ts.getDeclarationName(valueDeclaration));
91856                     }
91857                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
91858                 }
91859             }
91860             return exportedNames;
91861         }
91862         /**
91863          * Prevent substitution of a node for this transformer.
91864          *
91865          * @param node The node which should not be substituted.
91866          */
91867         function preventSubstitution(node) {
91868             if (noSubstitution === undefined)
91869                 noSubstitution = [];
91870             noSubstitution[ts.getNodeId(node)] = true;
91871             return node;
91872         }
91873         /**
91874          * Determines whether a node should not be substituted.
91875          *
91876          * @param node The node to test.
91877          */
91878         function isSubstitutionPrevented(node) {
91879             return noSubstitution && node.id && noSubstitution[node.id];
91880         }
91881     }
91882     ts.transformSystemModule = transformSystemModule;
91883 })(ts || (ts = {}));
91884 /*@internal*/
91885 var ts;
91886 (function (ts) {
91887     function transformECMAScriptModule(context) {
91888         var compilerOptions = context.getCompilerOptions();
91889         var previousOnEmitNode = context.onEmitNode;
91890         var previousOnSubstituteNode = context.onSubstituteNode;
91891         context.onEmitNode = onEmitNode;
91892         context.onSubstituteNode = onSubstituteNode;
91893         context.enableEmitNotification(290 /* SourceFile */);
91894         context.enableSubstitution(75 /* Identifier */);
91895         var helperNameSubstitutions;
91896         return ts.chainBundle(transformSourceFile);
91897         function transformSourceFile(node) {
91898             if (node.isDeclarationFile) {
91899                 return node;
91900             }
91901             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
91902                 var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(node, compilerOptions);
91903                 if (externalHelpersImportDeclaration) {
91904                     var statements = [];
91905                     var statementOffset = ts.addPrologue(statements, node.statements);
91906                     ts.append(statements, externalHelpersImportDeclaration);
91907                     ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
91908                     return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements));
91909                 }
91910                 else {
91911                     return ts.visitEachChild(node, visitor, context);
91912                 }
91913             }
91914             return node;
91915         }
91916         function visitor(node) {
91917             switch (node.kind) {
91918                 case 253 /* ImportEqualsDeclaration */:
91919                     // Elide `import=` as it is not legal with --module ES6
91920                     return undefined;
91921                 case 259 /* ExportAssignment */:
91922                     return visitExportAssignment(node);
91923                 case 260 /* ExportDeclaration */:
91924                     var exportDecl = node;
91925                     return visitExportDeclaration(exportDecl);
91926             }
91927             return node;
91928         }
91929         function visitExportAssignment(node) {
91930             // Elide `export=` as it is not legal with --module ES6
91931             return node.isExportEquals ? undefined : node;
91932         }
91933         function visitExportDeclaration(node) {
91934             // `export * as ns` only needs to be transformed in ES2015
91935             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
91936                 return node;
91937             }
91938             // Either ill-formed or don't need to be tranformed.
91939             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
91940                 return node;
91941             }
91942             var oldIdentifier = node.exportClause.name;
91943             var synthName = ts.getGeneratedNameForNode(oldIdentifier);
91944             var importDecl = ts.createImportDeclaration(
91945             /*decorators*/ undefined, 
91946             /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(synthName)), node.moduleSpecifier);
91947             ts.setOriginalNode(importDecl, node.exportClause);
91948             var exportDecl = ts.createExportDeclaration(
91949             /*decorators*/ undefined, 
91950             /*modifiers*/ undefined, ts.createNamedExports([ts.createExportSpecifier(synthName, oldIdentifier)]));
91951             ts.setOriginalNode(exportDecl, node);
91952             return [importDecl, exportDecl];
91953         }
91954         //
91955         // Emit Notification
91956         //
91957         /**
91958          * Hook for node emit.
91959          *
91960          * @param hint A hint as to the intended usage of the node.
91961          * @param node The node to emit.
91962          * @param emit A callback used to emit the node in the printer.
91963          */
91964         function onEmitNode(hint, node, emitCallback) {
91965             if (ts.isSourceFile(node)) {
91966                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
91967                     helperNameSubstitutions = ts.createMap();
91968                 }
91969                 previousOnEmitNode(hint, node, emitCallback);
91970                 helperNameSubstitutions = undefined;
91971             }
91972             else {
91973                 previousOnEmitNode(hint, node, emitCallback);
91974             }
91975         }
91976         //
91977         // Substitutions
91978         //
91979         /**
91980          * Hooks node substitutions.
91981          *
91982          * @param hint A hint as to the intended usage of the node.
91983          * @param node The node to substitute.
91984          */
91985         function onSubstituteNode(hint, node) {
91986             node = previousOnSubstituteNode(hint, node);
91987             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
91988                 return substituteHelperName(node);
91989             }
91990             return node;
91991         }
91992         function substituteHelperName(node) {
91993             var name = ts.idText(node);
91994             var substitution = helperNameSubstitutions.get(name);
91995             if (!substitution) {
91996                 helperNameSubstitutions.set(name, substitution = ts.createFileLevelUniqueName(name));
91997             }
91998             return substitution;
91999         }
92000     }
92001     ts.transformECMAScriptModule = transformECMAScriptModule;
92002 })(ts || (ts = {}));
92003 /* @internal */
92004 var ts;
92005 (function (ts) {
92006     function canProduceDiagnostics(node) {
92007         return ts.isVariableDeclaration(node) ||
92008             ts.isPropertyDeclaration(node) ||
92009             ts.isPropertySignature(node) ||
92010             ts.isBindingElement(node) ||
92011             ts.isSetAccessor(node) ||
92012             ts.isGetAccessor(node) ||
92013             ts.isConstructSignatureDeclaration(node) ||
92014             ts.isCallSignatureDeclaration(node) ||
92015             ts.isMethodDeclaration(node) ||
92016             ts.isMethodSignature(node) ||
92017             ts.isFunctionDeclaration(node) ||
92018             ts.isParameter(node) ||
92019             ts.isTypeParameterDeclaration(node) ||
92020             ts.isExpressionWithTypeArguments(node) ||
92021             ts.isImportEqualsDeclaration(node) ||
92022             ts.isTypeAliasDeclaration(node) ||
92023             ts.isConstructorDeclaration(node) ||
92024             ts.isIndexSignatureDeclaration(node) ||
92025             ts.isPropertyAccessExpression(node);
92026     }
92027     ts.canProduceDiagnostics = canProduceDiagnostics;
92028     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
92029         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92030             return getAccessorNameVisibilityError;
92031         }
92032         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
92033             return getMethodNameVisibilityError;
92034         }
92035         else {
92036             return createGetSymbolAccessibilityDiagnosticForNode(node);
92037         }
92038         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
92039             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92040             return diagnosticMessage !== undefined ? {
92041                 diagnosticMessage: diagnosticMessage,
92042                 errorNode: node,
92043                 typeName: node.name
92044             } : undefined;
92045         }
92046         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92047             if (ts.hasModifier(node, 32 /* Static */)) {
92048                 return symbolAccessibilityResult.errorModuleName ?
92049                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92050                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92051                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92052                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92053             }
92054             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92055                 return symbolAccessibilityResult.errorModuleName ?
92056                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92057                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92058                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92059                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92060             }
92061             else {
92062                 return symbolAccessibilityResult.errorModuleName ?
92063                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92064                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92065             }
92066         }
92067         function getMethodNameVisibilityError(symbolAccessibilityResult) {
92068             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
92069             return diagnosticMessage !== undefined ? {
92070                 diagnosticMessage: diagnosticMessage,
92071                 errorNode: node,
92072                 typeName: node.name
92073             } : undefined;
92074         }
92075         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92076             if (ts.hasModifier(node, 32 /* Static */)) {
92077                 return symbolAccessibilityResult.errorModuleName ?
92078                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92079                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92080                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92081                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
92082             }
92083             else if (node.parent.kind === 245 /* ClassDeclaration */) {
92084                 return symbolAccessibilityResult.errorModuleName ?
92085                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92086                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92087                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92088                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
92089             }
92090             else {
92091                 return symbolAccessibilityResult.errorModuleName ?
92092                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92093                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
92094             }
92095         }
92096     }
92097     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
92098     function createGetSymbolAccessibilityDiagnosticForNode(node) {
92099         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
92100             return getVariableDeclarationTypeVisibilityError;
92101         }
92102         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
92103             return getAccessorDeclarationTypeVisibilityError;
92104         }
92105         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
92106             return getReturnTypeVisibilityError;
92107         }
92108         else if (ts.isParameter(node)) {
92109             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasModifier(node.parent, 8 /* Private */)) {
92110                 return getVariableDeclarationTypeVisibilityError;
92111             }
92112             return getParameterDeclarationTypeVisibilityError;
92113         }
92114         else if (ts.isTypeParameterDeclaration(node)) {
92115             return getTypeParameterConstraintVisibilityError;
92116         }
92117         else if (ts.isExpressionWithTypeArguments(node)) {
92118             return getHeritageClauseVisibilityError;
92119         }
92120         else if (ts.isImportEqualsDeclaration(node)) {
92121             return getImportEntityNameVisibilityError;
92122         }
92123         else if (ts.isTypeAliasDeclaration(node)) {
92124             return getTypeAliasDeclarationVisibilityError;
92125         }
92126         else {
92127             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
92128         }
92129         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92130             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92131                 return symbolAccessibilityResult.errorModuleName ?
92132                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92133                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92134                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
92135                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
92136             }
92137             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
92138             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
92139             else if (node.kind === 159 /* PropertyDeclaration */ || node.kind === 194 /* PropertyAccessExpression */ || node.kind === 158 /* PropertySignature */ ||
92140                 (node.kind === 156 /* Parameter */ && ts.hasModifier(node.parent, 8 /* Private */))) {
92141                 // TODO(jfreeman): Deal with computed properties in error reporting.
92142                 if (ts.hasModifier(node, 32 /* Static */)) {
92143                     return symbolAccessibilityResult.errorModuleName ?
92144                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92145                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92146                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92147                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
92148                 }
92149                 else if (node.parent.kind === 245 /* ClassDeclaration */ || node.kind === 156 /* Parameter */) {
92150                     return symbolAccessibilityResult.errorModuleName ?
92151                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92152                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92153                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
92154                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
92155                 }
92156                 else {
92157                     // Interfaces cannot have types that cannot be named
92158                     return symbolAccessibilityResult.errorModuleName ?
92159                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92160                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
92161                 }
92162             }
92163         }
92164         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92165             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92166             return diagnosticMessage !== undefined ? {
92167                 diagnosticMessage: diagnosticMessage,
92168                 errorNode: node,
92169                 typeName: node.name
92170             } : undefined;
92171         }
92172         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92173             var diagnosticMessage;
92174             if (node.kind === 164 /* SetAccessor */) {
92175                 // Getters can infer the return type from the returned expression, but setters cannot, so the
92176                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
92177                 if (ts.hasModifier(node, 32 /* Static */)) {
92178                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92179                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92180                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
92181                 }
92182                 else {
92183                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92184                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92185                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
92186                 }
92187             }
92188             else {
92189                 if (ts.hasModifier(node, 32 /* Static */)) {
92190                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92191                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92192                             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 :
92193                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92194                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
92195                 }
92196                 else {
92197                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92198                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92199                             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 :
92200                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92201                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
92202                 }
92203             }
92204             return {
92205                 diagnosticMessage: diagnosticMessage,
92206                 errorNode: node.name,
92207                 typeName: node.name
92208             };
92209         }
92210         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
92211             var diagnosticMessage;
92212             switch (node.kind) {
92213                 case 166 /* ConstructSignature */:
92214                     // Interfaces cannot have return types that cannot be named
92215                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92216                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92217                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
92218                     break;
92219                 case 165 /* CallSignature */:
92220                     // Interfaces cannot have return types that cannot be named
92221                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92222                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92223                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
92224                     break;
92225                 case 167 /* IndexSignature */:
92226                     // Interfaces cannot have return types that cannot be named
92227                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92228                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92229                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
92230                     break;
92231                 case 161 /* MethodDeclaration */:
92232                 case 160 /* MethodSignature */:
92233                     if (ts.hasModifier(node, 32 /* Static */)) {
92234                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92235                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92236                                 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 :
92237                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92238                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
92239                     }
92240                     else if (node.parent.kind === 245 /* ClassDeclaration */) {
92241                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92242                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92243                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92244                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
92245                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
92246                     }
92247                     else {
92248                         // Interfaces cannot have return types that cannot be named
92249                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92250                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
92251                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
92252                     }
92253                     break;
92254                 case 244 /* FunctionDeclaration */:
92255                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
92256                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92257                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
92258                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
92259                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
92260                     break;
92261                 default:
92262                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
92263             }
92264             return {
92265                 diagnosticMessage: diagnosticMessage,
92266                 errorNode: node.name || node
92267             };
92268         }
92269         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
92270             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
92271             return diagnosticMessage !== undefined ? {
92272                 diagnosticMessage: diagnosticMessage,
92273                 errorNode: node,
92274                 typeName: node.name
92275             } : undefined;
92276         }
92277         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
92278             switch (node.parent.kind) {
92279                 case 162 /* Constructor */:
92280                     return symbolAccessibilityResult.errorModuleName ?
92281                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92282                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92283                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92284                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
92285                 case 166 /* ConstructSignature */:
92286                 case 171 /* ConstructorType */:
92287                     // Interfaces cannot have parameter types that cannot be named
92288                     return symbolAccessibilityResult.errorModuleName ?
92289                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92290                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92291                 case 165 /* CallSignature */:
92292                     // Interfaces cannot have parameter types that cannot be named
92293                     return symbolAccessibilityResult.errorModuleName ?
92294                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92295                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92296                 case 167 /* IndexSignature */:
92297                     // Interfaces cannot have parameter types that cannot be named
92298                     return symbolAccessibilityResult.errorModuleName ?
92299                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92300                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
92301                 case 161 /* MethodDeclaration */:
92302                 case 160 /* MethodSignature */:
92303                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92304                         return symbolAccessibilityResult.errorModuleName ?
92305                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92306                                 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 :
92307                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92308                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92309                     }
92310                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92311                         return symbolAccessibilityResult.errorModuleName ?
92312                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92313                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92314                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
92315                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92316                     }
92317                     else {
92318                         // Interfaces cannot have parameter types that cannot be named
92319                         return symbolAccessibilityResult.errorModuleName ?
92320                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
92321                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92322                     }
92323                 case 244 /* FunctionDeclaration */:
92324                 case 170 /* FunctionType */:
92325                     return symbolAccessibilityResult.errorModuleName ?
92326                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92327                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92328                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
92329                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
92330                 case 164 /* SetAccessor */:
92331                 case 163 /* GetAccessor */:
92332                     return symbolAccessibilityResult.errorModuleName ?
92333                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
92334                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
92335                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
92336                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
92337                 default:
92338                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
92339             }
92340         }
92341         function getTypeParameterConstraintVisibilityError() {
92342             // Type parameter constraints are named by user so we should always be able to name it
92343             var diagnosticMessage;
92344             switch (node.parent.kind) {
92345                 case 245 /* ClassDeclaration */:
92346                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
92347                     break;
92348                 case 246 /* InterfaceDeclaration */:
92349                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
92350                     break;
92351                 case 186 /* MappedType */:
92352                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
92353                     break;
92354                 case 171 /* ConstructorType */:
92355                 case 166 /* ConstructSignature */:
92356                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
92357                     break;
92358                 case 165 /* CallSignature */:
92359                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
92360                     break;
92361                 case 161 /* MethodDeclaration */:
92362                 case 160 /* MethodSignature */:
92363                     if (ts.hasModifier(node.parent, 32 /* Static */)) {
92364                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
92365                     }
92366                     else if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92367                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
92368                     }
92369                     else {
92370                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
92371                     }
92372                     break;
92373                 case 170 /* FunctionType */:
92374                 case 244 /* FunctionDeclaration */:
92375                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
92376                     break;
92377                 case 247 /* TypeAliasDeclaration */:
92378                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
92379                     break;
92380                 default:
92381                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
92382             }
92383             return {
92384                 diagnosticMessage: diagnosticMessage,
92385                 errorNode: node,
92386                 typeName: node.name
92387             };
92388         }
92389         function getHeritageClauseVisibilityError() {
92390             var diagnosticMessage;
92391             // Heritage clause is written by user so it can always be named
92392             if (node.parent.parent.kind === 245 /* ClassDeclaration */) {
92393                 // Class or Interface implemented/extended is inaccessible
92394                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 113 /* ImplementsKeyword */ ?
92395                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
92396                     ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1;
92397             }
92398             else {
92399                 // interface is inaccessible
92400                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
92401             }
92402             return {
92403                 diagnosticMessage: diagnosticMessage,
92404                 errorNode: node,
92405                 typeName: ts.getNameOfDeclaration(node.parent.parent)
92406             };
92407         }
92408         function getImportEntityNameVisibilityError() {
92409             return {
92410                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
92411                 errorNode: node,
92412                 typeName: node.name
92413             };
92414         }
92415         function getTypeAliasDeclarationVisibilityError() {
92416             return {
92417                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
92418                 errorNode: node.type,
92419                 typeName: node.name
92420             };
92421         }
92422     }
92423     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
92424 })(ts || (ts = {}));
92425 /*@internal*/
92426 var ts;
92427 (function (ts) {
92428     function getDeclarationDiagnostics(host, resolver, file) {
92429         if (file && ts.isJsonSourceFile(file)) {
92430             return []; // No declaration diagnostics for json for now
92431         }
92432         var compilerOptions = host.getCompilerOptions();
92433         var result = ts.transformNodes(resolver, host, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
92434         return result.diagnostics;
92435     }
92436     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
92437     function hasInternalAnnotation(range, currentSourceFile) {
92438         var comment = currentSourceFile.text.substring(range.pos, range.end);
92439         return ts.stringContains(comment, "@internal");
92440     }
92441     function isInternalDeclaration(node, currentSourceFile) {
92442         var parseTreeNode = ts.getParseTreeNode(node);
92443         if (parseTreeNode && parseTreeNode.kind === 156 /* Parameter */) {
92444             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
92445             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
92446             var text = currentSourceFile.text;
92447             var commentRanges = previousSibling
92448                 ? ts.concatenate(
92449                 // to handle
92450                 // ... parameters, /* @internal */
92451                 // public param: string
92452                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
92453                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
92454             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
92455         }
92456         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
92457         return !!ts.forEach(leadingCommentRanges, function (range) {
92458             return hasInternalAnnotation(range, currentSourceFile);
92459         });
92460     }
92461     ts.isInternalDeclaration = isInternalDeclaration;
92462     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
92463         2048 /* WriteClassExpressionAsTypeLiteral */ |
92464         4096 /* UseTypeOfFunction */ |
92465         8 /* UseStructuralFallback */ |
92466         524288 /* AllowEmptyTuple */ |
92467         4 /* GenerateNamesForShadowedTypeParams */ |
92468         1 /* NoTruncation */;
92469     /**
92470      * Transforms a ts file into a .d.ts file
92471      * This process requires type information, which is retrieved through the emit resolver. Because of this,
92472      * in many places this transformer assumes it will be operating on parse tree nodes directly.
92473      * This means that _no transforms should be allowed to occur before this one_.
92474      */
92475     function transformDeclarations(context) {
92476         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
92477         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
92478         var needsDeclare = true;
92479         var isBundledEmit = false;
92480         var resultHasExternalModuleIndicator = false;
92481         var needsScopeFixMarker = false;
92482         var resultHasScopeMarker = false;
92483         var enclosingDeclaration;
92484         var necessaryTypeReferences;
92485         var lateMarkedStatements;
92486         var lateStatementReplacementMap;
92487         var suppressNewDiagnosticContexts;
92488         var exportedModulesFromDeclarationEmit;
92489         var host = context.getEmitHost();
92490         var symbolTracker = {
92491             trackSymbol: trackSymbol,
92492             reportInaccessibleThisError: reportInaccessibleThisError,
92493             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
92494             reportCyclicStructureError: reportCyclicStructureError,
92495             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
92496             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
92497             moduleResolverHost: host,
92498             trackReferencedAmbientModule: trackReferencedAmbientModule,
92499             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
92500             reportNonlocalAugmentation: reportNonlocalAugmentation
92501         };
92502         var errorNameNode;
92503         var currentSourceFile;
92504         var refs;
92505         var libs;
92506         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
92507         var resolver = context.getEmitResolver();
92508         var options = context.getCompilerOptions();
92509         var noResolve = options.noResolve, stripInternal = options.stripInternal;
92510         return transformRoot;
92511         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
92512             if (!typeReferenceDirectives) {
92513                 return;
92514             }
92515             necessaryTypeReferences = necessaryTypeReferences || ts.createMap();
92516             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
92517                 var ref = typeReferenceDirectives_2[_i];
92518                 necessaryTypeReferences.set(ref, true);
92519             }
92520         }
92521         function trackReferencedAmbientModule(node, symbol) {
92522             // If it is visible via `// <reference types="..."/>`, then we should just use that
92523             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
92524             if (ts.length(directives)) {
92525                 return recordTypeReferenceDirectivesIfNecessary(directives);
92526             }
92527             // Otherwise we should emit a path-based reference
92528             var container = ts.getSourceFileOfNode(node);
92529             refs.set("" + ts.getOriginalNodeId(container), container);
92530         }
92531         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
92532             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
92533                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
92534                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
92535                     if (!lateMarkedStatements) {
92536                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
92537                     }
92538                     else {
92539                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
92540                             var ref = _a[_i];
92541                             ts.pushIfUnique(lateMarkedStatements, ref);
92542                         }
92543                     }
92544                 }
92545                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
92546             }
92547             else {
92548                 // Report error
92549                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
92550                 if (errorInfo) {
92551                     if (errorInfo.typeName) {
92552                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92553                     }
92554                     else {
92555                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
92556                     }
92557                 }
92558             }
92559         }
92560         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
92561             if (!isBundledEmit) {
92562                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92563             }
92564         }
92565         function trackSymbol(symbol, enclosingDeclaration, meaning) {
92566             if (symbol.flags & 262144 /* TypeParameter */)
92567                 return;
92568             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
92569             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
92570         }
92571         function reportPrivateInBaseOfClassExpression(propertyName) {
92572             if (errorNameNode) {
92573                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
92574             }
92575         }
92576         function reportInaccessibleUniqueSymbolError() {
92577             if (errorNameNode) {
92578                 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"));
92579             }
92580         }
92581         function reportCyclicStructureError() {
92582             if (errorNameNode) {
92583                 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)));
92584             }
92585         }
92586         function reportInaccessibleThisError() {
92587             if (errorNameNode) {
92588                 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"));
92589             }
92590         }
92591         function reportLikelyUnsafeImportRequiredError(specifier) {
92592             if (errorNameNode) {
92593                 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));
92594             }
92595         }
92596         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
92597             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
92598             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
92599             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
92600                 var augmentations = augmentingDeclarations_1[_i];
92601                 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)));
92602             }
92603         }
92604         function transformDeclarationsForJS(sourceFile, bundled) {
92605             var oldDiag = getSymbolAccessibilityDiagnostic;
92606             getSymbolAccessibilityDiagnostic = function (s) { return ({
92607                 diagnosticMessage: s.errorModuleName
92608                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
92609                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
92610                 errorNode: s.errorNode || sourceFile
92611             }); };
92612             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
92613             getSymbolAccessibilityDiagnostic = oldDiag;
92614             return result;
92615         }
92616         function transformRoot(node) {
92617             if (node.kind === 290 /* SourceFile */ && node.isDeclarationFile) {
92618                 return node;
92619             }
92620             if (node.kind === 291 /* Bundle */) {
92621                 isBundledEmit = true;
92622                 refs = ts.createMap();
92623                 libs = ts.createMap();
92624                 var hasNoDefaultLib_1 = false;
92625                 var bundle = ts.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
92626                     if (sourceFile.isDeclarationFile)
92627                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
92628                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
92629                     currentSourceFile = sourceFile;
92630                     enclosingDeclaration = sourceFile;
92631                     lateMarkedStatements = undefined;
92632                     suppressNewDiagnosticContexts = false;
92633                     lateStatementReplacementMap = ts.createMap();
92634                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
92635                     needsScopeFixMarker = false;
92636                     resultHasScopeMarker = false;
92637                     collectReferences(sourceFile, refs);
92638                     collectLibs(sourceFile, libs);
92639                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
92640                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
92641                         needsDeclare = false;
92642                         var statements = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92643                         var newFile = ts.updateSourceFileNode(sourceFile, [ts.createModuleDeclaration([], [ts.createModifier(130 /* DeclareKeyword */)], ts.createLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), ts.createModuleBlock(ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92644                         return newFile;
92645                     }
92646                     needsDeclare = true;
92647                     var updated = ts.isSourceFileJS(sourceFile) ? ts.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
92648                     return ts.updateSourceFileNode(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
92649                 }), ts.mapDefined(node.prepends, function (prepend) {
92650                     if (prepend.kind === 293 /* InputFiles */) {
92651                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
92652                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
92653                         collectReferences(sourceFile, refs);
92654                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
92655                         collectLibs(sourceFile, libs);
92656                         return sourceFile;
92657                     }
92658                     return prepend;
92659                 }));
92660                 bundle.syntheticFileReferences = [];
92661                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
92662                 bundle.syntheticLibReferences = getLibReferences();
92663                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
92664                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92665                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
92666                 refs.forEach(referenceVisitor_1);
92667                 return bundle;
92668             }
92669             // Single source file
92670             needsDeclare = true;
92671             needsScopeFixMarker = false;
92672             resultHasScopeMarker = false;
92673             enclosingDeclaration = node;
92674             currentSourceFile = node;
92675             getSymbolAccessibilityDiagnostic = throwDiagnostic;
92676             isBundledEmit = false;
92677             resultHasExternalModuleIndicator = false;
92678             suppressNewDiagnosticContexts = false;
92679             lateMarkedStatements = undefined;
92680             lateStatementReplacementMap = ts.createMap();
92681             necessaryTypeReferences = undefined;
92682             refs = collectReferences(currentSourceFile, ts.createMap());
92683             libs = collectLibs(currentSourceFile, ts.createMap());
92684             var references = [];
92685             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
92686             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
92687             var combinedStatements;
92688             if (ts.isSourceFileJS(currentSourceFile)) {
92689                 combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node));
92690                 refs.forEach(referenceVisitor);
92691                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92692             }
92693             else {
92694                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
92695                 combinedStatements = ts.setTextRange(ts.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
92696                 refs.forEach(referenceVisitor);
92697                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
92698                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
92699                     combinedStatements = ts.setTextRange(ts.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports()])), combinedStatements);
92700                 }
92701             }
92702             var updated = ts.updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
92703             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
92704             return updated;
92705             function getLibReferences() {
92706                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
92707             }
92708             function getFileReferencesForUsedTypeReferences() {
92709                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
92710             }
92711             function getFileReferenceForTypeName(typeName) {
92712                 // Elide type references for which we have imports
92713                 if (emittedImports) {
92714                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
92715                         var importStatement = emittedImports_1[_i];
92716                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
92717                             var expr = importStatement.moduleReference.expression;
92718                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
92719                                 return undefined;
92720                             }
92721                         }
92722                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
92723                             return undefined;
92724                         }
92725                     }
92726                 }
92727                 return { fileName: typeName, pos: -1, end: -1 };
92728             }
92729             function mapReferencesIntoArray(references, outputFilePath) {
92730                 return function (file) {
92731                     var declFileName;
92732                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
92733                         declFileName = file.fileName;
92734                     }
92735                     else {
92736                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
92737                             return; // Omit references to files which are being merged
92738                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
92739                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
92740                     }
92741                     if (declFileName) {
92742                         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, 
92743                         /*preferences*/ undefined);
92744                         if (!ts.pathIsRelative(specifier)) {
92745                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
92746                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
92747                             // a relative path to the declaration file
92748                             recordTypeReferenceDirectivesIfNecessary([specifier]);
92749                             return;
92750                         }
92751                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
92752                         /*isAbsolutePathAnUrl*/ false);
92753                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
92754                             fileName = fileName.substring(2);
92755                         }
92756                         // omit references to files from node_modules (npm may disambiguate module
92757                         // references when installing this package, making the path is unreliable).
92758                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
92759                             return;
92760                         }
92761                         references.push({ pos: -1, end: -1, fileName: fileName });
92762                     }
92763                 };
92764             }
92765         }
92766         function collectReferences(sourceFile, ret) {
92767             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
92768                 return ret;
92769             ts.forEach(sourceFile.referencedFiles, function (f) {
92770                 var elem = host.getSourceFileFromReference(sourceFile, f);
92771                 if (elem) {
92772                     ret.set("" + ts.getOriginalNodeId(elem), elem);
92773                 }
92774             });
92775             return ret;
92776         }
92777         function collectLibs(sourceFile, ret) {
92778             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
92779                 var lib = host.getLibFileFromReference(ref);
92780                 if (lib) {
92781                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
92782                 }
92783             });
92784             return ret;
92785         }
92786         function filterBindingPatternInitializers(name) {
92787             if (name.kind === 75 /* Identifier */) {
92788                 return name;
92789             }
92790             else {
92791                 if (name.kind === 190 /* ArrayBindingPattern */) {
92792                     return ts.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92793                 }
92794                 else {
92795                     return ts.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
92796                 }
92797             }
92798             function visitBindingElement(elem) {
92799                 if (elem.kind === 215 /* OmittedExpression */) {
92800                     return elem;
92801                 }
92802                 return ts.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
92803             }
92804         }
92805         function ensureParameter(p, modifierMask, type) {
92806             var oldDiag;
92807             if (!suppressNewDiagnosticContexts) {
92808                 oldDiag = getSymbolAccessibilityDiagnostic;
92809                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
92810             }
92811             var newParam = ts.updateParameter(p, 
92812             /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || ts.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
92813             ensureNoInitializer(p));
92814             if (!suppressNewDiagnosticContexts) {
92815                 getSymbolAccessibilityDiagnostic = oldDiag;
92816             }
92817             return newParam;
92818         }
92819         function shouldPrintWithInitializer(node) {
92820             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
92821         }
92822         function ensureNoInitializer(node) {
92823             if (shouldPrintWithInitializer(node)) {
92824                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
92825             }
92826             return undefined;
92827         }
92828         function ensureType(node, type, ignorePrivate) {
92829             if (!ignorePrivate && ts.hasModifier(node, 8 /* Private */)) {
92830                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
92831                 return;
92832             }
92833             if (shouldPrintWithInitializer(node)) {
92834                 // Literal const declarations will have an initializer ensured rather than a type
92835                 return;
92836             }
92837             var shouldUseResolverType = node.kind === 156 /* Parameter */ &&
92838                 (resolver.isRequiredInitializedParameter(node) ||
92839                     resolver.isOptionalUninitializedParameterProperty(node));
92840             if (type && !shouldUseResolverType) {
92841                 return ts.visitNode(type, visitDeclarationSubtree);
92842             }
92843             if (!ts.getParseTreeNode(node)) {
92844                 return type ? ts.visitNode(type, visitDeclarationSubtree) : ts.createKeywordTypeNode(125 /* AnyKeyword */);
92845             }
92846             if (node.kind === 164 /* SetAccessor */) {
92847                 // 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
92848                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
92849                 return ts.createKeywordTypeNode(125 /* AnyKeyword */);
92850             }
92851             errorNameNode = node.name;
92852             var oldDiag;
92853             if (!suppressNewDiagnosticContexts) {
92854                 oldDiag = getSymbolAccessibilityDiagnostic;
92855                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
92856             }
92857             if (node.kind === 242 /* VariableDeclaration */ || node.kind === 191 /* BindingElement */) {
92858                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92859             }
92860             if (node.kind === 156 /* Parameter */
92861                 || node.kind === 159 /* PropertyDeclaration */
92862                 || node.kind === 158 /* PropertySignature */) {
92863                 if (!node.initializer)
92864                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
92865                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92866             }
92867             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
92868             function cleanup(returnValue) {
92869                 errorNameNode = undefined;
92870                 if (!suppressNewDiagnosticContexts) {
92871                     getSymbolAccessibilityDiagnostic = oldDiag;
92872                 }
92873                 return returnValue || ts.createKeywordTypeNode(125 /* AnyKeyword */);
92874             }
92875         }
92876         function isDeclarationAndNotVisible(node) {
92877             node = ts.getParseTreeNode(node);
92878             switch (node.kind) {
92879                 case 244 /* FunctionDeclaration */:
92880                 case 249 /* ModuleDeclaration */:
92881                 case 246 /* InterfaceDeclaration */:
92882                 case 245 /* ClassDeclaration */:
92883                 case 247 /* TypeAliasDeclaration */:
92884                 case 248 /* EnumDeclaration */:
92885                     return !resolver.isDeclarationVisible(node);
92886                 // The following should be doing their own visibility checks based on filtering their members
92887                 case 242 /* VariableDeclaration */:
92888                     return !getBindingNameVisible(node);
92889                 case 253 /* ImportEqualsDeclaration */:
92890                 case 254 /* ImportDeclaration */:
92891                 case 260 /* ExportDeclaration */:
92892                 case 259 /* ExportAssignment */:
92893                     return false;
92894             }
92895             return false;
92896         }
92897         function getBindingNameVisible(elem) {
92898             if (ts.isOmittedExpression(elem)) {
92899                 return false;
92900             }
92901             if (ts.isBindingPattern(elem.name)) {
92902                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
92903                 return ts.some(elem.name.elements, getBindingNameVisible);
92904             }
92905             else {
92906                 return resolver.isDeclarationVisible(elem);
92907             }
92908         }
92909         function updateParamsList(node, params, modifierMask) {
92910             if (ts.hasModifier(node, 8 /* Private */)) {
92911                 return undefined; // TODO: GH#18217
92912             }
92913             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
92914             if (!newParams) {
92915                 return undefined; // TODO: GH#18217
92916             }
92917             return ts.createNodeArray(newParams, params.hasTrailingComma);
92918         }
92919         function updateAccessorParamsList(input, isPrivate) {
92920             var newParams;
92921             if (!isPrivate) {
92922                 var thisParameter = ts.getThisParameter(input);
92923                 if (thisParameter) {
92924                     newParams = [ensureParameter(thisParameter)];
92925                 }
92926             }
92927             if (ts.isSetAccessorDeclaration(input)) {
92928                 var newValueParameter = void 0;
92929                 if (!isPrivate) {
92930                     var valueParameter = ts.getSetAccessorValueParameter(input);
92931                     if (valueParameter) {
92932                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
92933                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
92934                     }
92935                 }
92936                 if (!newValueParameter) {
92937                     newValueParameter = ts.createParameter(
92938                     /*decorators*/ undefined, 
92939                     /*modifiers*/ undefined, 
92940                     /*dotDotDotToken*/ undefined, "value");
92941                 }
92942                 newParams = ts.append(newParams, newValueParameter);
92943             }
92944             return ts.createNodeArray(newParams || ts.emptyArray);
92945         }
92946         function ensureTypeParams(node, params) {
92947             return ts.hasModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
92948         }
92949         function isEnclosingDeclaration(node) {
92950             return ts.isSourceFile(node)
92951                 || ts.isTypeAliasDeclaration(node)
92952                 || ts.isModuleDeclaration(node)
92953                 || ts.isClassDeclaration(node)
92954                 || ts.isInterfaceDeclaration(node)
92955                 || ts.isFunctionLike(node)
92956                 || ts.isIndexSignatureDeclaration(node)
92957                 || ts.isMappedTypeNode(node);
92958         }
92959         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
92960             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
92961             handleSymbolAccessibilityError(visibilityResult);
92962             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
92963         }
92964         function preserveJsDoc(updated, original) {
92965             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
92966                 updated.jsDoc = original.jsDoc;
92967             }
92968             return ts.setCommentRange(updated, ts.getCommentRange(original));
92969         }
92970         function rewriteModuleSpecifier(parent, input) {
92971             if (!input)
92972                 return undefined; // TODO: GH#18217
92973             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 249 /* ModuleDeclaration */ && parent.kind !== 188 /* ImportType */);
92974             if (ts.isStringLiteralLike(input)) {
92975                 if (isBundledEmit) {
92976                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
92977                     if (newName) {
92978                         return ts.createLiteral(newName);
92979                     }
92980                 }
92981                 else {
92982                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
92983                     if (symbol) {
92984                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
92985                     }
92986                 }
92987             }
92988             return input;
92989         }
92990         function transformImportEqualsDeclaration(decl) {
92991             if (!resolver.isDeclarationVisible(decl))
92992                 return;
92993             if (decl.moduleReference.kind === 265 /* ExternalModuleReference */) {
92994                 // Rewrite external module names if necessary
92995                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
92996                 return ts.updateImportEqualsDeclaration(decl, 
92997                 /*decorators*/ undefined, decl.modifiers, decl.name, ts.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
92998             }
92999             else {
93000                 var oldDiag = getSymbolAccessibilityDiagnostic;
93001                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
93002                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
93003                 getSymbolAccessibilityDiagnostic = oldDiag;
93004                 return decl;
93005             }
93006         }
93007         function transformImportDeclaration(decl) {
93008             if (!decl.importClause) {
93009                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
93010                 return ts.updateImportDeclaration(decl, 
93011                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93012             }
93013             // The `importClause` visibility corresponds to the default's visibility.
93014             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
93015             if (!decl.importClause.namedBindings) {
93016                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
93017                 return visibleDefaultBinding && ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, 
93018                 /*namedBindings*/ undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93019             }
93020             if (decl.importClause.namedBindings.kind === 256 /* NamespaceImport */) {
93021                 // Namespace import (optionally with visible default)
93022                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
93023                 return visibleDefaultBinding || namedBindings ? ts.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, namedBindings, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
93024             }
93025             // Named imports (optionally with visible default)
93026             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
93027             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
93028                 return ts.updateImportDeclaration(decl, 
93029                 /*decorators*/ undefined, decl.modifiers, ts.updateImportClause(decl.importClause, visibleDefaultBinding, bindingList && bindingList.length ? ts.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined, decl.importClause.isTypeOnly), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93030             }
93031             // Augmentation of export depends on import
93032             if (resolver.isImportRequiredByAugmentation(decl)) {
93033                 return ts.updateImportDeclaration(decl, 
93034                 /*decorators*/ undefined, decl.modifiers, 
93035                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
93036             }
93037             // Nothing visible
93038         }
93039         function transformAndReplaceLatePaintedStatements(statements) {
93040             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
93041             // error handling which must now be included in the output and themselves checked for errors.
93042             // For example:
93043             // ```
93044             // module A {
93045             //   export module Q {}
93046             //   import B = Q;
93047             //   import C = B;
93048             //   export import D = C;
93049             // }
93050             // ```
93051             // 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
93052             // 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
93053             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
93054             while (ts.length(lateMarkedStatements)) {
93055                 var i = lateMarkedStatements.shift();
93056                 if (!ts.isLateVisibilityPaintedStatement(i)) {
93057                     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));
93058                 }
93059                 var priorNeedsDeclare = needsDeclare;
93060                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
93061                 var result = transformTopLevelDeclaration(i);
93062                 needsDeclare = priorNeedsDeclare;
93063                 lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result);
93064             }
93065             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
93066             // (and remove them from the set to examine for outter declarations)
93067             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
93068             function visitLateVisibilityMarkedStatements(statement) {
93069                 if (ts.isLateVisibilityPaintedStatement(statement)) {
93070                     var key = "" + ts.getOriginalNodeId(statement);
93071                     if (lateStatementReplacementMap.has(key)) {
93072                         var result = lateStatementReplacementMap.get(key);
93073                         lateStatementReplacementMap.delete(key);
93074                         if (result) {
93075                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
93076                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
93077                                 needsScopeFixMarker = true;
93078                             }
93079                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
93080                                 resultHasExternalModuleIndicator = true;
93081                             }
93082                         }
93083                         return result;
93084                     }
93085                 }
93086                 return statement;
93087             }
93088         }
93089         function visitDeclarationSubtree(input) {
93090             if (shouldStripInternal(input))
93091                 return;
93092             if (ts.isDeclaration(input)) {
93093                 if (isDeclarationAndNotVisible(input))
93094                     return;
93095                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
93096                     return;
93097                 }
93098             }
93099             // Elide implementation signatures from overload sets
93100             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93101                 return;
93102             // Elide semicolon class statements
93103             if (ts.isSemicolonClassElement(input))
93104                 return;
93105             var previousEnclosingDeclaration;
93106             if (isEnclosingDeclaration(input)) {
93107                 previousEnclosingDeclaration = enclosingDeclaration;
93108                 enclosingDeclaration = input;
93109             }
93110             var oldDiag = getSymbolAccessibilityDiagnostic;
93111             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
93112             // We'd see a TDZ violation at runtime
93113             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
93114             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
93115             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 173 /* TypeLiteral */ || input.kind === 186 /* MappedType */) && input.parent.kind !== 247 /* TypeAliasDeclaration */);
93116             // Emit methods which are private as properties with no type information
93117             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
93118                 if (ts.hasModifier(input, 8 /* Private */)) {
93119                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
93120                         return; // Elide all but the first overload
93121                     return cleanup(ts.createProperty(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
93122                 }
93123             }
93124             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93125                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93126             }
93127             if (ts.isTypeQueryNode(input)) {
93128                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
93129             }
93130             if (shouldEnterSuppressNewDiagnosticsContextContext) {
93131                 // 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.
93132                 suppressNewDiagnosticContexts = true;
93133             }
93134             if (isProcessedComponent(input)) {
93135                 switch (input.kind) {
93136                     case 216 /* ExpressionWithTypeArguments */: {
93137                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
93138                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
93139                         }
93140                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93141                         return cleanup(ts.updateExpressionWithTypeArguments(node, ts.parenthesizeTypeParameters(node.typeArguments), node.expression));
93142                     }
93143                     case 169 /* TypeReference */: {
93144                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
93145                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
93146                         return cleanup(ts.updateTypeReferenceNode(node, node.typeName, ts.parenthesizeTypeParameters(node.typeArguments)));
93147                     }
93148                     case 166 /* ConstructSignature */:
93149                         return cleanup(ts.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93150                     case 162 /* Constructor */: {
93151                         // A constructor declaration may not have a type annotation
93152                         var ctor = ts.createSignatureDeclaration(162 /* Constructor */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters, 0 /* None */), 
93153                         /*type*/ undefined);
93154                         ctor.modifiers = ts.createNodeArray(ensureModifiers(input));
93155                         return cleanup(ctor);
93156                     }
93157                     case 161 /* MethodDeclaration */: {
93158                         if (ts.isPrivateIdentifier(input.name)) {
93159                             return cleanup(/*returnValue*/ undefined);
93160                         }
93161                         var sig = ts.createSignatureDeclaration(160 /* MethodSignature */, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type));
93162                         sig.name = input.name;
93163                         sig.modifiers = ts.createNodeArray(ensureModifiers(input));
93164                         sig.questionToken = input.questionToken;
93165                         return cleanup(sig);
93166                     }
93167                     case 163 /* GetAccessor */: {
93168                         if (ts.isPrivateIdentifier(input.name)) {
93169                             return cleanup(/*returnValue*/ undefined);
93170                         }
93171                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
93172                         return cleanup(ts.updateGetAccessor(input, 
93173                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
93174                         /*body*/ undefined));
93175                     }
93176                     case 164 /* SetAccessor */: {
93177                         if (ts.isPrivateIdentifier(input.name)) {
93178                             return cleanup(/*returnValue*/ undefined);
93179                         }
93180                         return cleanup(ts.updateSetAccessor(input, 
93181                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasModifier(input, 8 /* Private */)), 
93182                         /*body*/ undefined));
93183                     }
93184                     case 159 /* PropertyDeclaration */:
93185                         if (ts.isPrivateIdentifier(input.name)) {
93186                             return cleanup(/*returnValue*/ undefined);
93187                         }
93188                         return cleanup(ts.updateProperty(input, 
93189                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93190                     case 158 /* PropertySignature */:
93191                         if (ts.isPrivateIdentifier(input.name)) {
93192                             return cleanup(/*returnValue*/ undefined);
93193                         }
93194                         return cleanup(ts.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
93195                     case 160 /* MethodSignature */: {
93196                         if (ts.isPrivateIdentifier(input.name)) {
93197                             return cleanup(/*returnValue*/ undefined);
93198                         }
93199                         return cleanup(ts.updateMethodSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), input.name, input.questionToken));
93200                     }
93201                     case 165 /* CallSignature */: {
93202                         return cleanup(ts.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
93203                     }
93204                     case 167 /* IndexSignature */: {
93205                         return cleanup(ts.updateIndexSignature(input, 
93206                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || ts.createKeywordTypeNode(125 /* AnyKeyword */)));
93207                     }
93208                     case 242 /* VariableDeclaration */: {
93209                         if (ts.isBindingPattern(input.name)) {
93210                             return recreateBindingPattern(input.name);
93211                         }
93212                         shouldEnterSuppressNewDiagnosticsContextContext = true;
93213                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
93214                         return cleanup(ts.updateTypeScriptVariableDeclaration(input, input.name, /*exclaimationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
93215                     }
93216                     case 155 /* TypeParameter */: {
93217                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
93218                             return cleanup(ts.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
93219                         }
93220                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93221                     }
93222                     case 180 /* ConditionalType */: {
93223                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
93224                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
93225                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
93226                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
93227                         var oldEnclosingDecl = enclosingDeclaration;
93228                         enclosingDeclaration = input.trueType;
93229                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
93230                         enclosingDeclaration = oldEnclosingDecl;
93231                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
93232                         return cleanup(ts.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
93233                     }
93234                     case 170 /* FunctionType */: {
93235                         return cleanup(ts.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93236                     }
93237                     case 171 /* ConstructorType */: {
93238                         return cleanup(ts.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
93239                     }
93240                     case 188 /* ImportType */: {
93241                         if (!ts.isLiteralImportTypeNode(input))
93242                             return cleanup(input);
93243                         return cleanup(ts.updateImportTypeNode(input, ts.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf));
93244                     }
93245                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
93246                 }
93247             }
93248             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
93249             function cleanup(returnValue) {
93250                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
93251                     checkName(input);
93252                 }
93253                 if (isEnclosingDeclaration(input)) {
93254                     enclosingDeclaration = previousEnclosingDeclaration;
93255                 }
93256                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
93257                     getSymbolAccessibilityDiagnostic = oldDiag;
93258                 }
93259                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
93260                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
93261                 }
93262                 if (returnValue === input) {
93263                     return returnValue;
93264                 }
93265                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
93266             }
93267         }
93268         function isPrivateMethodTypeParameter(node) {
93269             return node.parent.kind === 161 /* MethodDeclaration */ && ts.hasModifier(node.parent, 8 /* Private */);
93270         }
93271         function visitDeclarationStatements(input) {
93272             if (!isPreservedDeclarationStatement(input)) {
93273                 // return undefined for unmatched kinds to omit them from the tree
93274                 return;
93275             }
93276             if (shouldStripInternal(input))
93277                 return;
93278             switch (input.kind) {
93279                 case 260 /* ExportDeclaration */: {
93280                     if (ts.isSourceFile(input.parent)) {
93281                         resultHasExternalModuleIndicator = true;
93282                     }
93283                     resultHasScopeMarker = true;
93284                     // Always visible if the parent node isn't dropped for being not visible
93285                     // Rewrite external module names if necessary
93286                     return ts.updateExportDeclaration(input, 
93287                     /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier), input.isTypeOnly);
93288                 }
93289                 case 259 /* ExportAssignment */: {
93290                     // Always visible if the parent node isn't dropped for being not visible
93291                     if (ts.isSourceFile(input.parent)) {
93292                         resultHasExternalModuleIndicator = true;
93293                     }
93294                     resultHasScopeMarker = true;
93295                     if (input.expression.kind === 75 /* Identifier */) {
93296                         return input;
93297                     }
93298                     else {
93299                         var newId = ts.createOptimisticUniqueName("_default");
93300                         getSymbolAccessibilityDiagnostic = function () { return ({
93301                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
93302                             errorNode: input
93303                         }); };
93304                         var varDecl = ts.createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93305                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93306                         return [statement, ts.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
93307                     }
93308                 }
93309             }
93310             var result = transformTopLevelDeclaration(input);
93311             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
93312             lateStatementReplacementMap.set("" + ts.getOriginalNodeId(input), result);
93313             return input;
93314         }
93315         function stripExportModifiers(statement) {
93316             if (ts.isImportEqualsDeclaration(statement) || ts.hasModifier(statement, 512 /* Default */)) {
93317                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
93318                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
93319                 return statement;
93320             }
93321             var clone = ts.getMutableClone(statement);
93322             var modifiers = ts.createModifiersFromModifierFlags(ts.getModifierFlags(statement) & (3071 /* All */ ^ 1 /* Export */));
93323             clone.modifiers = modifiers.length ? ts.createNodeArray(modifiers) : undefined;
93324             return clone;
93325         }
93326         function transformTopLevelDeclaration(input) {
93327             if (shouldStripInternal(input))
93328                 return;
93329             switch (input.kind) {
93330                 case 253 /* ImportEqualsDeclaration */: {
93331                     return transformImportEqualsDeclaration(input);
93332                 }
93333                 case 254 /* ImportDeclaration */: {
93334                     return transformImportDeclaration(input);
93335                 }
93336             }
93337             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
93338                 return;
93339             // Elide implementation signatures from overload sets
93340             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
93341                 return;
93342             var previousEnclosingDeclaration;
93343             if (isEnclosingDeclaration(input)) {
93344                 previousEnclosingDeclaration = enclosingDeclaration;
93345                 enclosingDeclaration = input;
93346             }
93347             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
93348             var oldDiag = getSymbolAccessibilityDiagnostic;
93349             if (canProdiceDiagnostic) {
93350                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
93351             }
93352             var previousNeedsDeclare = needsDeclare;
93353             switch (input.kind) {
93354                 case 247 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
93355                     return cleanup(ts.updateTypeAliasDeclaration(input, 
93356                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
93357                 case 246 /* InterfaceDeclaration */: {
93358                     return cleanup(ts.updateInterfaceDeclaration(input, 
93359                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
93360                 }
93361                 case 244 /* FunctionDeclaration */: {
93362                     // Generators lose their generator-ness, excepting their return type
93363                     var clean = cleanup(ts.updateFunctionDeclaration(input, 
93364                     /*decorators*/ undefined, ensureModifiers(input), 
93365                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
93366                     /*body*/ undefined));
93367                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
93368                         var props = resolver.getPropertiesOfContainerFunction(input);
93369                         var fakespace_1 = ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || ts.createIdentifier("_default"), ts.createModuleBlock([]), 16 /* Namespace */);
93370                         fakespace_1.flags ^= 8 /* Synthesized */; // unset synthesized so it is usable as an enclosing declaration
93371                         fakespace_1.parent = enclosingDeclaration;
93372                         fakespace_1.locals = ts.createSymbolTable(props);
93373                         fakespace_1.symbol = props[0].parent;
93374                         var declarations = ts.mapDefined(props, function (p) {
93375                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
93376                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
93377                             }
93378                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
93379                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
93380                             getSymbolAccessibilityDiagnostic = oldDiag;
93381                             var varDecl = ts.createVariableDeclaration(ts.unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined);
93382                             return ts.createVariableStatement(/*modifiers*/ undefined, ts.createVariableDeclarationList([varDecl]));
93383                         });
93384                         var namespaceDecl = ts.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, ts.createModuleBlock(declarations), 16 /* Namespace */);
93385                         if (!ts.hasModifier(clean, 512 /* Default */)) {
93386                             return [clean, namespaceDecl];
93387                         }
93388                         var modifiers = ts.createModifiersFromModifierFlags((ts.getModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
93389                         var cleanDeclaration = ts.updateFunctionDeclaration(clean, 
93390                         /*decorators*/ undefined, modifiers, 
93391                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
93392                         /*body*/ undefined);
93393                         var namespaceDeclaration = ts.updateModuleDeclaration(namespaceDecl, 
93394                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
93395                         var exportDefaultDeclaration = ts.createExportAssignment(
93396                         /*decorators*/ undefined, 
93397                         /*modifiers*/ undefined, 
93398                         /*isExportEquals*/ false, namespaceDecl.name);
93399                         if (ts.isSourceFile(input.parent)) {
93400                             resultHasExternalModuleIndicator = true;
93401                         }
93402                         resultHasScopeMarker = true;
93403                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
93404                     }
93405                     else {
93406                         return clean;
93407                     }
93408                 }
93409                 case 249 /* ModuleDeclaration */: {
93410                     needsDeclare = false;
93411                     var inner = input.body;
93412                     if (inner && inner.kind === 250 /* ModuleBlock */) {
93413                         var oldNeedsScopeFix = needsScopeFixMarker;
93414                         var oldHasScopeFix = resultHasScopeMarker;
93415                         resultHasScopeMarker = false;
93416                         needsScopeFixMarker = false;
93417                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
93418                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
93419                         if (input.flags & 8388608 /* Ambient */) {
93420                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
93421                         }
93422                         // With the final list of statements, there are 3 possibilities:
93423                         // 1. There's an export assignment or export declaration in the namespace - do nothing
93424                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
93425                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
93426                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
93427                             if (needsScopeFixMarker) {
93428                                 lateStatements = ts.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports()]));
93429                             }
93430                             else {
93431                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
93432                             }
93433                         }
93434                         var body = ts.updateModuleBlock(inner, lateStatements);
93435                         needsDeclare = previousNeedsDeclare;
93436                         needsScopeFixMarker = oldNeedsScopeFix;
93437                         resultHasScopeMarker = oldHasScopeFix;
93438                         var mods = ensureModifiers(input);
93439                         return cleanup(ts.updateModuleDeclaration(input, 
93440                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
93441                     }
93442                     else {
93443                         needsDeclare = previousNeedsDeclare;
93444                         var mods = ensureModifiers(input);
93445                         needsDeclare = false;
93446                         ts.visitNode(inner, visitDeclarationStatements);
93447                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
93448                         var id = "" + ts.getOriginalNodeId(inner); // TODO: GH#18217
93449                         var body = lateStatementReplacementMap.get(id);
93450                         lateStatementReplacementMap.delete(id);
93451                         return cleanup(ts.updateModuleDeclaration(input, 
93452                         /*decorators*/ undefined, mods, input.name, body));
93453                     }
93454                 }
93455                 case 245 /* ClassDeclaration */: {
93456                     var modifiers = ts.createNodeArray(ensureModifiers(input));
93457                     var typeParameters = ensureTypeParams(input, input.typeParameters);
93458                     var ctor = ts.getFirstConstructorWithBody(input);
93459                     var parameterProperties = void 0;
93460                     if (ctor) {
93461                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
93462                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
93463                             if (!ts.hasModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
93464                                 return;
93465                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
93466                             if (param.name.kind === 75 /* Identifier */) {
93467                                 return preserveJsDoc(ts.createProperty(
93468                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
93469                             }
93470                             else {
93471                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
93472                                 return walkBindingPattern(param.name);
93473                             }
93474                             function walkBindingPattern(pattern) {
93475                                 var elems;
93476                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
93477                                     var elem = _a[_i];
93478                                     if (ts.isOmittedExpression(elem))
93479                                         continue;
93480                                     if (ts.isBindingPattern(elem.name)) {
93481                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
93482                                     }
93483                                     elems = elems || [];
93484                                     elems.push(ts.createProperty(
93485                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
93486                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
93487                                     /*initializer*/ undefined));
93488                                 }
93489                                 return elems;
93490                             }
93491                         }));
93492                         getSymbolAccessibilityDiagnostic = oldDiag_1;
93493                     }
93494                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
93495                     var privateIdentifier = hasPrivateIdentifier ? [
93496                         ts.createProperty(
93497                         /*decorators*/ undefined, 
93498                         /*modifiers*/ undefined, ts.createPrivateIdentifier("#private"), 
93499                         /*questionToken*/ undefined, 
93500                         /*type*/ undefined, 
93501                         /*initializer*/ undefined)
93502                     ] : undefined;
93503                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
93504                     var members = ts.createNodeArray(memberNodes);
93505                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
93506                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 100 /* NullKeyword */) {
93507                         // We must add a temporary declaration for the extends clause expression
93508                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
93509                         var newId_1 = ts.createOptimisticUniqueName(oldId + "_base");
93510                         getSymbolAccessibilityDiagnostic = function () { return ({
93511                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
93512                             errorNode: extendsClause_1,
93513                             typeName: input.name
93514                         }); };
93515                         var varDecl = ts.createVariableDeclaration(newId_1, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
93516                         var statement = ts.createVariableStatement(needsDeclare ? [ts.createModifier(130 /* DeclareKeyword */)] : [], ts.createVariableDeclarationList([varDecl], 2 /* Const */));
93517                         var heritageClauses = ts.createNodeArray(ts.map(input.heritageClauses, function (clause) {
93518                             if (clause.token === 90 /* ExtendsKeyword */) {
93519                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
93520                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
93521                                 var newClause = ts.updateHeritageClause(clause, ts.map(clause.types, function (t) { return ts.updateExpressionWithTypeArguments(t, ts.visitNodes(t.typeArguments, visitDeclarationSubtree), newId_1); }));
93522                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
93523                                 return newClause;
93524                             }
93525                             return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 100 /* NullKeyword */; })), visitDeclarationSubtree));
93526                         }));
93527                         return [statement, cleanup(ts.updateClassDeclaration(input, 
93528                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
93529                     }
93530                     else {
93531                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
93532                         return cleanup(ts.updateClassDeclaration(input, 
93533                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
93534                     }
93535                 }
93536                 case 225 /* VariableStatement */: {
93537                     return cleanup(transformVariableStatement(input));
93538                 }
93539                 case 248 /* EnumDeclaration */: {
93540                     return cleanup(ts.updateEnumDeclaration(input, /*decorators*/ undefined, ts.createNodeArray(ensureModifiers(input)), input.name, ts.createNodeArray(ts.mapDefined(input.members, function (m) {
93541                         if (shouldStripInternal(m))
93542                             return;
93543                         // Rewrite enum values to their constants, if available
93544                         var constValue = resolver.getConstantValue(m);
93545                         return preserveJsDoc(ts.updateEnumMember(m, m.name, constValue !== undefined ? ts.createLiteral(constValue) : undefined), m);
93546                     }))));
93547                 }
93548             }
93549             // Anything left unhandled is an error, so this should be unreachable
93550             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
93551             function cleanup(node) {
93552                 if (isEnclosingDeclaration(input)) {
93553                     enclosingDeclaration = previousEnclosingDeclaration;
93554                 }
93555                 if (canProdiceDiagnostic) {
93556                     getSymbolAccessibilityDiagnostic = oldDiag;
93557                 }
93558                 if (input.kind === 249 /* ModuleDeclaration */) {
93559                     needsDeclare = previousNeedsDeclare;
93560                 }
93561                 if (node === input) {
93562                     return node;
93563                 }
93564                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
93565             }
93566         }
93567         function transformVariableStatement(input) {
93568             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
93569                 return;
93570             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
93571             if (!ts.length(nodes))
93572                 return;
93573             return ts.updateVariableStatement(input, ts.createNodeArray(ensureModifiers(input)), ts.updateVariableDeclarationList(input.declarationList, nodes));
93574         }
93575         function recreateBindingPattern(d) {
93576             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
93577         }
93578         function recreateBindingElement(e) {
93579             if (e.kind === 215 /* OmittedExpression */) {
93580                 return;
93581             }
93582             if (e.name) {
93583                 if (!getBindingNameVisible(e))
93584                     return;
93585                 if (ts.isBindingPattern(e.name)) {
93586                     return recreateBindingPattern(e.name);
93587                 }
93588                 else {
93589                     return ts.createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
93590                 }
93591             }
93592         }
93593         function checkName(node) {
93594             var oldDiag;
93595             if (!suppressNewDiagnosticContexts) {
93596                 oldDiag = getSymbolAccessibilityDiagnostic;
93597                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
93598             }
93599             errorNameNode = node.name;
93600             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
93601             var decl = node;
93602             var entityName = decl.name.expression;
93603             checkEntityNameVisibility(entityName, enclosingDeclaration);
93604             if (!suppressNewDiagnosticContexts) {
93605                 getSymbolAccessibilityDiagnostic = oldDiag;
93606             }
93607             errorNameNode = undefined;
93608         }
93609         function shouldStripInternal(node) {
93610             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
93611         }
93612         function isScopeMarker(node) {
93613             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
93614         }
93615         function hasScopeMarker(statements) {
93616             return ts.some(statements, isScopeMarker);
93617         }
93618         function ensureModifiers(node) {
93619             var currentFlags = ts.getModifierFlags(node);
93620             var newFlags = ensureModifierFlags(node);
93621             if (currentFlags === newFlags) {
93622                 return node.modifiers;
93623             }
93624             return ts.createModifiersFromModifierFlags(newFlags);
93625         }
93626         function ensureModifierFlags(node) {
93627             var mask = 3071 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
93628             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
93629             var parentIsFile = node.parent.kind === 290 /* SourceFile */;
93630             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
93631                 mask ^= 2 /* Ambient */;
93632                 additions = 0 /* None */;
93633             }
93634             return maskModifierFlags(node, mask, additions);
93635         }
93636         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
93637             var accessorType = getTypeAnnotationFromAccessor(node);
93638             if (!accessorType && node !== accessors.firstAccessor) {
93639                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
93640                 // 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
93641                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
93642             }
93643             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
93644                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
93645                 // 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
93646                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
93647             }
93648             return accessorType;
93649         }
93650         function transformHeritageClauses(nodes) {
93651             return ts.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return ts.updateHeritageClause(clause, ts.visitNodes(ts.createNodeArray(ts.filter(clause.types, function (t) {
93652                 return ts.isEntityNameExpression(t.expression) || (clause.token === 90 /* ExtendsKeyword */ && t.expression.kind === 100 /* NullKeyword */);
93653             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
93654         }
93655     }
93656     ts.transformDeclarations = transformDeclarations;
93657     function isAlwaysType(node) {
93658         if (node.kind === 246 /* InterfaceDeclaration */) {
93659             return true;
93660         }
93661         return false;
93662     }
93663     // Elide "public" modifier, as it is the default
93664     function maskModifiers(node, modifierMask, modifierAdditions) {
93665         return ts.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
93666     }
93667     function maskModifierFlags(node, modifierMask, modifierAdditions) {
93668         if (modifierMask === void 0) { modifierMask = 3071 /* All */ ^ 4 /* Public */; }
93669         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
93670         var flags = (ts.getModifierFlags(node) & modifierMask) | modifierAdditions;
93671         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
93672             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
93673             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
93674             flags ^= 1 /* Export */;
93675         }
93676         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
93677             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
93678         }
93679         return flags;
93680     }
93681     function getTypeAnnotationFromAccessor(accessor) {
93682         if (accessor) {
93683             return accessor.kind === 163 /* GetAccessor */
93684                 ? accessor.type // Getter - return type
93685                 : accessor.parameters.length > 0
93686                     ? accessor.parameters[0].type // Setter parameter type
93687                     : undefined;
93688         }
93689     }
93690     function canHaveLiteralInitializer(node) {
93691         switch (node.kind) {
93692             case 159 /* PropertyDeclaration */:
93693             case 158 /* PropertySignature */:
93694                 return !ts.hasModifier(node, 8 /* Private */);
93695             case 156 /* Parameter */:
93696             case 242 /* VariableDeclaration */:
93697                 return true;
93698         }
93699         return false;
93700     }
93701     function isPreservedDeclarationStatement(node) {
93702         switch (node.kind) {
93703             case 244 /* FunctionDeclaration */:
93704             case 249 /* ModuleDeclaration */:
93705             case 253 /* ImportEqualsDeclaration */:
93706             case 246 /* InterfaceDeclaration */:
93707             case 245 /* ClassDeclaration */:
93708             case 247 /* TypeAliasDeclaration */:
93709             case 248 /* EnumDeclaration */:
93710             case 225 /* VariableStatement */:
93711             case 254 /* ImportDeclaration */:
93712             case 260 /* ExportDeclaration */:
93713             case 259 /* ExportAssignment */:
93714                 return true;
93715         }
93716         return false;
93717     }
93718     function isProcessedComponent(node) {
93719         switch (node.kind) {
93720             case 166 /* ConstructSignature */:
93721             case 162 /* Constructor */:
93722             case 161 /* MethodDeclaration */:
93723             case 163 /* GetAccessor */:
93724             case 164 /* SetAccessor */:
93725             case 159 /* PropertyDeclaration */:
93726             case 158 /* PropertySignature */:
93727             case 160 /* MethodSignature */:
93728             case 165 /* CallSignature */:
93729             case 167 /* IndexSignature */:
93730             case 242 /* VariableDeclaration */:
93731             case 155 /* TypeParameter */:
93732             case 216 /* ExpressionWithTypeArguments */:
93733             case 169 /* TypeReference */:
93734             case 180 /* ConditionalType */:
93735             case 170 /* FunctionType */:
93736             case 171 /* ConstructorType */:
93737             case 188 /* ImportType */:
93738                 return true;
93739         }
93740         return false;
93741     }
93742 })(ts || (ts = {}));
93743 /* @internal */
93744 var ts;
93745 (function (ts) {
93746     function getModuleTransformer(moduleKind) {
93747         switch (moduleKind) {
93748             case ts.ModuleKind.ESNext:
93749             case ts.ModuleKind.ES2020:
93750             case ts.ModuleKind.ES2015:
93751                 return ts.transformECMAScriptModule;
93752             case ts.ModuleKind.System:
93753                 return ts.transformSystemModule;
93754             default:
93755                 return ts.transformModule;
93756         }
93757     }
93758     var TransformationState;
93759     (function (TransformationState) {
93760         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
93761         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
93762         TransformationState[TransformationState["Completed"] = 2] = "Completed";
93763         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
93764     })(TransformationState || (TransformationState = {}));
93765     var SyntaxKindFeatureFlags;
93766     (function (SyntaxKindFeatureFlags) {
93767         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
93768         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
93769     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
93770     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
93771     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93772         return {
93773             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
93774             declarationTransformers: getDeclarationTransformers(customTransformers),
93775         };
93776     }
93777     ts.getTransformers = getTransformers;
93778     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
93779         if (emitOnlyDtsFiles)
93780             return ts.emptyArray;
93781         var jsx = compilerOptions.jsx;
93782         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93783         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93784         var transformers = [];
93785         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
93786         transformers.push(ts.transformTypeScript);
93787         transformers.push(ts.transformClassFields);
93788         if (jsx === 2 /* React */) {
93789             transformers.push(ts.transformJsx);
93790         }
93791         if (languageVersion < 99 /* ESNext */) {
93792             transformers.push(ts.transformESNext);
93793         }
93794         if (languageVersion < 7 /* ES2020 */) {
93795             transformers.push(ts.transformES2020);
93796         }
93797         if (languageVersion < 6 /* ES2019 */) {
93798             transformers.push(ts.transformES2019);
93799         }
93800         if (languageVersion < 5 /* ES2018 */) {
93801             transformers.push(ts.transformES2018);
93802         }
93803         if (languageVersion < 4 /* ES2017 */) {
93804             transformers.push(ts.transformES2017);
93805         }
93806         if (languageVersion < 3 /* ES2016 */) {
93807             transformers.push(ts.transformES2016);
93808         }
93809         if (languageVersion < 2 /* ES2015 */) {
93810             transformers.push(ts.transformES2015);
93811             transformers.push(ts.transformGenerators);
93812         }
93813         transformers.push(getModuleTransformer(moduleKind));
93814         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
93815         // for ES3.
93816         if (languageVersion < 1 /* ES5 */) {
93817             transformers.push(ts.transformES5);
93818         }
93819         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
93820         return transformers;
93821     }
93822     function getDeclarationTransformers(customTransformers) {
93823         var transformers = [];
93824         transformers.push(ts.transformDeclarations);
93825         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
93826         return transformers;
93827     }
93828     /**
93829      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
93830      */
93831     function wrapCustomTransformer(transformer) {
93832         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
93833     }
93834     /**
93835      * Wrap a transformer factory that may return a custom script or declaration transformer object.
93836      */
93837     function wrapCustomTransformerFactory(transformer, handleDefault) {
93838         return function (context) {
93839             var customTransformer = transformer(context);
93840             return typeof customTransformer === "function"
93841                 ? handleDefault(customTransformer)
93842                 : wrapCustomTransformer(customTransformer);
93843         };
93844     }
93845     function wrapScriptTransformerFactory(transformer) {
93846         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
93847     }
93848     function wrapDeclarationTransformerFactory(transformer) {
93849         return wrapCustomTransformerFactory(transformer, ts.identity);
93850     }
93851     function noEmitSubstitution(_hint, node) {
93852         return node;
93853     }
93854     ts.noEmitSubstitution = noEmitSubstitution;
93855     function noEmitNotification(hint, node, callback) {
93856         callback(hint, node);
93857     }
93858     ts.noEmitNotification = noEmitNotification;
93859     /**
93860      * Transforms an array of SourceFiles by passing them through each transformer.
93861      *
93862      * @param resolver The emit resolver provided by the checker.
93863      * @param host The emit host object used to interact with the file system.
93864      * @param options Compiler options to surface in the `TransformationContext`.
93865      * @param nodes An array of nodes to transform.
93866      * @param transforms An array of `TransformerFactory` callbacks.
93867      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
93868      */
93869     function transformNodes(resolver, host, options, nodes, transformers, allowDtsFiles) {
93870         var enabledSyntaxKindFeatures = new Array(331 /* Count */);
93871         var lexicalEnvironmentVariableDeclarations;
93872         var lexicalEnvironmentFunctionDeclarations;
93873         var lexicalEnvironmentStatements;
93874         var lexicalEnvironmentFlags = 0 /* None */;
93875         var lexicalEnvironmentVariableDeclarationsStack = [];
93876         var lexicalEnvironmentFunctionDeclarationsStack = [];
93877         var lexicalEnvironmentStatementsStack = [];
93878         var lexicalEnvironmentFlagsStack = [];
93879         var lexicalEnvironmentStackOffset = 0;
93880         var lexicalEnvironmentSuspended = false;
93881         var emitHelpers;
93882         var onSubstituteNode = noEmitSubstitution;
93883         var onEmitNode = noEmitNotification;
93884         var state = 0 /* Uninitialized */;
93885         var diagnostics = [];
93886         // The transformation context is provided to each transformer as part of transformer
93887         // initialization.
93888         var context = {
93889             getCompilerOptions: function () { return options; },
93890             getEmitResolver: function () { return resolver; },
93891             getEmitHost: function () { return host; },
93892             startLexicalEnvironment: startLexicalEnvironment,
93893             suspendLexicalEnvironment: suspendLexicalEnvironment,
93894             resumeLexicalEnvironment: resumeLexicalEnvironment,
93895             endLexicalEnvironment: endLexicalEnvironment,
93896             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
93897             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
93898             hoistVariableDeclaration: hoistVariableDeclaration,
93899             hoistFunctionDeclaration: hoistFunctionDeclaration,
93900             addInitializationStatement: addInitializationStatement,
93901             requestEmitHelper: requestEmitHelper,
93902             readEmitHelpers: readEmitHelpers,
93903             enableSubstitution: enableSubstitution,
93904             enableEmitNotification: enableEmitNotification,
93905             isSubstitutionEnabled: isSubstitutionEnabled,
93906             isEmitNotificationEnabled: isEmitNotificationEnabled,
93907             get onSubstituteNode() { return onSubstituteNode; },
93908             set onSubstituteNode(value) {
93909                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93910                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93911                 onSubstituteNode = value;
93912             },
93913             get onEmitNode() { return onEmitNode; },
93914             set onEmitNode(value) {
93915                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
93916                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
93917                 onEmitNode = value;
93918             },
93919             addDiagnostic: function (diag) {
93920                 diagnostics.push(diag);
93921             }
93922         };
93923         // Ensure the parse tree is clean before applying transformations
93924         for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
93925             var node = nodes_4[_i];
93926             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
93927         }
93928         ts.performance.mark("beforeTransform");
93929         // Chain together and initialize each transformer.
93930         var transformersWithContext = transformers.map(function (t) { return t(context); });
93931         var transformation = function (node) {
93932             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
93933                 var transform = transformersWithContext_1[_i];
93934                 node = transform(node);
93935             }
93936             return node;
93937         };
93938         // prevent modification of transformation hooks.
93939         state = 1 /* Initialized */;
93940         // Transform each node.
93941         var transformed = ts.map(nodes, allowDtsFiles ? transformation : transformRoot);
93942         // prevent modification of the lexical environment.
93943         state = 2 /* Completed */;
93944         ts.performance.mark("afterTransform");
93945         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
93946         return {
93947             transformed: transformed,
93948             substituteNode: substituteNode,
93949             emitNodeWithNotification: emitNodeWithNotification,
93950             isEmitNotificationEnabled: isEmitNotificationEnabled,
93951             dispose: dispose,
93952             diagnostics: diagnostics
93953         };
93954         function transformRoot(node) {
93955             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
93956         }
93957         /**
93958          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
93959          */
93960         function enableSubstitution(kind) {
93961             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93962             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
93963         }
93964         /**
93965          * Determines whether expression substitutions are enabled for the provided node.
93966          */
93967         function isSubstitutionEnabled(node) {
93968             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
93969                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
93970         }
93971         /**
93972          * Emits a node with possible substitution.
93973          *
93974          * @param hint A hint as to the intended usage of the node.
93975          * @param node The node to emit.
93976          * @param emitCallback The callback used to emit the node or its substitute.
93977          */
93978         function substituteNode(hint, node) {
93979             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
93980             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
93981         }
93982         /**
93983          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
93984          */
93985         function enableEmitNotification(kind) {
93986             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
93987             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
93988         }
93989         /**
93990          * Determines whether before/after emit notifications should be raised in the pretty
93991          * printer when it emits a node.
93992          */
93993         function isEmitNotificationEnabled(node) {
93994             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
93995                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
93996         }
93997         /**
93998          * Emits a node with possible emit notification.
93999          *
94000          * @param hint A hint as to the intended usage of the node.
94001          * @param node The node to emit.
94002          * @param emitCallback The callback used to emit the node.
94003          */
94004         function emitNodeWithNotification(hint, node, emitCallback) {
94005             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
94006             if (node) {
94007                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
94008                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
94009                 if (isEmitNotificationEnabled(node)) {
94010                     onEmitNode(hint, node, emitCallback);
94011                 }
94012                 else {
94013                     emitCallback(hint, node);
94014                 }
94015             }
94016         }
94017         /**
94018          * Records a hoisted variable declaration for the provided name within a lexical environment.
94019          */
94020         function hoistVariableDeclaration(name) {
94021             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94022             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94023             var decl = ts.setEmitFlags(ts.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
94024             if (!lexicalEnvironmentVariableDeclarations) {
94025                 lexicalEnvironmentVariableDeclarations = [decl];
94026             }
94027             else {
94028                 lexicalEnvironmentVariableDeclarations.push(decl);
94029             }
94030             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
94031                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
94032             }
94033         }
94034         /**
94035          * Records a hoisted function declaration within a lexical environment.
94036          */
94037         function hoistFunctionDeclaration(func) {
94038             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94039             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94040             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
94041             if (!lexicalEnvironmentFunctionDeclarations) {
94042                 lexicalEnvironmentFunctionDeclarations = [func];
94043             }
94044             else {
94045                 lexicalEnvironmentFunctionDeclarations.push(func);
94046             }
94047         }
94048         /**
94049          * Adds an initialization statement to the top of the lexical environment.
94050          */
94051         function addInitializationStatement(node) {
94052             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94053             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94054             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
94055             if (!lexicalEnvironmentStatements) {
94056                 lexicalEnvironmentStatements = [node];
94057             }
94058             else {
94059                 lexicalEnvironmentStatements.push(node);
94060             }
94061         }
94062         /**
94063          * Starts a new lexical environment. Any existing hoisted variable or function declarations
94064          * are pushed onto a stack, and the related storage variables are reset.
94065          */
94066         function startLexicalEnvironment() {
94067             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94068             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94069             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94070             // Save the current lexical environment. Rather than resizing the array we adjust the
94071             // stack size variable. This allows us to reuse existing array slots we've
94072             // already allocated between transformations to avoid allocation and GC overhead during
94073             // transformation.
94074             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
94075             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
94076             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
94077             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
94078             lexicalEnvironmentStackOffset++;
94079             lexicalEnvironmentVariableDeclarations = undefined;
94080             lexicalEnvironmentFunctionDeclarations = undefined;
94081             lexicalEnvironmentStatements = undefined;
94082             lexicalEnvironmentFlags = 0 /* None */;
94083         }
94084         /** Suspends the current lexical environment, usually after visiting a parameter list. */
94085         function suspendLexicalEnvironment() {
94086             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94087             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94088             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
94089             lexicalEnvironmentSuspended = true;
94090         }
94091         /** Resumes a suspended lexical environment, usually before visiting a function body. */
94092         function resumeLexicalEnvironment() {
94093             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94094             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94095             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
94096             lexicalEnvironmentSuspended = false;
94097         }
94098         /**
94099          * Ends a lexical environment. The previous set of hoisted declarations are restored and
94100          * any hoisted declarations added in this environment are returned.
94101          */
94102         function endLexicalEnvironment() {
94103             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
94104             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
94105             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
94106             var statements;
94107             if (lexicalEnvironmentVariableDeclarations ||
94108                 lexicalEnvironmentFunctionDeclarations ||
94109                 lexicalEnvironmentStatements) {
94110                 if (lexicalEnvironmentFunctionDeclarations) {
94111                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
94112                 }
94113                 if (lexicalEnvironmentVariableDeclarations) {
94114                     var statement = ts.createVariableStatement(
94115                     /*modifiers*/ undefined, ts.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
94116                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
94117                     if (!statements) {
94118                         statements = [statement];
94119                     }
94120                     else {
94121                         statements.push(statement);
94122                     }
94123                 }
94124                 if (lexicalEnvironmentStatements) {
94125                     if (!statements) {
94126                         statements = __spreadArrays(lexicalEnvironmentStatements);
94127                     }
94128                     else {
94129                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
94130                     }
94131                 }
94132             }
94133             // Restore the previous lexical environment.
94134             lexicalEnvironmentStackOffset--;
94135             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
94136             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
94137             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
94138             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
94139             if (lexicalEnvironmentStackOffset === 0) {
94140                 lexicalEnvironmentVariableDeclarationsStack = [];
94141                 lexicalEnvironmentFunctionDeclarationsStack = [];
94142                 lexicalEnvironmentStatementsStack = [];
94143                 lexicalEnvironmentFlagsStack = [];
94144             }
94145             return statements;
94146         }
94147         function setLexicalEnvironmentFlags(flags, value) {
94148             lexicalEnvironmentFlags = value ?
94149                 lexicalEnvironmentFlags | flags :
94150                 lexicalEnvironmentFlags & ~flags;
94151         }
94152         function getLexicalEnvironmentFlags() {
94153             return lexicalEnvironmentFlags;
94154         }
94155         function requestEmitHelper(helper) {
94156             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94157             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94158             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
94159             if (helper.dependencies) {
94160                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
94161                     var h = _a[_i];
94162                     requestEmitHelper(h);
94163                 }
94164             }
94165             emitHelpers = ts.append(emitHelpers, helper);
94166         }
94167         function readEmitHelpers() {
94168             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
94169             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
94170             var helpers = emitHelpers;
94171             emitHelpers = undefined;
94172             return helpers;
94173         }
94174         function dispose() {
94175             if (state < 3 /* Disposed */) {
94176                 // Clean up emit nodes on parse tree
94177                 for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) {
94178                     var node = nodes_5[_i];
94179                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
94180                 }
94181                 // Release references to external entries for GC purposes.
94182                 lexicalEnvironmentVariableDeclarations = undefined;
94183                 lexicalEnvironmentVariableDeclarationsStack = undefined;
94184                 lexicalEnvironmentFunctionDeclarations = undefined;
94185                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
94186                 onSubstituteNode = undefined;
94187                 onEmitNode = undefined;
94188                 emitHelpers = undefined;
94189                 // Prevent further use of the transformation result.
94190                 state = 3 /* Disposed */;
94191             }
94192         }
94193     }
94194     ts.transformNodes = transformNodes;
94195 })(ts || (ts = {}));
94196 var ts;
94197 (function (ts) {
94198     var brackets = createBracketsMap();
94199     var syntheticParent = { pos: -1, end: -1 };
94200     /*@internal*/
94201     function isBuildInfoFile(file) {
94202         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
94203     }
94204     ts.isBuildInfoFile = isBuildInfoFile;
94205     /*@internal*/
94206     /**
94207      * Iterates over the source files that are expected to have an emit output.
94208      *
94209      * @param host An EmitHost.
94210      * @param action The action to execute.
94211      * @param sourceFilesOrTargetSourceFile
94212      *   If an array, the full list of source files to emit.
94213      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
94214      */
94215     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
94216         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
94217         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
94218         var options = host.getCompilerOptions();
94219         if (options.outFile || options.out) {
94220             var prepends = host.getPrependNodes();
94221             if (sourceFiles.length || prepends.length) {
94222                 var bundle = ts.createBundle(sourceFiles, prepends);
94223                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
94224                 if (result) {
94225                     return result;
94226                 }
94227             }
94228         }
94229         else {
94230             if (!onlyBuildInfo) {
94231                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
94232                     var sourceFile = sourceFiles_1[_a];
94233                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
94234                     if (result) {
94235                         return result;
94236                     }
94237                 }
94238             }
94239             if (includeBuildInfo) {
94240                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(host.getCompilerOptions());
94241                 if (buildInfoPath)
94242                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
94243             }
94244         }
94245     }
94246     ts.forEachEmittedFile = forEachEmittedFile;
94247     function getTsBuildInfoEmitOutputFilePath(options) {
94248         var configFile = options.configFilePath;
94249         if (!ts.isIncrementalCompilation(options))
94250             return undefined;
94251         if (options.tsBuildInfoFile)
94252             return options.tsBuildInfoFile;
94253         var outPath = options.outFile || options.out;
94254         var buildInfoExtensionLess;
94255         if (outPath) {
94256             buildInfoExtensionLess = ts.removeFileExtension(outPath);
94257         }
94258         else {
94259             if (!configFile)
94260                 return undefined;
94261             var configFileExtensionLess = ts.removeFileExtension(configFile);
94262             buildInfoExtensionLess = options.outDir ?
94263                 options.rootDir ?
94264                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
94265                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
94266                 configFileExtensionLess;
94267         }
94268         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
94269     }
94270     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
94271     /*@internal*/
94272     function getOutputPathsForBundle(options, forceDtsPaths) {
94273         var outPath = options.outFile || options.out;
94274         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
94275         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
94276         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
94277         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94278         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
94279         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
94280     }
94281     ts.getOutputPathsForBundle = getOutputPathsForBundle;
94282     /*@internal*/
94283     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
94284         var options = host.getCompilerOptions();
94285         if (sourceFile.kind === 291 /* Bundle */) {
94286             return getOutputPathsForBundle(options, forceDtsPaths);
94287         }
94288         else {
94289             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
94290             var isJsonFile = ts.isJsonSourceFile(sourceFile);
94291             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
94292             var isJsonEmittedToSameLocation = isJsonFile &&
94293                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
94294             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
94295             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
94296             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
94297             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
94298             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
94299         }
94300     }
94301     ts.getOutputPathsFor = getOutputPathsFor;
94302     function getSourceMapFilePath(jsFilePath, options) {
94303         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
94304     }
94305     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
94306     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
94307     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
94308     /* @internal */
94309     function getOutputExtension(sourceFile, options) {
94310         if (ts.isJsonSourceFile(sourceFile)) {
94311             return ".json" /* Json */;
94312         }
94313         if (options.jsx === 1 /* Preserve */) {
94314             if (ts.isSourceFileJS(sourceFile)) {
94315                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
94316                     return ".jsx" /* Jsx */;
94317                 }
94318             }
94319             else if (sourceFile.languageVariant === 1 /* JSX */) {
94320                 // TypeScript source file preserving JSX syntax
94321                 return ".jsx" /* Jsx */;
94322             }
94323         }
94324         return ".js" /* Js */;
94325     }
94326     ts.getOutputExtension = getOutputExtension;
94327     function rootDirOfOptions(configFile) {
94328         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
94329     }
94330     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
94331         return outputDir ?
94332             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
94333             inputFileName;
94334     }
94335     /* @internal */
94336     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
94337         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
94338         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
94339     }
94340     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
94341     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
94342         if (configFile.options.emitDeclarationOnly)
94343             return undefined;
94344         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
94345         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
94346             ".json" /* Json */ :
94347             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
94348                 ".jsx" /* Jsx */ :
94349                 ".js" /* Js */);
94350         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
94351             outputFileName :
94352             undefined;
94353     }
94354     function createAddOutput() {
94355         var outputs;
94356         return { addOutput: addOutput, getOutputs: getOutputs };
94357         function addOutput(path) {
94358             if (path) {
94359                 (outputs || (outputs = [])).push(path);
94360             }
94361         }
94362         function getOutputs() {
94363             return outputs || ts.emptyArray;
94364         }
94365     }
94366     function getSingleOutputFileNames(configFile, addOutput) {
94367         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94368         addOutput(jsFilePath);
94369         addOutput(sourceMapFilePath);
94370         addOutput(declarationFilePath);
94371         addOutput(declarationMapPath);
94372         addOutput(buildInfoPath);
94373     }
94374     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
94375         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94376             return;
94377         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94378         addOutput(js);
94379         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94380             return;
94381         if (js && configFile.options.sourceMap) {
94382             addOutput(js + ".map");
94383         }
94384         if (ts.getEmitDeclarations(configFile.options)) {
94385             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94386             addOutput(dts);
94387             if (configFile.options.declarationMap) {
94388                 addOutput(dts + ".map");
94389             }
94390         }
94391     }
94392     /*@internal*/
94393     function getAllProjectOutputs(configFile, ignoreCase) {
94394         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94395         if (configFile.options.outFile || configFile.options.out) {
94396             getSingleOutputFileNames(configFile, addOutput);
94397         }
94398         else {
94399             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
94400                 var inputFileName = _c[_b];
94401                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
94402             }
94403             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
94404         }
94405         return getOutputs();
94406     }
94407     ts.getAllProjectOutputs = getAllProjectOutputs;
94408     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
94409         inputFileName = ts.normalizePath(inputFileName);
94410         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
94411         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
94412         if (commandLine.options.outFile || commandLine.options.out) {
94413             getSingleOutputFileNames(commandLine, addOutput);
94414         }
94415         else {
94416             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
94417         }
94418         return getOutputs();
94419     }
94420     ts.getOutputFileNames = getOutputFileNames;
94421     /*@internal*/
94422     function getFirstProjectOutput(configFile, ignoreCase) {
94423         if (configFile.options.outFile || configFile.options.out) {
94424             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
94425             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
94426         }
94427         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
94428             var inputFileName = _b[_a];
94429             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
94430                 continue;
94431             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
94432             if (jsFilePath)
94433                 return jsFilePath;
94434             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
94435                 continue;
94436             if (ts.getEmitDeclarations(configFile.options)) {
94437                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
94438             }
94439         }
94440         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
94441         if (buildInfoPath)
94442             return buildInfoPath;
94443         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
94444     }
94445     ts.getFirstProjectOutput = getFirstProjectOutput;
94446     /*@internal*/
94447     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
94448     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
94449         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
94450         var compilerOptions = host.getCompilerOptions();
94451         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
94452         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
94453         var emitterDiagnostics = ts.createDiagnosticCollection();
94454         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
94455         var writer = ts.createTextWriter(newLine);
94456         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
94457         var bundleBuildInfo;
94458         var emitSkipped = false;
94459         var exportedModulesFromDeclarationEmit;
94460         // Emit each output file
94461         enter();
94462         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
94463         exit();
94464         return {
94465             emitSkipped: emitSkipped,
94466             diagnostics: emitterDiagnostics.getDiagnostics(),
94467             emittedFiles: emittedFilesList,
94468             sourceMaps: sourceMapDataList,
94469             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
94470         };
94471         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
94472             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
94473             var buildInfoDirectory;
94474             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
94475                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94476                 bundleBuildInfo = {
94477                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
94478                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
94479                 };
94480             }
94481             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
94482             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
94483             emitBuildInfo(bundleBuildInfo, buildInfoPath);
94484             if (!emitSkipped && emittedFilesList) {
94485                 if (!emitOnlyDtsFiles) {
94486                     if (jsFilePath) {
94487                         emittedFilesList.push(jsFilePath);
94488                     }
94489                     if (sourceMapFilePath) {
94490                         emittedFilesList.push(sourceMapFilePath);
94491                     }
94492                     if (buildInfoPath) {
94493                         emittedFilesList.push(buildInfoPath);
94494                     }
94495                 }
94496                 if (declarationFilePath) {
94497                     emittedFilesList.push(declarationFilePath);
94498                 }
94499                 if (declarationMapPath) {
94500                     emittedFilesList.push(declarationMapPath);
94501                 }
94502             }
94503             function relativeToBuildInfo(path) {
94504                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
94505             }
94506         }
94507         function emitBuildInfo(bundle, buildInfoPath) {
94508             // Write build information if applicable
94509             if (!buildInfoPath || targetSourceFile || emitSkipped)
94510                 return;
94511             var program = host.getProgramBuildInfo();
94512             if (host.isEmitBlocked(buildInfoPath) || compilerOptions.noEmit) {
94513                 emitSkipped = true;
94514                 return;
94515             }
94516             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
94517             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
94518         }
94519         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
94520             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
94521                 return;
94522             }
94523             // Make sure not to write js file and source map file if any of them cannot be written
94524             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
94525                 emitSkipped = true;
94526                 return;
94527             }
94528             // Transform the source files
94529             var transform = ts.transformNodes(resolver, host, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
94530             var printerOptions = {
94531                 removeComments: compilerOptions.removeComments,
94532                 newLine: compilerOptions.newLine,
94533                 noEmitHelpers: compilerOptions.noEmitHelpers,
94534                 module: compilerOptions.module,
94535                 target: compilerOptions.target,
94536                 sourceMap: compilerOptions.sourceMap,
94537                 inlineSourceMap: compilerOptions.inlineSourceMap,
94538                 inlineSources: compilerOptions.inlineSources,
94539                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94540                 writeBundleFileInfo: !!bundleBuildInfo,
94541                 relativeToBuildInfo: relativeToBuildInfo
94542             };
94543             // Create a printer to print the nodes
94544             var printer = createPrinter(printerOptions, {
94545                 // resolver hooks
94546                 hasGlobalName: resolver.hasGlobalName,
94547                 // transform hooks
94548                 onEmitNode: transform.emitNodeWithNotification,
94549                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
94550                 substituteNode: transform.substituteNode,
94551             });
94552             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
94553             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
94554             // Clean up emit nodes on parse tree
94555             transform.dispose();
94556             if (bundleBuildInfo)
94557                 bundleBuildInfo.js = printer.bundleFileInfo;
94558         }
94559         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
94560             if (!sourceFileOrBundle)
94561                 return;
94562             if (!declarationFilePath) {
94563                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
94564                     emitSkipped = true;
94565                 return;
94566             }
94567             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
94568             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
94569             // Setup and perform the transformation to retrieve declarations from the input files
94570             var inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [ts.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
94571             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
94572                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
94573                 // Do that here when emitting only dts files
94574                 filesForEmit.forEach(collectLinkedAliases);
94575             }
94576             var declarationTransform = ts.transformNodes(resolver, host, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
94577             if (ts.length(declarationTransform.diagnostics)) {
94578                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
94579                     var diagnostic = _b[_a];
94580                     emitterDiagnostics.add(diagnostic);
94581                 }
94582             }
94583             var printerOptions = {
94584                 removeComments: compilerOptions.removeComments,
94585                 newLine: compilerOptions.newLine,
94586                 noEmitHelpers: true,
94587                 module: compilerOptions.module,
94588                 target: compilerOptions.target,
94589                 sourceMap: compilerOptions.sourceMap,
94590                 inlineSourceMap: compilerOptions.inlineSourceMap,
94591                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
94592                 onlyPrintJsDocStyle: true,
94593                 writeBundleFileInfo: !!bundleBuildInfo,
94594                 recordInternalSection: !!bundleBuildInfo,
94595                 relativeToBuildInfo: relativeToBuildInfo
94596             };
94597             var declarationPrinter = createPrinter(printerOptions, {
94598                 // resolver hooks
94599                 hasGlobalName: resolver.hasGlobalName,
94600                 // transform hooks
94601                 onEmitNode: declarationTransform.emitNodeWithNotification,
94602                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
94603                 substituteNode: declarationTransform.substituteNode,
94604             });
94605             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
94606             emitSkipped = emitSkipped || declBlocked;
94607             if (!declBlocked || forceDtsEmit) {
94608                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
94609                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
94610                     sourceMap: compilerOptions.declarationMap,
94611                     sourceRoot: compilerOptions.sourceRoot,
94612                     mapRoot: compilerOptions.mapRoot,
94613                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
94614                 });
94615                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 290 /* SourceFile */) {
94616                     var sourceFile = declarationTransform.transformed[0];
94617                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
94618                 }
94619             }
94620             declarationTransform.dispose();
94621             if (bundleBuildInfo)
94622                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
94623         }
94624         function collectLinkedAliases(node) {
94625             if (ts.isExportAssignment(node)) {
94626                 if (node.expression.kind === 75 /* Identifier */) {
94627                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
94628                 }
94629                 return;
94630             }
94631             else if (ts.isExportSpecifier(node)) {
94632                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
94633                 return;
94634             }
94635             ts.forEachChild(node, collectLinkedAliases);
94636         }
94637         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
94638             var bundle = sourceFileOrBundle.kind === 291 /* Bundle */ ? sourceFileOrBundle : undefined;
94639             var sourceFile = sourceFileOrBundle.kind === 290 /* SourceFile */ ? sourceFileOrBundle : undefined;
94640             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
94641             var sourceMapGenerator;
94642             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
94643                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
94644             }
94645             if (bundle) {
94646                 printer.writeBundle(bundle, writer, sourceMapGenerator);
94647             }
94648             else {
94649                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
94650             }
94651             if (sourceMapGenerator) {
94652                 if (sourceMapDataList) {
94653                     sourceMapDataList.push({
94654                         inputSourceFileNames: sourceMapGenerator.getSources(),
94655                         sourceMap: sourceMapGenerator.toJSON()
94656                     });
94657                 }
94658                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
94659                 if (sourceMappingURL) {
94660                     if (!writer.isAtStartOfLine())
94661                         writer.rawWrite(newLine);
94662                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
94663                 }
94664                 // Write the source map
94665                 if (sourceMapFilePath) {
94666                     var sourceMap = sourceMapGenerator.toString();
94667                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
94668                 }
94669             }
94670             else {
94671                 writer.writeLine();
94672             }
94673             // Write the output file
94674             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
94675             // Reset state
94676             writer.clear();
94677         }
94678         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
94679             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
94680                 && (sourceFileOrBundle.kind !== 290 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
94681         }
94682         function getSourceRoot(mapOptions) {
94683             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
94684             // relative paths of the sources list in the sourcemap
94685             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
94686             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
94687         }
94688         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
94689             if (mapOptions.sourceRoot)
94690                 return host.getCommonSourceDirectory();
94691             if (mapOptions.mapRoot) {
94692                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94693                 if (sourceFile) {
94694                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94695                     // 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
94696                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94697                 }
94698                 if (ts.getRootLength(sourceMapDir) === 0) {
94699                     // The relative paths are relative to the common directory
94700                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94701                 }
94702                 return sourceMapDir;
94703             }
94704             return ts.getDirectoryPath(ts.normalizePath(filePath));
94705         }
94706         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
94707             if (mapOptions.inlineSourceMap) {
94708                 // Encode the sourceMap into the sourceMap url
94709                 var sourceMapText = sourceMapGenerator.toString();
94710                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
94711                 return "data:application/json;base64," + base64SourceMapText;
94712             }
94713             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
94714             if (mapOptions.mapRoot) {
94715                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
94716                 if (sourceFile) {
94717                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
94718                     // 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
94719                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
94720                 }
94721                 if (ts.getRootLength(sourceMapDir) === 0) {
94722                     // The relative paths are relative to the common directory
94723                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
94724                     return ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
94725                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
94726                     host.getCurrentDirectory(), host.getCanonicalFileName, 
94727                     /*isAbsolutePathAnUrl*/ true);
94728                 }
94729                 else {
94730                     return ts.combinePaths(sourceMapDir, sourceMapFile);
94731                 }
94732             }
94733             return sourceMapFile;
94734         }
94735     }
94736     ts.emitFiles = emitFiles;
94737     /*@internal*/
94738     function getBuildInfoText(buildInfo) {
94739         return JSON.stringify(buildInfo, undefined, 2);
94740     }
94741     ts.getBuildInfoText = getBuildInfoText;
94742     /*@internal*/
94743     function getBuildInfo(buildInfoText) {
94744         return JSON.parse(buildInfoText);
94745     }
94746     ts.getBuildInfo = getBuildInfo;
94747     /*@internal*/
94748     ts.notImplementedResolver = {
94749         hasGlobalName: ts.notImplemented,
94750         getReferencedExportContainer: ts.notImplemented,
94751         getReferencedImportDeclaration: ts.notImplemented,
94752         getReferencedDeclarationWithCollidingName: ts.notImplemented,
94753         isDeclarationWithCollidingName: ts.notImplemented,
94754         isValueAliasDeclaration: ts.notImplemented,
94755         isReferencedAliasDeclaration: ts.notImplemented,
94756         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
94757         getNodeCheckFlags: ts.notImplemented,
94758         isDeclarationVisible: ts.notImplemented,
94759         isLateBound: function (_node) { return false; },
94760         collectLinkedAliases: ts.notImplemented,
94761         isImplementationOfOverload: ts.notImplemented,
94762         isRequiredInitializedParameter: ts.notImplemented,
94763         isOptionalUninitializedParameterProperty: ts.notImplemented,
94764         isExpandoFunctionDeclaration: ts.notImplemented,
94765         getPropertiesOfContainerFunction: ts.notImplemented,
94766         createTypeOfDeclaration: ts.notImplemented,
94767         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
94768         createTypeOfExpression: ts.notImplemented,
94769         createLiteralConstValue: ts.notImplemented,
94770         isSymbolAccessible: ts.notImplemented,
94771         isEntityNameVisible: ts.notImplemented,
94772         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
94773         getConstantValue: ts.notImplemented,
94774         getReferencedValueDeclaration: ts.notImplemented,
94775         getTypeReferenceSerializationKind: ts.notImplemented,
94776         isOptionalParameter: ts.notImplemented,
94777         moduleExportsSomeValue: ts.notImplemented,
94778         isArgumentsLocalBinding: ts.notImplemented,
94779         getExternalModuleFileFromDeclaration: ts.notImplemented,
94780         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
94781         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
94782         isLiteralConstDeclaration: ts.notImplemented,
94783         getJsxFactoryEntity: ts.notImplemented,
94784         getAllAccessorDeclarations: ts.notImplemented,
94785         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
94786         isBindingCapturedByNode: ts.notImplemented,
94787         getDeclarationStatementsForSourceFile: ts.notImplemented,
94788         isImportRequiredByAugmentation: ts.notImplemented,
94789     };
94790     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
94791         var sourceFiles = bundle.sourceFiles.map(function (fileName) {
94792             var sourceFile = ts.createNode(290 /* SourceFile */, 0, 0);
94793             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
94794             sourceFile.text = "";
94795             sourceFile.statements = ts.createNodeArray();
94796             return sourceFile;
94797         });
94798         var jsBundle = ts.Debug.checkDefined(bundle.js);
94799         ts.forEach(jsBundle.sources && jsBundle.sources.prologues, function (prologueInfo) {
94800             var sourceFile = sourceFiles[prologueInfo.file];
94801             sourceFile.text = prologueInfo.text;
94802             sourceFile.end = prologueInfo.text.length;
94803             sourceFile.statements = ts.createNodeArray(prologueInfo.directives.map(function (directive) {
94804                 var statement = ts.createNode(226 /* ExpressionStatement */, directive.pos, directive.end);
94805                 statement.expression = ts.createNode(10 /* StringLiteral */, directive.expression.pos, directive.expression.end);
94806                 statement.expression.text = directive.expression.text;
94807                 return statement;
94808             }));
94809         });
94810         return sourceFiles;
94811     }
94812     /*@internal*/
94813     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
94814         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
94815         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
94816         if (!buildInfoText)
94817             return buildInfoPath;
94818         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
94819         if (!jsFileText)
94820             return jsFilePath;
94821         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
94822         // error if no source map or for now if inline sourcemap
94823         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
94824             return sourceMapFilePath || "inline sourcemap decoding";
94825         // read declaration text
94826         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
94827         if (declarationFilePath && !declarationText)
94828             return declarationFilePath;
94829         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
94830         // error if no source map or for now if inline sourcemap
94831         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
94832             return declarationMapPath || "inline sourcemap decoding";
94833         var buildInfo = getBuildInfo(buildInfoText);
94834         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
94835             return buildInfoPath;
94836         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
94837         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
94838         /*onlyOwnText*/ true);
94839         var outputFiles = [];
94840         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
94841         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
94842         var emitHost = {
94843             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
94844             getCanonicalFileName: host.getCanonicalFileName,
94845             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
94846             getCompilerOptions: function () { return config.options; },
94847             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
94848             getNewLine: function () { return host.getNewLine(); },
94849             getSourceFile: ts.returnUndefined,
94850             getSourceFileByPath: ts.returnUndefined,
94851             getSourceFiles: function () { return sourceFilesForJsEmit; },
94852             getLibFileFromReference: ts.notImplemented,
94853             isSourceFileFromExternalLibrary: ts.returnFalse,
94854             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
94855             getProjectReferenceRedirect: ts.returnUndefined,
94856             isSourceOfProjectReferenceRedirect: ts.returnFalse,
94857             writeFile: function (name, text, writeByteOrderMark) {
94858                 switch (name) {
94859                     case jsFilePath:
94860                         if (jsFileText === text)
94861                             return;
94862                         break;
94863                     case sourceMapFilePath:
94864                         if (sourceMapText === text)
94865                             return;
94866                         break;
94867                     case buildInfoPath:
94868                         var newBuildInfo = getBuildInfo(text);
94869                         newBuildInfo.program = buildInfo.program;
94870                         // Update sourceFileInfo
94871                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
94872                         newBuildInfo.bundle.js.sources = js.sources;
94873                         if (dts) {
94874                             newBuildInfo.bundle.dts.sources = dts.sources;
94875                         }
94876                         newBuildInfo.bundle.sourceFiles = sourceFiles;
94877                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
94878                         return;
94879                     case declarationFilePath:
94880                         if (declarationText === text)
94881                             return;
94882                         break;
94883                     case declarationMapPath:
94884                         if (declarationMapText === text)
94885                             return;
94886                         break;
94887                     default:
94888                         ts.Debug.fail("Unexpected path: " + name);
94889                 }
94890                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
94891             },
94892             isEmitBlocked: ts.returnFalse,
94893             readFile: function (f) { return host.readFile(f); },
94894             fileExists: function (f) { return host.fileExists(f); },
94895             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
94896             getProgramBuildInfo: ts.returnUndefined,
94897             getSourceFileFromReference: ts.returnUndefined,
94898             redirectTargetsMap: ts.createMultiMap()
94899         };
94900         emitFiles(ts.notImplementedResolver, emitHost, 
94901         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
94902         return outputFiles;
94903     }
94904     ts.emitUsingBuildInfo = emitUsingBuildInfo;
94905     var PipelinePhase;
94906     (function (PipelinePhase) {
94907         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
94908         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
94909         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
94910         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
94911         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
94912     })(PipelinePhase || (PipelinePhase = {}));
94913     function createPrinter(printerOptions, handlers) {
94914         if (printerOptions === void 0) { printerOptions = {}; }
94915         if (handlers === void 0) { handlers = {}; }
94916         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;
94917         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
94918         var newLine = ts.getNewLineCharacter(printerOptions);
94919         var moduleKind = ts.getEmitModuleKind(printerOptions);
94920         var bundledHelpers = ts.createMap();
94921         var currentSourceFile;
94922         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
94923         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
94924         var generatedNames; // Set of names generated by the NameGenerator.
94925         var tempFlagsStack; // Stack of enclosing name generation scopes.
94926         var tempFlags; // TempFlags for the current name generation scope.
94927         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
94928         var reservedNames; // TempFlags to reserve in nested name generation scopes.
94929         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
94930         var writer;
94931         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
94932         var write = writeBase;
94933         var isOwnFileEmit;
94934         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
94935         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
94936         var recordInternalSection = printerOptions.recordInternalSection;
94937         var sourceFileTextPos = 0;
94938         var sourceFileTextKind = "text" /* Text */;
94939         // Source Maps
94940         var sourceMapsDisabled = true;
94941         var sourceMapGenerator;
94942         var sourceMapSource;
94943         var sourceMapSourceIndex = -1;
94944         // Comments
94945         var containerPos = -1;
94946         var containerEnd = -1;
94947         var declarationListContainerEnd = -1;
94948         var currentLineMap;
94949         var detachedCommentsInfo;
94950         var hasWrittenComment = false;
94951         var commentsDisabled = !!printerOptions.removeComments;
94952         var lastNode;
94953         var lastSubstitution;
94954         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
94955         reset();
94956         return {
94957             // public API
94958             printNode: printNode,
94959             printList: printList,
94960             printFile: printFile,
94961             printBundle: printBundle,
94962             // internal API
94963             writeNode: writeNode,
94964             writeList: writeList,
94965             writeFile: writeFile,
94966             writeBundle: writeBundle,
94967             bundleFileInfo: bundleFileInfo
94968         };
94969         function printNode(hint, node, sourceFile) {
94970             switch (hint) {
94971                 case 0 /* SourceFile */:
94972                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
94973                     break;
94974                 case 2 /* IdentifierName */:
94975                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
94976                     break;
94977                 case 1 /* Expression */:
94978                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
94979                     break;
94980             }
94981             switch (node.kind) {
94982                 case 290 /* SourceFile */: return printFile(node);
94983                 case 291 /* Bundle */: return printBundle(node);
94984                 case 292 /* UnparsedSource */: return printUnparsedSource(node);
94985             }
94986             writeNode(hint, node, sourceFile, beginPrint());
94987             return endPrint();
94988         }
94989         function printList(format, nodes, sourceFile) {
94990             writeList(format, nodes, sourceFile, beginPrint());
94991             return endPrint();
94992         }
94993         function printBundle(bundle) {
94994             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
94995             return endPrint();
94996         }
94997         function printFile(sourceFile) {
94998             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
94999             return endPrint();
95000         }
95001         function printUnparsedSource(unparsed) {
95002             writeUnparsedSource(unparsed, beginPrint());
95003             return endPrint();
95004         }
95005         function writeNode(hint, node, sourceFile, output) {
95006             var previousWriter = writer;
95007             setWriter(output, /*_sourceMapGenerator*/ undefined);
95008             print(hint, node, sourceFile);
95009             reset();
95010             writer = previousWriter;
95011         }
95012         function writeList(format, nodes, sourceFile, output) {
95013             var previousWriter = writer;
95014             setWriter(output, /*_sourceMapGenerator*/ undefined);
95015             if (sourceFile) {
95016                 setSourceFile(sourceFile);
95017             }
95018             emitList(syntheticParent, nodes, format);
95019             reset();
95020             writer = previousWriter;
95021         }
95022         function getTextPosWithWriteLine() {
95023             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
95024         }
95025         function updateOrPushBundleFileTextLike(pos, end, kind) {
95026             var last = ts.lastOrUndefined(bundleFileInfo.sections);
95027             if (last && last.kind === kind) {
95028                 last.end = end;
95029             }
95030             else {
95031                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
95032             }
95033         }
95034         function recordBundleFileInternalSectionStart(node) {
95035             if (recordInternalSection &&
95036                 bundleFileInfo &&
95037                 currentSourceFile &&
95038                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
95039                 ts.isInternalDeclaration(node, currentSourceFile) &&
95040                 sourceFileTextKind !== "internal" /* Internal */) {
95041                 var prevSourceFileTextKind = sourceFileTextKind;
95042                 recordBundleFileTextLikeSection(writer.getTextPos());
95043                 sourceFileTextPos = getTextPosWithWriteLine();
95044                 sourceFileTextKind = "internal" /* Internal */;
95045                 return prevSourceFileTextKind;
95046             }
95047             return undefined;
95048         }
95049         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
95050             if (prevSourceFileTextKind) {
95051                 recordBundleFileTextLikeSection(writer.getTextPos());
95052                 sourceFileTextPos = getTextPosWithWriteLine();
95053                 sourceFileTextKind = prevSourceFileTextKind;
95054             }
95055         }
95056         function recordBundleFileTextLikeSection(end) {
95057             if (sourceFileTextPos < end) {
95058                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
95059                 return true;
95060             }
95061             return false;
95062         }
95063         function writeBundle(bundle, output, sourceMapGenerator) {
95064             var _a;
95065             isOwnFileEmit = false;
95066             var previousWriter = writer;
95067             setWriter(output, sourceMapGenerator);
95068             emitShebangIfNeeded(bundle);
95069             emitPrologueDirectivesIfNeeded(bundle);
95070             emitHelpers(bundle);
95071             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
95072             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
95073                 var prepend = _c[_b];
95074                 writeLine();
95075                 var pos = writer.getTextPos();
95076                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
95077                 if (savedSections)
95078                     bundleFileInfo.sections = [];
95079                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
95080                 if (bundleFileInfo) {
95081                     var newSections = bundleFileInfo.sections;
95082                     bundleFileInfo.sections = savedSections;
95083                     if (prepend.oldFileOfCurrentEmit)
95084                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
95085                     else {
95086                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
95087                         bundleFileInfo.sections.push({
95088                             pos: pos,
95089                             end: writer.getTextPos(),
95090                             kind: "prepend" /* Prepend */,
95091                             data: relativeToBuildInfo(prepend.fileName),
95092                             texts: newSections
95093                         });
95094                     }
95095                 }
95096             }
95097             sourceFileTextPos = getTextPosWithWriteLine();
95098             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
95099                 var sourceFile = _e[_d];
95100                 print(0 /* SourceFile */, sourceFile, sourceFile);
95101             }
95102             if (bundleFileInfo && bundle.sourceFiles.length) {
95103                 var end = writer.getTextPos();
95104                 if (recordBundleFileTextLikeSection(end)) {
95105                     // Store prologues
95106                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
95107                     if (prologues) {
95108                         if (!bundleFileInfo.sources)
95109                             bundleFileInfo.sources = {};
95110                         bundleFileInfo.sources.prologues = prologues;
95111                     }
95112                     // Store helpes
95113                     var helpers = getHelpersFromBundledSourceFiles(bundle);
95114                     if (helpers) {
95115                         if (!bundleFileInfo.sources)
95116                             bundleFileInfo.sources = {};
95117                         bundleFileInfo.sources.helpers = helpers;
95118                     }
95119                 }
95120             }
95121             reset();
95122             writer = previousWriter;
95123         }
95124         function writeUnparsedSource(unparsed, output) {
95125             var previousWriter = writer;
95126             setWriter(output, /*_sourceMapGenerator*/ undefined);
95127             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
95128             reset();
95129             writer = previousWriter;
95130         }
95131         function writeFile(sourceFile, output, sourceMapGenerator) {
95132             isOwnFileEmit = true;
95133             var previousWriter = writer;
95134             setWriter(output, sourceMapGenerator);
95135             emitShebangIfNeeded(sourceFile);
95136             emitPrologueDirectivesIfNeeded(sourceFile);
95137             print(0 /* SourceFile */, sourceFile, sourceFile);
95138             reset();
95139             writer = previousWriter;
95140         }
95141         function beginPrint() {
95142             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
95143         }
95144         function endPrint() {
95145             var text = ownWriter.getText();
95146             ownWriter.clear();
95147             return text;
95148         }
95149         function print(hint, node, sourceFile) {
95150             if (sourceFile) {
95151                 setSourceFile(sourceFile);
95152             }
95153             pipelineEmit(hint, node);
95154         }
95155         function setSourceFile(sourceFile) {
95156             currentSourceFile = sourceFile;
95157             currentLineMap = undefined;
95158             detachedCommentsInfo = undefined;
95159             if (sourceFile) {
95160                 setSourceMapSource(sourceFile);
95161             }
95162         }
95163         function setWriter(_writer, _sourceMapGenerator) {
95164             if (_writer && printerOptions.omitTrailingSemicolon) {
95165                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
95166             }
95167             writer = _writer; // TODO: GH#18217
95168             sourceMapGenerator = _sourceMapGenerator;
95169             sourceMapsDisabled = !writer || !sourceMapGenerator;
95170         }
95171         function reset() {
95172             nodeIdToGeneratedName = [];
95173             autoGeneratedIdToGeneratedName = [];
95174             generatedNames = ts.createMap();
95175             tempFlagsStack = [];
95176             tempFlags = 0 /* Auto */;
95177             reservedNamesStack = [];
95178             currentSourceFile = undefined;
95179             currentLineMap = undefined;
95180             detachedCommentsInfo = undefined;
95181             lastNode = undefined;
95182             lastSubstitution = undefined;
95183             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
95184         }
95185         function getCurrentLineMap() {
95186             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
95187         }
95188         function emit(node) {
95189             if (node === undefined)
95190                 return;
95191             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
95192             var substitute = pipelineEmit(4 /* Unspecified */, node);
95193             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
95194             return substitute;
95195         }
95196         function emitIdentifierName(node) {
95197             if (node === undefined)
95198                 return;
95199             return pipelineEmit(2 /* IdentifierName */, node);
95200         }
95201         function emitExpression(node) {
95202             if (node === undefined)
95203                 return;
95204             return pipelineEmit(1 /* Expression */, node);
95205         }
95206         function emitJsxAttributeValue(node) {
95207             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
95208         }
95209         function pipelineEmit(emitHint, node) {
95210             var savedLastNode = lastNode;
95211             var savedLastSubstitution = lastSubstitution;
95212             var savedPreserveSourceNewlines = preserveSourceNewlines;
95213             lastNode = node;
95214             lastSubstitution = undefined;
95215             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
95216                 preserveSourceNewlines = false;
95217             }
95218             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
95219             pipelinePhase(emitHint, node);
95220             ts.Debug.assert(lastNode === node);
95221             var substitute = lastSubstitution;
95222             lastNode = savedLastNode;
95223             lastSubstitution = savedLastSubstitution;
95224             preserveSourceNewlines = savedPreserveSourceNewlines;
95225             return substitute || node;
95226         }
95227         function getPipelinePhase(phase, emitHint, node) {
95228             switch (phase) {
95229                 case 0 /* Notification */:
95230                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
95231                         return pipelineEmitWithNotification;
95232                     }
95233                 // falls through
95234                 case 1 /* Substitution */:
95235                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
95236                         return pipelineEmitWithSubstitution;
95237                     }
95238                 // falls through
95239                 case 2 /* Comments */:
95240                     if (!commentsDisabled && node.kind !== 290 /* SourceFile */) {
95241                         return pipelineEmitWithComments;
95242                     }
95243                 // falls through
95244                 case 3 /* SourceMaps */:
95245                     if (!sourceMapsDisabled && node.kind !== 290 /* SourceFile */ && !ts.isInJsonFile(node)) {
95246                         return pipelineEmitWithSourceMap;
95247                     }
95248                 // falls through
95249                 case 4 /* Emit */:
95250                     return pipelineEmitWithHint;
95251                 default:
95252                     return ts.Debug.assertNever(phase);
95253             }
95254         }
95255         function getNextPipelinePhase(currentPhase, emitHint, node) {
95256             return getPipelinePhase(currentPhase + 1, emitHint, node);
95257         }
95258         function pipelineEmitWithNotification(hint, node) {
95259             ts.Debug.assert(lastNode === node);
95260             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
95261             onEmitNode(hint, node, pipelinePhase);
95262             ts.Debug.assert(lastNode === node);
95263         }
95264         function pipelineEmitWithHint(hint, node) {
95265             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95266             if (hint === 0 /* SourceFile */)
95267                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
95268             if (hint === 2 /* IdentifierName */)
95269                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
95270             if (hint === 6 /* JsxAttributeValue */)
95271                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
95272             if (hint === 3 /* MappedTypeParameter */)
95273                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
95274             if (hint === 5 /* EmbeddedStatement */) {
95275                 ts.Debug.assertNode(node, ts.isEmptyStatement);
95276                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
95277             }
95278             if (hint === 4 /* Unspecified */) {
95279                 if (ts.isKeyword(node.kind))
95280                     return writeTokenNode(node, writeKeyword);
95281                 switch (node.kind) {
95282                     // Pseudo-literals
95283                     case 15 /* TemplateHead */:
95284                     case 16 /* TemplateMiddle */:
95285                     case 17 /* TemplateTail */:
95286                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95287                     case 292 /* UnparsedSource */:
95288                     case 286 /* UnparsedPrepend */:
95289                         return emitUnparsedSourceOrPrepend(node);
95290                     case 285 /* UnparsedPrologue */:
95291                         return writeUnparsedNode(node);
95292                     case 287 /* UnparsedText */:
95293                     case 288 /* UnparsedInternalText */:
95294                         return emitUnparsedTextLike(node);
95295                     case 289 /* UnparsedSyntheticReference */:
95296                         return emitUnparsedSyntheticReference(node);
95297                     // Identifiers
95298                     case 75 /* Identifier */:
95299                         return emitIdentifier(node);
95300                     // PrivateIdentifiers
95301                     case 76 /* PrivateIdentifier */:
95302                         return emitPrivateIdentifier(node);
95303                     // Parse tree nodes
95304                     // Names
95305                     case 153 /* QualifiedName */:
95306                         return emitQualifiedName(node);
95307                     case 154 /* ComputedPropertyName */:
95308                         return emitComputedPropertyName(node);
95309                     // Signature elements
95310                     case 155 /* TypeParameter */:
95311                         return emitTypeParameter(node);
95312                     case 156 /* Parameter */:
95313                         return emitParameter(node);
95314                     case 157 /* Decorator */:
95315                         return emitDecorator(node);
95316                     // Type members
95317                     case 158 /* PropertySignature */:
95318                         return emitPropertySignature(node);
95319                     case 159 /* PropertyDeclaration */:
95320                         return emitPropertyDeclaration(node);
95321                     case 160 /* MethodSignature */:
95322                         return emitMethodSignature(node);
95323                     case 161 /* MethodDeclaration */:
95324                         return emitMethodDeclaration(node);
95325                     case 162 /* Constructor */:
95326                         return emitConstructor(node);
95327                     case 163 /* GetAccessor */:
95328                     case 164 /* SetAccessor */:
95329                         return emitAccessorDeclaration(node);
95330                     case 165 /* CallSignature */:
95331                         return emitCallSignature(node);
95332                     case 166 /* ConstructSignature */:
95333                         return emitConstructSignature(node);
95334                     case 167 /* IndexSignature */:
95335                         return emitIndexSignature(node);
95336                     // Types
95337                     case 168 /* TypePredicate */:
95338                         return emitTypePredicate(node);
95339                     case 169 /* TypeReference */:
95340                         return emitTypeReference(node);
95341                     case 170 /* FunctionType */:
95342                         return emitFunctionType(node);
95343                     case 300 /* JSDocFunctionType */:
95344                         return emitJSDocFunctionType(node);
95345                     case 171 /* ConstructorType */:
95346                         return emitConstructorType(node);
95347                     case 172 /* TypeQuery */:
95348                         return emitTypeQuery(node);
95349                     case 173 /* TypeLiteral */:
95350                         return emitTypeLiteral(node);
95351                     case 174 /* ArrayType */:
95352                         return emitArrayType(node);
95353                     case 175 /* TupleType */:
95354                         return emitTupleType(node);
95355                     case 176 /* OptionalType */:
95356                         return emitOptionalType(node);
95357                     case 178 /* UnionType */:
95358                         return emitUnionType(node);
95359                     case 179 /* IntersectionType */:
95360                         return emitIntersectionType(node);
95361                     case 180 /* ConditionalType */:
95362                         return emitConditionalType(node);
95363                     case 181 /* InferType */:
95364                         return emitInferType(node);
95365                     case 182 /* ParenthesizedType */:
95366                         return emitParenthesizedType(node);
95367                     case 216 /* ExpressionWithTypeArguments */:
95368                         return emitExpressionWithTypeArguments(node);
95369                     case 183 /* ThisType */:
95370                         return emitThisType();
95371                     case 184 /* TypeOperator */:
95372                         return emitTypeOperator(node);
95373                     case 185 /* IndexedAccessType */:
95374                         return emitIndexedAccessType(node);
95375                     case 186 /* MappedType */:
95376                         return emitMappedType(node);
95377                     case 187 /* LiteralType */:
95378                         return emitLiteralType(node);
95379                     case 188 /* ImportType */:
95380                         return emitImportTypeNode(node);
95381                     case 295 /* JSDocAllType */:
95382                         writePunctuation("*");
95383                         return;
95384                     case 296 /* JSDocUnknownType */:
95385                         writePunctuation("?");
95386                         return;
95387                     case 297 /* JSDocNullableType */:
95388                         return emitJSDocNullableType(node);
95389                     case 298 /* JSDocNonNullableType */:
95390                         return emitJSDocNonNullableType(node);
95391                     case 299 /* JSDocOptionalType */:
95392                         return emitJSDocOptionalType(node);
95393                     case 177 /* RestType */:
95394                     case 301 /* JSDocVariadicType */:
95395                         return emitRestOrJSDocVariadicType(node);
95396                     // Binding patterns
95397                     case 189 /* ObjectBindingPattern */:
95398                         return emitObjectBindingPattern(node);
95399                     case 190 /* ArrayBindingPattern */:
95400                         return emitArrayBindingPattern(node);
95401                     case 191 /* BindingElement */:
95402                         return emitBindingElement(node);
95403                     // Misc
95404                     case 221 /* TemplateSpan */:
95405                         return emitTemplateSpan(node);
95406                     case 222 /* SemicolonClassElement */:
95407                         return emitSemicolonClassElement();
95408                     // Statements
95409                     case 223 /* Block */:
95410                         return emitBlock(node);
95411                     case 225 /* VariableStatement */:
95412                         return emitVariableStatement(node);
95413                     case 224 /* EmptyStatement */:
95414                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
95415                     case 226 /* ExpressionStatement */:
95416                         return emitExpressionStatement(node);
95417                     case 227 /* IfStatement */:
95418                         return emitIfStatement(node);
95419                     case 228 /* DoStatement */:
95420                         return emitDoStatement(node);
95421                     case 229 /* WhileStatement */:
95422                         return emitWhileStatement(node);
95423                     case 230 /* ForStatement */:
95424                         return emitForStatement(node);
95425                     case 231 /* ForInStatement */:
95426                         return emitForInStatement(node);
95427                     case 232 /* ForOfStatement */:
95428                         return emitForOfStatement(node);
95429                     case 233 /* ContinueStatement */:
95430                         return emitContinueStatement(node);
95431                     case 234 /* BreakStatement */:
95432                         return emitBreakStatement(node);
95433                     case 235 /* ReturnStatement */:
95434                         return emitReturnStatement(node);
95435                     case 236 /* WithStatement */:
95436                         return emitWithStatement(node);
95437                     case 237 /* SwitchStatement */:
95438                         return emitSwitchStatement(node);
95439                     case 238 /* LabeledStatement */:
95440                         return emitLabeledStatement(node);
95441                     case 239 /* ThrowStatement */:
95442                         return emitThrowStatement(node);
95443                     case 240 /* TryStatement */:
95444                         return emitTryStatement(node);
95445                     case 241 /* DebuggerStatement */:
95446                         return emitDebuggerStatement(node);
95447                     // Declarations
95448                     case 242 /* VariableDeclaration */:
95449                         return emitVariableDeclaration(node);
95450                     case 243 /* VariableDeclarationList */:
95451                         return emitVariableDeclarationList(node);
95452                     case 244 /* FunctionDeclaration */:
95453                         return emitFunctionDeclaration(node);
95454                     case 245 /* ClassDeclaration */:
95455                         return emitClassDeclaration(node);
95456                     case 246 /* InterfaceDeclaration */:
95457                         return emitInterfaceDeclaration(node);
95458                     case 247 /* TypeAliasDeclaration */:
95459                         return emitTypeAliasDeclaration(node);
95460                     case 248 /* EnumDeclaration */:
95461                         return emitEnumDeclaration(node);
95462                     case 249 /* ModuleDeclaration */:
95463                         return emitModuleDeclaration(node);
95464                     case 250 /* ModuleBlock */:
95465                         return emitModuleBlock(node);
95466                     case 251 /* CaseBlock */:
95467                         return emitCaseBlock(node);
95468                     case 252 /* NamespaceExportDeclaration */:
95469                         return emitNamespaceExportDeclaration(node);
95470                     case 253 /* ImportEqualsDeclaration */:
95471                         return emitImportEqualsDeclaration(node);
95472                     case 254 /* ImportDeclaration */:
95473                         return emitImportDeclaration(node);
95474                     case 255 /* ImportClause */:
95475                         return emitImportClause(node);
95476                     case 256 /* NamespaceImport */:
95477                         return emitNamespaceImport(node);
95478                     case 262 /* NamespaceExport */:
95479                         return emitNamespaceExport(node);
95480                     case 257 /* NamedImports */:
95481                         return emitNamedImports(node);
95482                     case 258 /* ImportSpecifier */:
95483                         return emitImportSpecifier(node);
95484                     case 259 /* ExportAssignment */:
95485                         return emitExportAssignment(node);
95486                     case 260 /* ExportDeclaration */:
95487                         return emitExportDeclaration(node);
95488                     case 261 /* NamedExports */:
95489                         return emitNamedExports(node);
95490                     case 263 /* ExportSpecifier */:
95491                         return emitExportSpecifier(node);
95492                     case 264 /* MissingDeclaration */:
95493                         return;
95494                     // Module references
95495                     case 265 /* ExternalModuleReference */:
95496                         return emitExternalModuleReference(node);
95497                     // JSX (non-expression)
95498                     case 11 /* JsxText */:
95499                         return emitJsxText(node);
95500                     case 268 /* JsxOpeningElement */:
95501                     case 271 /* JsxOpeningFragment */:
95502                         return emitJsxOpeningElementOrFragment(node);
95503                     case 269 /* JsxClosingElement */:
95504                     case 272 /* JsxClosingFragment */:
95505                         return emitJsxClosingElementOrFragment(node);
95506                     case 273 /* JsxAttribute */:
95507                         return emitJsxAttribute(node);
95508                     case 274 /* JsxAttributes */:
95509                         return emitJsxAttributes(node);
95510                     case 275 /* JsxSpreadAttribute */:
95511                         return emitJsxSpreadAttribute(node);
95512                     case 276 /* JsxExpression */:
95513                         return emitJsxExpression(node);
95514                     // Clauses
95515                     case 277 /* CaseClause */:
95516                         return emitCaseClause(node);
95517                     case 278 /* DefaultClause */:
95518                         return emitDefaultClause(node);
95519                     case 279 /* HeritageClause */:
95520                         return emitHeritageClause(node);
95521                     case 280 /* CatchClause */:
95522                         return emitCatchClause(node);
95523                     // Property assignments
95524                     case 281 /* PropertyAssignment */:
95525                         return emitPropertyAssignment(node);
95526                     case 282 /* ShorthandPropertyAssignment */:
95527                         return emitShorthandPropertyAssignment(node);
95528                     case 283 /* SpreadAssignment */:
95529                         return emitSpreadAssignment(node);
95530                     // Enum
95531                     case 284 /* EnumMember */:
95532                         return emitEnumMember(node);
95533                     // JSDoc nodes (only used in codefixes currently)
95534                     case 317 /* JSDocParameterTag */:
95535                     case 323 /* JSDocPropertyTag */:
95536                         return emitJSDocPropertyLikeTag(node);
95537                     case 318 /* JSDocReturnTag */:
95538                     case 320 /* JSDocTypeTag */:
95539                     case 319 /* JSDocThisTag */:
95540                     case 316 /* JSDocEnumTag */:
95541                         return emitJSDocSimpleTypedTag(node);
95542                     case 308 /* JSDocImplementsTag */:
95543                     case 307 /* JSDocAugmentsTag */:
95544                         return emitJSDocHeritageTag(node);
95545                     case 321 /* JSDocTemplateTag */:
95546                         return emitJSDocTemplateTag(node);
95547                     case 322 /* JSDocTypedefTag */:
95548                         return emitJSDocTypedefTag(node);
95549                     case 315 /* JSDocCallbackTag */:
95550                         return emitJSDocCallbackTag(node);
95551                     case 305 /* JSDocSignature */:
95552                         return emitJSDocSignature(node);
95553                     case 304 /* JSDocTypeLiteral */:
95554                         return emitJSDocTypeLiteral(node);
95555                     case 310 /* JSDocClassTag */:
95556                     case 306 /* JSDocTag */:
95557                         return emitJSDocSimpleTag(node);
95558                     case 303 /* JSDocComment */:
95559                         return emitJSDoc(node);
95560                     // Transformation nodes (ignored)
95561                 }
95562                 if (ts.isExpression(node)) {
95563                     hint = 1 /* Expression */;
95564                     if (substituteNode !== ts.noEmitSubstitution) {
95565                         lastSubstitution = node = substituteNode(hint, node);
95566                     }
95567                 }
95568                 else if (ts.isToken(node)) {
95569                     return writeTokenNode(node, writePunctuation);
95570                 }
95571             }
95572             if (hint === 1 /* Expression */) {
95573                 switch (node.kind) {
95574                     // Literals
95575                     case 8 /* NumericLiteral */:
95576                     case 9 /* BigIntLiteral */:
95577                         return emitNumericOrBigIntLiteral(node);
95578                     case 10 /* StringLiteral */:
95579                     case 13 /* RegularExpressionLiteral */:
95580                     case 14 /* NoSubstitutionTemplateLiteral */:
95581                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
95582                     // Identifiers
95583                     case 75 /* Identifier */:
95584                         return emitIdentifier(node);
95585                     // Reserved words
95586                     case 91 /* FalseKeyword */:
95587                     case 100 /* NullKeyword */:
95588                     case 102 /* SuperKeyword */:
95589                     case 106 /* TrueKeyword */:
95590                     case 104 /* ThisKeyword */:
95591                     case 96 /* ImportKeyword */:
95592                         writeTokenNode(node, writeKeyword);
95593                         return;
95594                     // Expressions
95595                     case 192 /* ArrayLiteralExpression */:
95596                         return emitArrayLiteralExpression(node);
95597                     case 193 /* ObjectLiteralExpression */:
95598                         return emitObjectLiteralExpression(node);
95599                     case 194 /* PropertyAccessExpression */:
95600                         return emitPropertyAccessExpression(node);
95601                     case 195 /* ElementAccessExpression */:
95602                         return emitElementAccessExpression(node);
95603                     case 196 /* CallExpression */:
95604                         return emitCallExpression(node);
95605                     case 197 /* NewExpression */:
95606                         return emitNewExpression(node);
95607                     case 198 /* TaggedTemplateExpression */:
95608                         return emitTaggedTemplateExpression(node);
95609                     case 199 /* TypeAssertionExpression */:
95610                         return emitTypeAssertionExpression(node);
95611                     case 200 /* ParenthesizedExpression */:
95612                         return emitParenthesizedExpression(node);
95613                     case 201 /* FunctionExpression */:
95614                         return emitFunctionExpression(node);
95615                     case 202 /* ArrowFunction */:
95616                         return emitArrowFunction(node);
95617                     case 203 /* DeleteExpression */:
95618                         return emitDeleteExpression(node);
95619                     case 204 /* TypeOfExpression */:
95620                         return emitTypeOfExpression(node);
95621                     case 205 /* VoidExpression */:
95622                         return emitVoidExpression(node);
95623                     case 206 /* AwaitExpression */:
95624                         return emitAwaitExpression(node);
95625                     case 207 /* PrefixUnaryExpression */:
95626                         return emitPrefixUnaryExpression(node);
95627                     case 208 /* PostfixUnaryExpression */:
95628                         return emitPostfixUnaryExpression(node);
95629                     case 209 /* BinaryExpression */:
95630                         return emitBinaryExpression(node);
95631                     case 210 /* ConditionalExpression */:
95632                         return emitConditionalExpression(node);
95633                     case 211 /* TemplateExpression */:
95634                         return emitTemplateExpression(node);
95635                     case 212 /* YieldExpression */:
95636                         return emitYieldExpression(node);
95637                     case 213 /* SpreadElement */:
95638                         return emitSpreadExpression(node);
95639                     case 214 /* ClassExpression */:
95640                         return emitClassExpression(node);
95641                     case 215 /* OmittedExpression */:
95642                         return;
95643                     case 217 /* AsExpression */:
95644                         return emitAsExpression(node);
95645                     case 218 /* NonNullExpression */:
95646                         return emitNonNullExpression(node);
95647                     case 219 /* MetaProperty */:
95648                         return emitMetaProperty(node);
95649                     // JSX
95650                     case 266 /* JsxElement */:
95651                         return emitJsxElement(node);
95652                     case 267 /* JsxSelfClosingElement */:
95653                         return emitJsxSelfClosingElement(node);
95654                     case 270 /* JsxFragment */:
95655                         return emitJsxFragment(node);
95656                     // Transformation nodes
95657                     case 326 /* PartiallyEmittedExpression */:
95658                         return emitPartiallyEmittedExpression(node);
95659                     case 327 /* CommaListExpression */:
95660                         return emitCommaList(node);
95661                 }
95662             }
95663         }
95664         function emitMappedTypeParameter(node) {
95665             emit(node.name);
95666             writeSpace();
95667             writeKeyword("in");
95668             writeSpace();
95669             emit(node.constraint);
95670         }
95671         function pipelineEmitWithSubstitution(hint, node) {
95672             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95673             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
95674             pipelinePhase(hint, lastSubstitution);
95675             ts.Debug.assert(lastNode === node || lastSubstitution === node);
95676         }
95677         function getHelpersFromBundledSourceFiles(bundle) {
95678             var result;
95679             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
95680                 return undefined;
95681             }
95682             var bundledHelpers = ts.createMap();
95683             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
95684                 var sourceFile = _b[_a];
95685                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
95686                 var helpers = getSortedEmitHelpers(sourceFile);
95687                 if (!helpers)
95688                     continue;
95689                 for (var _c = 0, helpers_4 = helpers; _c < helpers_4.length; _c++) {
95690                     var helper = helpers_4[_c];
95691                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
95692                         bundledHelpers.set(helper.name, true);
95693                         (result || (result = [])).push(helper.name);
95694                     }
95695                 }
95696             }
95697             return result;
95698         }
95699         function emitHelpers(node) {
95700             var helpersEmitted = false;
95701             var bundle = node.kind === 291 /* Bundle */ ? node : undefined;
95702             if (bundle && moduleKind === ts.ModuleKind.None) {
95703                 return;
95704             }
95705             var numPrepends = bundle ? bundle.prepends.length : 0;
95706             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
95707             for (var i = 0; i < numNodes; i++) {
95708                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
95709                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
95710                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
95711                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
95712                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
95713                 if (helpers) {
95714                     for (var _a = 0, helpers_5 = helpers; _a < helpers_5.length; _a++) {
95715                         var helper = helpers_5[_a];
95716                         if (!helper.scoped) {
95717                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
95718                             // option is set, or if it can be imported and the importHelpers compiler
95719                             // option is set.
95720                             if (shouldSkip)
95721                                 continue;
95722                             // Skip the helper if it can be bundled but hasn't already been emitted and we
95723                             // are emitting a bundled module.
95724                             if (shouldBundle) {
95725                                 if (bundledHelpers.get(helper.name)) {
95726                                     continue;
95727                                 }
95728                                 bundledHelpers.set(helper.name, true);
95729                             }
95730                         }
95731                         else if (bundle) {
95732                             // Skip the helper if it is scoped and we are emitting bundled helpers
95733                             continue;
95734                         }
95735                         var pos = getTextPosWithWriteLine();
95736                         if (typeof helper.text === "string") {
95737                             writeLines(helper.text);
95738                         }
95739                         else {
95740                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
95741                         }
95742                         if (bundleFileInfo)
95743                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
95744                         helpersEmitted = true;
95745                     }
95746                 }
95747             }
95748             return helpersEmitted;
95749         }
95750         function getSortedEmitHelpers(node) {
95751             var helpers = ts.getEmitHelpers(node);
95752             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
95753         }
95754         //
95755         // Literals/Pseudo-literals
95756         //
95757         // SyntaxKind.NumericLiteral
95758         // SyntaxKind.BigIntLiteral
95759         function emitNumericOrBigIntLiteral(node) {
95760             emitLiteral(node, /*jsxAttributeEscape*/ false);
95761         }
95762         // SyntaxKind.StringLiteral
95763         // SyntaxKind.RegularExpressionLiteral
95764         // SyntaxKind.NoSubstitutionTemplateLiteral
95765         // SyntaxKind.TemplateHead
95766         // SyntaxKind.TemplateMiddle
95767         // SyntaxKind.TemplateTail
95768         function emitLiteral(node, jsxAttributeEscape) {
95769             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
95770             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
95771                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
95772                 writeLiteral(text);
95773             }
95774             else {
95775                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
95776                 writeStringLiteral(text);
95777             }
95778         }
95779         // SyntaxKind.UnparsedSource
95780         // SyntaxKind.UnparsedPrepend
95781         function emitUnparsedSourceOrPrepend(unparsed) {
95782             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
95783                 var text = _b[_a];
95784                 writeLine();
95785                 emit(text);
95786             }
95787         }
95788         // SyntaxKind.UnparsedPrologue
95789         // SyntaxKind.UnparsedText
95790         // SyntaxKind.UnparsedInternal
95791         // SyntaxKind.UnparsedSyntheticReference
95792         function writeUnparsedNode(unparsed) {
95793             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
95794         }
95795         // SyntaxKind.UnparsedText
95796         // SyntaxKind.UnparsedInternal
95797         function emitUnparsedTextLike(unparsed) {
95798             var pos = getTextPosWithWriteLine();
95799             writeUnparsedNode(unparsed);
95800             if (bundleFileInfo) {
95801                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 287 /* UnparsedText */ ?
95802                     "text" /* Text */ :
95803                     "internal" /* Internal */);
95804             }
95805         }
95806         // SyntaxKind.UnparsedSyntheticReference
95807         function emitUnparsedSyntheticReference(unparsed) {
95808             var pos = getTextPosWithWriteLine();
95809             writeUnparsedNode(unparsed);
95810             if (bundleFileInfo) {
95811                 var section = ts.clone(unparsed.section);
95812                 section.pos = pos;
95813                 section.end = writer.getTextPos();
95814                 bundleFileInfo.sections.push(section);
95815             }
95816         }
95817         //
95818         // Identifiers
95819         //
95820         function emitIdentifier(node) {
95821             var writeText = node.symbol ? writeSymbol : write;
95822             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95823             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
95824         }
95825         //
95826         // Names
95827         //
95828         function emitPrivateIdentifier(node) {
95829             var writeText = node.symbol ? writeSymbol : write;
95830             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
95831         }
95832         function emitQualifiedName(node) {
95833             emitEntityName(node.left);
95834             writePunctuation(".");
95835             emit(node.right);
95836         }
95837         function emitEntityName(node) {
95838             if (node.kind === 75 /* Identifier */) {
95839                 emitExpression(node);
95840             }
95841             else {
95842                 emit(node);
95843             }
95844         }
95845         function emitComputedPropertyName(node) {
95846             writePunctuation("[");
95847             emitExpression(node.expression);
95848             writePunctuation("]");
95849         }
95850         //
95851         // Signature elements
95852         //
95853         function emitTypeParameter(node) {
95854             emit(node.name);
95855             if (node.constraint) {
95856                 writeSpace();
95857                 writeKeyword("extends");
95858                 writeSpace();
95859                 emit(node.constraint);
95860             }
95861             if (node.default) {
95862                 writeSpace();
95863                 writeOperator("=");
95864                 writeSpace();
95865                 emit(node.default);
95866             }
95867         }
95868         function emitParameter(node) {
95869             emitDecorators(node, node.decorators);
95870             emitModifiers(node, node.modifiers);
95871             emit(node.dotDotDotToken);
95872             emitNodeWithWriter(node.name, writeParameter);
95873             emit(node.questionToken);
95874             if (node.parent && node.parent.kind === 300 /* JSDocFunctionType */ && !node.name) {
95875                 emit(node.type);
95876             }
95877             else {
95878                 emitTypeAnnotation(node.type);
95879             }
95880             // 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.
95881             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);
95882         }
95883         function emitDecorator(decorator) {
95884             writePunctuation("@");
95885             emitExpression(decorator.expression);
95886         }
95887         //
95888         // Type members
95889         //
95890         function emitPropertySignature(node) {
95891             emitDecorators(node, node.decorators);
95892             emitModifiers(node, node.modifiers);
95893             emitNodeWithWriter(node.name, writeProperty);
95894             emit(node.questionToken);
95895             emitTypeAnnotation(node.type);
95896             writeTrailingSemicolon();
95897         }
95898         function emitPropertyDeclaration(node) {
95899             emitDecorators(node, node.decorators);
95900             emitModifiers(node, node.modifiers);
95901             emit(node.name);
95902             emit(node.questionToken);
95903             emit(node.exclamationToken);
95904             emitTypeAnnotation(node.type);
95905             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
95906             writeTrailingSemicolon();
95907         }
95908         function emitMethodSignature(node) {
95909             pushNameGenerationScope(node);
95910             emitDecorators(node, node.decorators);
95911             emitModifiers(node, node.modifiers);
95912             emit(node.name);
95913             emit(node.questionToken);
95914             emitTypeParameters(node, node.typeParameters);
95915             emitParameters(node, node.parameters);
95916             emitTypeAnnotation(node.type);
95917             writeTrailingSemicolon();
95918             popNameGenerationScope(node);
95919         }
95920         function emitMethodDeclaration(node) {
95921             emitDecorators(node, node.decorators);
95922             emitModifiers(node, node.modifiers);
95923             emit(node.asteriskToken);
95924             emit(node.name);
95925             emit(node.questionToken);
95926             emitSignatureAndBody(node, emitSignatureHead);
95927         }
95928         function emitConstructor(node) {
95929             emitModifiers(node, node.modifiers);
95930             writeKeyword("constructor");
95931             emitSignatureAndBody(node, emitSignatureHead);
95932         }
95933         function emitAccessorDeclaration(node) {
95934             emitDecorators(node, node.decorators);
95935             emitModifiers(node, node.modifiers);
95936             writeKeyword(node.kind === 163 /* GetAccessor */ ? "get" : "set");
95937             writeSpace();
95938             emit(node.name);
95939             emitSignatureAndBody(node, emitSignatureHead);
95940         }
95941         function emitCallSignature(node) {
95942             pushNameGenerationScope(node);
95943             emitDecorators(node, node.decorators);
95944             emitModifiers(node, node.modifiers);
95945             emitTypeParameters(node, node.typeParameters);
95946             emitParameters(node, node.parameters);
95947             emitTypeAnnotation(node.type);
95948             writeTrailingSemicolon();
95949             popNameGenerationScope(node);
95950         }
95951         function emitConstructSignature(node) {
95952             pushNameGenerationScope(node);
95953             emitDecorators(node, node.decorators);
95954             emitModifiers(node, node.modifiers);
95955             writeKeyword("new");
95956             writeSpace();
95957             emitTypeParameters(node, node.typeParameters);
95958             emitParameters(node, node.parameters);
95959             emitTypeAnnotation(node.type);
95960             writeTrailingSemicolon();
95961             popNameGenerationScope(node);
95962         }
95963         function emitIndexSignature(node) {
95964             emitDecorators(node, node.decorators);
95965             emitModifiers(node, node.modifiers);
95966             emitParametersForIndexSignature(node, node.parameters);
95967             emitTypeAnnotation(node.type);
95968             writeTrailingSemicolon();
95969         }
95970         function emitSemicolonClassElement() {
95971             writeTrailingSemicolon();
95972         }
95973         //
95974         // Types
95975         //
95976         function emitTypePredicate(node) {
95977             if (node.assertsModifier) {
95978                 emit(node.assertsModifier);
95979                 writeSpace();
95980             }
95981             emit(node.parameterName);
95982             if (node.type) {
95983                 writeSpace();
95984                 writeKeyword("is");
95985                 writeSpace();
95986                 emit(node.type);
95987             }
95988         }
95989         function emitTypeReference(node) {
95990             emit(node.typeName);
95991             emitTypeArguments(node, node.typeArguments);
95992         }
95993         function emitFunctionType(node) {
95994             pushNameGenerationScope(node);
95995             emitTypeParameters(node, node.typeParameters);
95996             emitParametersForArrow(node, node.parameters);
95997             writeSpace();
95998             writePunctuation("=>");
95999             writeSpace();
96000             emit(node.type);
96001             popNameGenerationScope(node);
96002         }
96003         function emitJSDocFunctionType(node) {
96004             writeKeyword("function");
96005             emitParameters(node, node.parameters);
96006             writePunctuation(":");
96007             emit(node.type);
96008         }
96009         function emitJSDocNullableType(node) {
96010             writePunctuation("?");
96011             emit(node.type);
96012         }
96013         function emitJSDocNonNullableType(node) {
96014             writePunctuation("!");
96015             emit(node.type);
96016         }
96017         function emitJSDocOptionalType(node) {
96018             emit(node.type);
96019             writePunctuation("=");
96020         }
96021         function emitConstructorType(node) {
96022             pushNameGenerationScope(node);
96023             writeKeyword("new");
96024             writeSpace();
96025             emitTypeParameters(node, node.typeParameters);
96026             emitParameters(node, node.parameters);
96027             writeSpace();
96028             writePunctuation("=>");
96029             writeSpace();
96030             emit(node.type);
96031             popNameGenerationScope(node);
96032         }
96033         function emitTypeQuery(node) {
96034             writeKeyword("typeof");
96035             writeSpace();
96036             emit(node.exprName);
96037         }
96038         function emitTypeLiteral(node) {
96039             writePunctuation("{");
96040             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
96041             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
96042             writePunctuation("}");
96043         }
96044         function emitArrayType(node) {
96045             emit(node.elementType);
96046             writePunctuation("[");
96047             writePunctuation("]");
96048         }
96049         function emitRestOrJSDocVariadicType(node) {
96050             writePunctuation("...");
96051             emit(node.type);
96052         }
96053         function emitTupleType(node) {
96054             writePunctuation("[");
96055             emitList(node, node.elementTypes, 528 /* TupleTypeElements */);
96056             writePunctuation("]");
96057         }
96058         function emitOptionalType(node) {
96059             emit(node.type);
96060             writePunctuation("?");
96061         }
96062         function emitUnionType(node) {
96063             emitList(node, node.types, 516 /* UnionTypeConstituents */);
96064         }
96065         function emitIntersectionType(node) {
96066             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
96067         }
96068         function emitConditionalType(node) {
96069             emit(node.checkType);
96070             writeSpace();
96071             writeKeyword("extends");
96072             writeSpace();
96073             emit(node.extendsType);
96074             writeSpace();
96075             writePunctuation("?");
96076             writeSpace();
96077             emit(node.trueType);
96078             writeSpace();
96079             writePunctuation(":");
96080             writeSpace();
96081             emit(node.falseType);
96082         }
96083         function emitInferType(node) {
96084             writeKeyword("infer");
96085             writeSpace();
96086             emit(node.typeParameter);
96087         }
96088         function emitParenthesizedType(node) {
96089             writePunctuation("(");
96090             emit(node.type);
96091             writePunctuation(")");
96092         }
96093         function emitThisType() {
96094             writeKeyword("this");
96095         }
96096         function emitTypeOperator(node) {
96097             writeTokenText(node.operator, writeKeyword);
96098             writeSpace();
96099             emit(node.type);
96100         }
96101         function emitIndexedAccessType(node) {
96102             emit(node.objectType);
96103             writePunctuation("[");
96104             emit(node.indexType);
96105             writePunctuation("]");
96106         }
96107         function emitMappedType(node) {
96108             var emitFlags = ts.getEmitFlags(node);
96109             writePunctuation("{");
96110             if (emitFlags & 1 /* SingleLine */) {
96111                 writeSpace();
96112             }
96113             else {
96114                 writeLine();
96115                 increaseIndent();
96116             }
96117             if (node.readonlyToken) {
96118                 emit(node.readonlyToken);
96119                 if (node.readonlyToken.kind !== 138 /* ReadonlyKeyword */) {
96120                     writeKeyword("readonly");
96121                 }
96122                 writeSpace();
96123             }
96124             writePunctuation("[");
96125             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
96126             writePunctuation("]");
96127             if (node.questionToken) {
96128                 emit(node.questionToken);
96129                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
96130                     writePunctuation("?");
96131                 }
96132             }
96133             writePunctuation(":");
96134             writeSpace();
96135             emit(node.type);
96136             writeTrailingSemicolon();
96137             if (emitFlags & 1 /* SingleLine */) {
96138                 writeSpace();
96139             }
96140             else {
96141                 writeLine();
96142                 decreaseIndent();
96143             }
96144             writePunctuation("}");
96145         }
96146         function emitLiteralType(node) {
96147             emitExpression(node.literal);
96148         }
96149         function emitImportTypeNode(node) {
96150             if (node.isTypeOf) {
96151                 writeKeyword("typeof");
96152                 writeSpace();
96153             }
96154             writeKeyword("import");
96155             writePunctuation("(");
96156             emit(node.argument);
96157             writePunctuation(")");
96158             if (node.qualifier) {
96159                 writePunctuation(".");
96160                 emit(node.qualifier);
96161             }
96162             emitTypeArguments(node, node.typeArguments);
96163         }
96164         //
96165         // Binding patterns
96166         //
96167         function emitObjectBindingPattern(node) {
96168             writePunctuation("{");
96169             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
96170             writePunctuation("}");
96171         }
96172         function emitArrayBindingPattern(node) {
96173             writePunctuation("[");
96174             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
96175             writePunctuation("]");
96176         }
96177         function emitBindingElement(node) {
96178             emit(node.dotDotDotToken);
96179             if (node.propertyName) {
96180                 emit(node.propertyName);
96181                 writePunctuation(":");
96182                 writeSpace();
96183             }
96184             emit(node.name);
96185             emitInitializer(node.initializer, node.name.end, node);
96186         }
96187         //
96188         // Expressions
96189         //
96190         function emitArrayLiteralExpression(node) {
96191             var elements = node.elements;
96192             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96193             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
96194         }
96195         function emitObjectLiteralExpression(node) {
96196             ts.forEach(node.properties, generateMemberNames);
96197             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96198             if (indentedFlag) {
96199                 increaseIndent();
96200             }
96201             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
96202             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
96203             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
96204             if (indentedFlag) {
96205                 decreaseIndent();
96206             }
96207         }
96208         function emitPropertyAccessExpression(node) {
96209             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
96210             var token = node.questionDotToken || ts.createNode(24 /* DotToken */, node.expression.end, node.name.pos);
96211             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
96212             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
96213             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
96214             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
96215                 mayNeedDotDotForPropertyAccess(expression) &&
96216                 !writer.hasTrailingComment() &&
96217                 !writer.hasTrailingWhitespace();
96218             if (shouldEmitDotDot) {
96219                 writePunctuation(".");
96220             }
96221             if (node.questionDotToken) {
96222                 emit(token);
96223             }
96224             else {
96225                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
96226             }
96227             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
96228             emit(node.name);
96229             decreaseIndentIf(linesBeforeDot, linesAfterDot);
96230         }
96231         // 1..toString is a valid property access, emit a dot after the literal
96232         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
96233         function mayNeedDotDotForPropertyAccess(expression) {
96234             expression = ts.skipPartiallyEmittedExpressions(expression);
96235             if (ts.isNumericLiteral(expression)) {
96236                 // check if numeric literal is a decimal literal that was originally written with a dot
96237                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
96238                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
96239                 // if the expression doesn't have any comments that will be emitted.
96240                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
96241             }
96242             else if (ts.isAccessExpression(expression)) {
96243                 // check if constant enum value is integer
96244                 var constantValue = ts.getConstantValue(expression);
96245                 // isFinite handles cases when constantValue is undefined
96246                 return typeof constantValue === "number" && isFinite(constantValue)
96247                     && Math.floor(constantValue) === constantValue;
96248             }
96249         }
96250         function emitElementAccessExpression(node) {
96251             emitExpression(node.expression);
96252             emit(node.questionDotToken);
96253             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
96254             emitExpression(node.argumentExpression);
96255             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
96256         }
96257         function emitCallExpression(node) {
96258             emitExpression(node.expression);
96259             emit(node.questionDotToken);
96260             emitTypeArguments(node, node.typeArguments);
96261             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
96262         }
96263         function emitNewExpression(node) {
96264             emitTokenWithComment(99 /* NewKeyword */, node.pos, writeKeyword, node);
96265             writeSpace();
96266             emitExpression(node.expression);
96267             emitTypeArguments(node, node.typeArguments);
96268             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
96269         }
96270         function emitTaggedTemplateExpression(node) {
96271             emitExpression(node.tag);
96272             emitTypeArguments(node, node.typeArguments);
96273             writeSpace();
96274             emitExpression(node.template);
96275         }
96276         function emitTypeAssertionExpression(node) {
96277             writePunctuation("<");
96278             emit(node.type);
96279             writePunctuation(">");
96280             emitExpression(node.expression);
96281         }
96282         function emitParenthesizedExpression(node) {
96283             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
96284             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
96285             emitExpression(node.expression);
96286             writeLineSeparatorsAfter(node.expression, node);
96287             decreaseIndentIf(indented);
96288             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
96289         }
96290         function emitFunctionExpression(node) {
96291             generateNameIfNeeded(node.name);
96292             emitFunctionDeclarationOrExpression(node);
96293         }
96294         function emitArrowFunction(node) {
96295             emitDecorators(node, node.decorators);
96296             emitModifiers(node, node.modifiers);
96297             emitSignatureAndBody(node, emitArrowFunctionHead);
96298         }
96299         function emitArrowFunctionHead(node) {
96300             emitTypeParameters(node, node.typeParameters);
96301             emitParametersForArrow(node, node.parameters);
96302             emitTypeAnnotation(node.type);
96303             writeSpace();
96304             emit(node.equalsGreaterThanToken);
96305         }
96306         function emitDeleteExpression(node) {
96307             emitTokenWithComment(85 /* DeleteKeyword */, node.pos, writeKeyword, node);
96308             writeSpace();
96309             emitExpression(node.expression);
96310         }
96311         function emitTypeOfExpression(node) {
96312             emitTokenWithComment(108 /* TypeOfKeyword */, node.pos, writeKeyword, node);
96313             writeSpace();
96314             emitExpression(node.expression);
96315         }
96316         function emitVoidExpression(node) {
96317             emitTokenWithComment(110 /* VoidKeyword */, node.pos, writeKeyword, node);
96318             writeSpace();
96319             emitExpression(node.expression);
96320         }
96321         function emitAwaitExpression(node) {
96322             emitTokenWithComment(127 /* AwaitKeyword */, node.pos, writeKeyword, node);
96323             writeSpace();
96324             emitExpression(node.expression);
96325         }
96326         function emitPrefixUnaryExpression(node) {
96327             writeTokenText(node.operator, writeOperator);
96328             if (shouldEmitWhitespaceBeforeOperand(node)) {
96329                 writeSpace();
96330             }
96331             emitExpression(node.operand);
96332         }
96333         function shouldEmitWhitespaceBeforeOperand(node) {
96334             // In some cases, we need to emit a space between the operator and the operand. One obvious case
96335             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
96336             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
96337             // are just for clarity of exposition, and not part of the source code):
96338             //
96339             //  (+(+1))
96340             //  (+(++1))
96341             //
96342             // We need to emit a space in both cases. In the first case, the absence of a space will make
96343             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
96344             // expression a prefix increment whose operand is a plus expression - (++(+x))
96345             // The same is true of minus of course.
96346             var operand = node.operand;
96347             return operand.kind === 207 /* PrefixUnaryExpression */
96348                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
96349                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
96350         }
96351         function emitPostfixUnaryExpression(node) {
96352             emitExpression(node.operand);
96353             writeTokenText(node.operator, writeOperator);
96354         }
96355         var EmitBinaryExpressionState;
96356         (function (EmitBinaryExpressionState) {
96357             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
96358             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
96359             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
96360         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
96361         /**
96362          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
96363          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
96364          * not require notification/substitution/comment/sourcemap decorations.
96365          */
96366         function emitBinaryExpression(node) {
96367             var nodeStack = [node];
96368             var stateStack = [0 /* EmitLeft */];
96369             var stackIndex = 0;
96370             while (stackIndex >= 0) {
96371                 node = nodeStack[stackIndex];
96372                 switch (stateStack[stackIndex]) {
96373                     case 0 /* EmitLeft */: {
96374                         maybePipelineEmitExpression(node.left);
96375                         break;
96376                     }
96377                     case 1 /* EmitRight */: {
96378                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
96379                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96380                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96381                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
96382                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
96383                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 97 /* InKeyword */ ? writeKeyword : writeOperator);
96384                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
96385                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
96386                         maybePipelineEmitExpression(node.right);
96387                         break;
96388                     }
96389                     case 2 /* FinishEmit */: {
96390                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
96391                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
96392                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
96393                         stackIndex--;
96394                         break;
96395                     }
96396                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
96397                 }
96398             }
96399             function maybePipelineEmitExpression(next) {
96400                 // Advance the state of this unit of work,
96401                 stateStack[stackIndex]++;
96402                 // Then actually do the work of emitting the node `next` returned by the prior state
96403                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
96404                 // binary expression handling, where possible, to the contained work queue
96405                 // #region trampolinePipelineEmit
96406                 var savedLastNode = lastNode;
96407                 var savedLastSubstitution = lastSubstitution;
96408                 lastNode = next;
96409                 lastSubstitution = undefined;
96410                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
96411                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
96412                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
96413                     // skip all the intermediate indirection and push the expression directly onto the work stack
96414                     stackIndex++;
96415                     stateStack[stackIndex] = 0 /* EmitLeft */;
96416                     nodeStack[stackIndex] = next;
96417                 }
96418                 else {
96419                     pipelinePhase(1 /* Expression */, next);
96420                 }
96421                 ts.Debug.assert(lastNode === next);
96422                 lastNode = savedLastNode;
96423                 lastSubstitution = savedLastSubstitution;
96424                 // #endregion trampolinePipelineEmit
96425             }
96426         }
96427         function emitConditionalExpression(node) {
96428             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
96429             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
96430             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
96431             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
96432             emitExpression(node.condition);
96433             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
96434             emit(node.questionToken);
96435             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
96436             emitExpression(node.whenTrue);
96437             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
96438             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
96439             emit(node.colonToken);
96440             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
96441             emitExpression(node.whenFalse);
96442             decreaseIndentIf(linesBeforeColon, linesAfterColon);
96443         }
96444         function emitTemplateExpression(node) {
96445             emit(node.head);
96446             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
96447         }
96448         function emitYieldExpression(node) {
96449             emitTokenWithComment(121 /* YieldKeyword */, node.pos, writeKeyword, node);
96450             emit(node.asteriskToken);
96451             emitExpressionWithLeadingSpace(node.expression);
96452         }
96453         function emitSpreadExpression(node) {
96454             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
96455             emitExpression(node.expression);
96456         }
96457         function emitClassExpression(node) {
96458             generateNameIfNeeded(node.name);
96459             emitClassDeclarationOrExpression(node);
96460         }
96461         function emitExpressionWithTypeArguments(node) {
96462             emitExpression(node.expression);
96463             emitTypeArguments(node, node.typeArguments);
96464         }
96465         function emitAsExpression(node) {
96466             emitExpression(node.expression);
96467             if (node.type) {
96468                 writeSpace();
96469                 writeKeyword("as");
96470                 writeSpace();
96471                 emit(node.type);
96472             }
96473         }
96474         function emitNonNullExpression(node) {
96475             emitExpression(node.expression);
96476             writeOperator("!");
96477         }
96478         function emitMetaProperty(node) {
96479             writeToken(node.keywordToken, node.pos, writePunctuation);
96480             writePunctuation(".");
96481             emit(node.name);
96482         }
96483         //
96484         // Misc
96485         //
96486         function emitTemplateSpan(node) {
96487             emitExpression(node.expression);
96488             emit(node.literal);
96489         }
96490         //
96491         // Statements
96492         //
96493         function emitBlock(node) {
96494             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
96495         }
96496         function emitBlockStatements(node, forceSingleLine) {
96497             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
96498             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
96499             emitList(node, node.statements, format);
96500             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
96501         }
96502         function emitVariableStatement(node) {
96503             emitModifiers(node, node.modifiers);
96504             emit(node.declarationList);
96505             writeTrailingSemicolon();
96506         }
96507         function emitEmptyStatement(isEmbeddedStatement) {
96508             // While most trailing semicolons are possibly insignificant, an embedded "empty"
96509             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
96510             if (isEmbeddedStatement) {
96511                 writePunctuation(";");
96512             }
96513             else {
96514                 writeTrailingSemicolon();
96515             }
96516         }
96517         function emitExpressionStatement(node) {
96518             emitExpression(node.expression);
96519             // Emit semicolon in non json files
96520             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
96521             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
96522                 writeTrailingSemicolon();
96523             }
96524         }
96525         function emitIfStatement(node) {
96526             var openParenPos = emitTokenWithComment(95 /* IfKeyword */, node.pos, writeKeyword, node);
96527             writeSpace();
96528             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96529             emitExpression(node.expression);
96530             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96531             emitEmbeddedStatement(node, node.thenStatement);
96532             if (node.elseStatement) {
96533                 writeLineOrSpace(node);
96534                 emitTokenWithComment(87 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
96535                 if (node.elseStatement.kind === 227 /* IfStatement */) {
96536                     writeSpace();
96537                     emit(node.elseStatement);
96538                 }
96539                 else {
96540                     emitEmbeddedStatement(node, node.elseStatement);
96541                 }
96542             }
96543         }
96544         function emitWhileClause(node, startPos) {
96545             var openParenPos = emitTokenWithComment(111 /* WhileKeyword */, startPos, writeKeyword, node);
96546             writeSpace();
96547             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96548             emitExpression(node.expression);
96549             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96550         }
96551         function emitDoStatement(node) {
96552             emitTokenWithComment(86 /* DoKeyword */, node.pos, writeKeyword, node);
96553             emitEmbeddedStatement(node, node.statement);
96554             if (ts.isBlock(node.statement)) {
96555                 writeSpace();
96556             }
96557             else {
96558                 writeLineOrSpace(node);
96559             }
96560             emitWhileClause(node, node.statement.end);
96561             writeTrailingSemicolon();
96562         }
96563         function emitWhileStatement(node) {
96564             emitWhileClause(node, node.pos);
96565             emitEmbeddedStatement(node, node.statement);
96566         }
96567         function emitForStatement(node) {
96568             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96569             writeSpace();
96570             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
96571             emitForBinding(node.initializer);
96572             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
96573             emitExpressionWithLeadingSpace(node.condition);
96574             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
96575             emitExpressionWithLeadingSpace(node.incrementor);
96576             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
96577             emitEmbeddedStatement(node, node.statement);
96578         }
96579         function emitForInStatement(node) {
96580             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96581             writeSpace();
96582             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96583             emitForBinding(node.initializer);
96584             writeSpace();
96585             emitTokenWithComment(97 /* InKeyword */, node.initializer.end, writeKeyword, node);
96586             writeSpace();
96587             emitExpression(node.expression);
96588             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96589             emitEmbeddedStatement(node, node.statement);
96590         }
96591         function emitForOfStatement(node) {
96592             var openParenPos = emitTokenWithComment(93 /* ForKeyword */, node.pos, writeKeyword, node);
96593             writeSpace();
96594             emitWithTrailingSpace(node.awaitModifier);
96595             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96596             emitForBinding(node.initializer);
96597             writeSpace();
96598             emitTokenWithComment(152 /* OfKeyword */, node.initializer.end, writeKeyword, node);
96599             writeSpace();
96600             emitExpression(node.expression);
96601             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96602             emitEmbeddedStatement(node, node.statement);
96603         }
96604         function emitForBinding(node) {
96605             if (node !== undefined) {
96606                 if (node.kind === 243 /* VariableDeclarationList */) {
96607                     emit(node);
96608                 }
96609                 else {
96610                     emitExpression(node);
96611                 }
96612             }
96613         }
96614         function emitContinueStatement(node) {
96615             emitTokenWithComment(82 /* ContinueKeyword */, node.pos, writeKeyword, node);
96616             emitWithLeadingSpace(node.label);
96617             writeTrailingSemicolon();
96618         }
96619         function emitBreakStatement(node) {
96620             emitTokenWithComment(77 /* BreakKeyword */, node.pos, writeKeyword, node);
96621             emitWithLeadingSpace(node.label);
96622             writeTrailingSemicolon();
96623         }
96624         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
96625             var node = ts.getParseTreeNode(contextNode);
96626             var isSimilarNode = node && node.kind === contextNode.kind;
96627             var startPos = pos;
96628             if (isSimilarNode && currentSourceFile) {
96629                 pos = ts.skipTrivia(currentSourceFile.text, pos);
96630             }
96631             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
96632                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
96633                 if (needsIndent) {
96634                     increaseIndent();
96635                 }
96636                 emitLeadingCommentsOfPosition(startPos);
96637                 if (needsIndent) {
96638                     decreaseIndent();
96639                 }
96640             }
96641             pos = writeTokenText(token, writer, pos);
96642             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
96643                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
96644             }
96645             return pos;
96646         }
96647         function emitReturnStatement(node) {
96648             emitTokenWithComment(101 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
96649             emitExpressionWithLeadingSpace(node.expression);
96650             writeTrailingSemicolon();
96651         }
96652         function emitWithStatement(node) {
96653             var openParenPos = emitTokenWithComment(112 /* WithKeyword */, node.pos, writeKeyword, node);
96654             writeSpace();
96655             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96656             emitExpression(node.expression);
96657             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96658             emitEmbeddedStatement(node, node.statement);
96659         }
96660         function emitSwitchStatement(node) {
96661             var openParenPos = emitTokenWithComment(103 /* SwitchKeyword */, node.pos, writeKeyword, node);
96662             writeSpace();
96663             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
96664             emitExpression(node.expression);
96665             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
96666             writeSpace();
96667             emit(node.caseBlock);
96668         }
96669         function emitLabeledStatement(node) {
96670             emit(node.label);
96671             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
96672             writeSpace();
96673             emit(node.statement);
96674         }
96675         function emitThrowStatement(node) {
96676             emitTokenWithComment(105 /* ThrowKeyword */, node.pos, writeKeyword, node);
96677             emitExpressionWithLeadingSpace(node.expression);
96678             writeTrailingSemicolon();
96679         }
96680         function emitTryStatement(node) {
96681             emitTokenWithComment(107 /* TryKeyword */, node.pos, writeKeyword, node);
96682             writeSpace();
96683             emit(node.tryBlock);
96684             if (node.catchClause) {
96685                 writeLineOrSpace(node);
96686                 emit(node.catchClause);
96687             }
96688             if (node.finallyBlock) {
96689                 writeLineOrSpace(node);
96690                 emitTokenWithComment(92 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
96691                 writeSpace();
96692                 emit(node.finallyBlock);
96693             }
96694         }
96695         function emitDebuggerStatement(node) {
96696             writeToken(83 /* DebuggerKeyword */, node.pos, writeKeyword);
96697             writeTrailingSemicolon();
96698         }
96699         //
96700         // Declarations
96701         //
96702         function emitVariableDeclaration(node) {
96703             emit(node.name);
96704             emit(node.exclamationToken);
96705             emitTypeAnnotation(node.type);
96706             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
96707         }
96708         function emitVariableDeclarationList(node) {
96709             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
96710             writeSpace();
96711             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
96712         }
96713         function emitFunctionDeclaration(node) {
96714             emitFunctionDeclarationOrExpression(node);
96715         }
96716         function emitFunctionDeclarationOrExpression(node) {
96717             emitDecorators(node, node.decorators);
96718             emitModifiers(node, node.modifiers);
96719             writeKeyword("function");
96720             emit(node.asteriskToken);
96721             writeSpace();
96722             emitIdentifierName(node.name);
96723             emitSignatureAndBody(node, emitSignatureHead);
96724         }
96725         function emitBlockCallback(_hint, body) {
96726             emitBlockFunctionBody(body);
96727         }
96728         function emitSignatureAndBody(node, emitSignatureHead) {
96729             var body = node.body;
96730             if (body) {
96731                 if (ts.isBlock(body)) {
96732                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96733                     if (indentedFlag) {
96734                         increaseIndent();
96735                     }
96736                     pushNameGenerationScope(node);
96737                     ts.forEach(node.parameters, generateNames);
96738                     generateNames(node.body);
96739                     emitSignatureHead(node);
96740                     if (onEmitNode) {
96741                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
96742                     }
96743                     else {
96744                         emitBlockFunctionBody(body);
96745                     }
96746                     popNameGenerationScope(node);
96747                     if (indentedFlag) {
96748                         decreaseIndent();
96749                     }
96750                 }
96751                 else {
96752                     emitSignatureHead(node);
96753                     writeSpace();
96754                     emitExpression(body);
96755                 }
96756             }
96757             else {
96758                 emitSignatureHead(node);
96759                 writeTrailingSemicolon();
96760             }
96761         }
96762         function emitSignatureHead(node) {
96763             emitTypeParameters(node, node.typeParameters);
96764             emitParameters(node, node.parameters);
96765             emitTypeAnnotation(node.type);
96766         }
96767         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
96768             // We must emit a function body as a single-line body in the following case:
96769             // * The body has NodeEmitFlags.SingleLine specified.
96770             // We must emit a function body as a multi-line body in the following cases:
96771             // * The body is explicitly marked as multi-line.
96772             // * A non-synthesized body's start and end position are on different lines.
96773             // * Any statement in the body starts on a new line.
96774             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
96775                 return true;
96776             }
96777             if (body.multiLine) {
96778                 return false;
96779             }
96780             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
96781                 return false;
96782             }
96783             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
96784                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
96785                 return false;
96786             }
96787             var previousStatement;
96788             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
96789                 var statement = _b[_a];
96790                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
96791                     return false;
96792                 }
96793                 previousStatement = statement;
96794             }
96795             return true;
96796         }
96797         function emitBlockFunctionBody(body) {
96798             writeSpace();
96799             writePunctuation("{");
96800             increaseIndent();
96801             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
96802                 ? emitBlockFunctionBodyOnSingleLine
96803                 : emitBlockFunctionBodyWorker;
96804             if (emitBodyWithDetachedComments) {
96805                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
96806             }
96807             else {
96808                 emitBlockFunctionBody(body);
96809             }
96810             decreaseIndent();
96811             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
96812         }
96813         function emitBlockFunctionBodyOnSingleLine(body) {
96814             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
96815         }
96816         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
96817             // Emit all the prologue directives (like "use strict").
96818             var statementOffset = emitPrologueDirectives(body.statements);
96819             var pos = writer.getTextPos();
96820             emitHelpers(body);
96821             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
96822                 decreaseIndent();
96823                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
96824                 increaseIndent();
96825             }
96826             else {
96827                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
96828             }
96829         }
96830         function emitClassDeclaration(node) {
96831             emitClassDeclarationOrExpression(node);
96832         }
96833         function emitClassDeclarationOrExpression(node) {
96834             ts.forEach(node.members, generateMemberNames);
96835             emitDecorators(node, node.decorators);
96836             emitModifiers(node, node.modifiers);
96837             writeKeyword("class");
96838             if (node.name) {
96839                 writeSpace();
96840                 emitIdentifierName(node.name);
96841             }
96842             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
96843             if (indentedFlag) {
96844                 increaseIndent();
96845             }
96846             emitTypeParameters(node, node.typeParameters);
96847             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
96848             writeSpace();
96849             writePunctuation("{");
96850             emitList(node, node.members, 129 /* ClassMembers */);
96851             writePunctuation("}");
96852             if (indentedFlag) {
96853                 decreaseIndent();
96854             }
96855         }
96856         function emitInterfaceDeclaration(node) {
96857             emitDecorators(node, node.decorators);
96858             emitModifiers(node, node.modifiers);
96859             writeKeyword("interface");
96860             writeSpace();
96861             emit(node.name);
96862             emitTypeParameters(node, node.typeParameters);
96863             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
96864             writeSpace();
96865             writePunctuation("{");
96866             emitList(node, node.members, 129 /* InterfaceMembers */);
96867             writePunctuation("}");
96868         }
96869         function emitTypeAliasDeclaration(node) {
96870             emitDecorators(node, node.decorators);
96871             emitModifiers(node, node.modifiers);
96872             writeKeyword("type");
96873             writeSpace();
96874             emit(node.name);
96875             emitTypeParameters(node, node.typeParameters);
96876             writeSpace();
96877             writePunctuation("=");
96878             writeSpace();
96879             emit(node.type);
96880             writeTrailingSemicolon();
96881         }
96882         function emitEnumDeclaration(node) {
96883             emitModifiers(node, node.modifiers);
96884             writeKeyword("enum");
96885             writeSpace();
96886             emit(node.name);
96887             writeSpace();
96888             writePunctuation("{");
96889             emitList(node, node.members, 145 /* EnumMembers */);
96890             writePunctuation("}");
96891         }
96892         function emitModuleDeclaration(node) {
96893             emitModifiers(node, node.modifiers);
96894             if (~node.flags & 1024 /* GlobalAugmentation */) {
96895                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
96896                 writeSpace();
96897             }
96898             emit(node.name);
96899             var body = node.body;
96900             if (!body)
96901                 return writeTrailingSemicolon();
96902             while (body.kind === 249 /* ModuleDeclaration */) {
96903                 writePunctuation(".");
96904                 emit(body.name);
96905                 body = body.body;
96906             }
96907             writeSpace();
96908             emit(body);
96909         }
96910         function emitModuleBlock(node) {
96911             pushNameGenerationScope(node);
96912             ts.forEach(node.statements, generateNames);
96913             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
96914             popNameGenerationScope(node);
96915         }
96916         function emitCaseBlock(node) {
96917             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
96918             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
96919             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
96920         }
96921         function emitImportEqualsDeclaration(node) {
96922             emitModifiers(node, node.modifiers);
96923             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96924             writeSpace();
96925             emit(node.name);
96926             writeSpace();
96927             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
96928             writeSpace();
96929             emitModuleReference(node.moduleReference);
96930             writeTrailingSemicolon();
96931         }
96932         function emitModuleReference(node) {
96933             if (node.kind === 75 /* Identifier */) {
96934                 emitExpression(node);
96935             }
96936             else {
96937                 emit(node);
96938             }
96939         }
96940         function emitImportDeclaration(node) {
96941             emitModifiers(node, node.modifiers);
96942             emitTokenWithComment(96 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
96943             writeSpace();
96944             if (node.importClause) {
96945                 emit(node.importClause);
96946                 writeSpace();
96947                 emitTokenWithComment(149 /* FromKeyword */, node.importClause.end, writeKeyword, node);
96948                 writeSpace();
96949             }
96950             emitExpression(node.moduleSpecifier);
96951             writeTrailingSemicolon();
96952         }
96953         function emitImportClause(node) {
96954             if (node.isTypeOnly) {
96955                 emitTokenWithComment(145 /* TypeKeyword */, node.pos, writeKeyword, node);
96956                 writeSpace();
96957             }
96958             emit(node.name);
96959             if (node.name && node.namedBindings) {
96960                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
96961                 writeSpace();
96962             }
96963             emit(node.namedBindings);
96964         }
96965         function emitNamespaceImport(node) {
96966             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
96967             writeSpace();
96968             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
96969             writeSpace();
96970             emit(node.name);
96971         }
96972         function emitNamedImports(node) {
96973             emitNamedImportsOrExports(node);
96974         }
96975         function emitImportSpecifier(node) {
96976             emitImportOrExportSpecifier(node);
96977         }
96978         function emitExportAssignment(node) {
96979             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96980             writeSpace();
96981             if (node.isExportEquals) {
96982                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
96983             }
96984             else {
96985                 emitTokenWithComment(84 /* DefaultKeyword */, nextPos, writeKeyword, node);
96986             }
96987             writeSpace();
96988             emitExpression(node.expression);
96989             writeTrailingSemicolon();
96990         }
96991         function emitExportDeclaration(node) {
96992             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
96993             writeSpace();
96994             if (node.isTypeOnly) {
96995                 nextPos = emitTokenWithComment(145 /* TypeKeyword */, nextPos, writeKeyword, node);
96996                 writeSpace();
96997             }
96998             if (node.exportClause) {
96999                 emit(node.exportClause);
97000             }
97001             else {
97002                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
97003             }
97004             if (node.moduleSpecifier) {
97005                 writeSpace();
97006                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
97007                 emitTokenWithComment(149 /* FromKeyword */, fromPos, writeKeyword, node);
97008                 writeSpace();
97009                 emitExpression(node.moduleSpecifier);
97010             }
97011             writeTrailingSemicolon();
97012         }
97013         function emitNamespaceExportDeclaration(node) {
97014             var nextPos = emitTokenWithComment(89 /* ExportKeyword */, node.pos, writeKeyword, node);
97015             writeSpace();
97016             nextPos = emitTokenWithComment(123 /* AsKeyword */, nextPos, writeKeyword, node);
97017             writeSpace();
97018             nextPos = emitTokenWithComment(136 /* NamespaceKeyword */, nextPos, writeKeyword, node);
97019             writeSpace();
97020             emit(node.name);
97021             writeTrailingSemicolon();
97022         }
97023         function emitNamespaceExport(node) {
97024             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
97025             writeSpace();
97026             emitTokenWithComment(123 /* AsKeyword */, asPos, writeKeyword, node);
97027             writeSpace();
97028             emit(node.name);
97029         }
97030         function emitNamedExports(node) {
97031             emitNamedImportsOrExports(node);
97032         }
97033         function emitExportSpecifier(node) {
97034             emitImportOrExportSpecifier(node);
97035         }
97036         function emitNamedImportsOrExports(node) {
97037             writePunctuation("{");
97038             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
97039             writePunctuation("}");
97040         }
97041         function emitImportOrExportSpecifier(node) {
97042             if (node.propertyName) {
97043                 emit(node.propertyName);
97044                 writeSpace();
97045                 emitTokenWithComment(123 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
97046                 writeSpace();
97047             }
97048             emit(node.name);
97049         }
97050         //
97051         // Module references
97052         //
97053         function emitExternalModuleReference(node) {
97054             writeKeyword("require");
97055             writePunctuation("(");
97056             emitExpression(node.expression);
97057             writePunctuation(")");
97058         }
97059         //
97060         // JSX
97061         //
97062         function emitJsxElement(node) {
97063             emit(node.openingElement);
97064             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97065             emit(node.closingElement);
97066         }
97067         function emitJsxSelfClosingElement(node) {
97068             writePunctuation("<");
97069             emitJsxTagName(node.tagName);
97070             emitTypeArguments(node, node.typeArguments);
97071             writeSpace();
97072             emit(node.attributes);
97073             writePunctuation("/>");
97074         }
97075         function emitJsxFragment(node) {
97076             emit(node.openingFragment);
97077             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
97078             emit(node.closingFragment);
97079         }
97080         function emitJsxOpeningElementOrFragment(node) {
97081             writePunctuation("<");
97082             if (ts.isJsxOpeningElement(node)) {
97083                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
97084                 emitJsxTagName(node.tagName);
97085                 emitTypeArguments(node, node.typeArguments);
97086                 if (node.attributes.properties && node.attributes.properties.length > 0) {
97087                     writeSpace();
97088                 }
97089                 emit(node.attributes);
97090                 writeLineSeparatorsAfter(node.attributes, node);
97091                 decreaseIndentIf(indented);
97092             }
97093             writePunctuation(">");
97094         }
97095         function emitJsxText(node) {
97096             writer.writeLiteral(node.text);
97097         }
97098         function emitJsxClosingElementOrFragment(node) {
97099             writePunctuation("</");
97100             if (ts.isJsxClosingElement(node)) {
97101                 emitJsxTagName(node.tagName);
97102             }
97103             writePunctuation(">");
97104         }
97105         function emitJsxAttributes(node) {
97106             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
97107         }
97108         function emitJsxAttribute(node) {
97109             emit(node.name);
97110             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
97111         }
97112         function emitJsxSpreadAttribute(node) {
97113             writePunctuation("{...");
97114             emitExpression(node.expression);
97115             writePunctuation("}");
97116         }
97117         function emitJsxExpression(node) {
97118             if (node.expression) {
97119                 writePunctuation("{");
97120                 emit(node.dotDotDotToken);
97121                 emitExpression(node.expression);
97122                 writePunctuation("}");
97123             }
97124         }
97125         function emitJsxTagName(node) {
97126             if (node.kind === 75 /* Identifier */) {
97127                 emitExpression(node);
97128             }
97129             else {
97130                 emit(node);
97131             }
97132         }
97133         //
97134         // Clauses
97135         //
97136         function emitCaseClause(node) {
97137             emitTokenWithComment(78 /* CaseKeyword */, node.pos, writeKeyword, node);
97138             writeSpace();
97139             emitExpression(node.expression);
97140             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
97141         }
97142         function emitDefaultClause(node) {
97143             var pos = emitTokenWithComment(84 /* DefaultKeyword */, node.pos, writeKeyword, node);
97144             emitCaseOrDefaultClauseRest(node, node.statements, pos);
97145         }
97146         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
97147             var emitAsSingleStatement = statements.length === 1 &&
97148                 (
97149                 // treat synthesized nodes as located on the same line for emit purposes
97150                 ts.nodeIsSynthesized(parentNode) ||
97151                     ts.nodeIsSynthesized(statements[0]) ||
97152                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
97153             var format = 163969 /* CaseOrDefaultClauseStatements */;
97154             if (emitAsSingleStatement) {
97155                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97156                 writeSpace();
97157                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
97158             }
97159             else {
97160                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
97161             }
97162             emitList(parentNode, statements, format);
97163         }
97164         function emitHeritageClause(node) {
97165             writeSpace();
97166             writeTokenText(node.token, writeKeyword);
97167             writeSpace();
97168             emitList(node, node.types, 528 /* HeritageClauseTypes */);
97169         }
97170         function emitCatchClause(node) {
97171             var openParenPos = emitTokenWithComment(79 /* CatchKeyword */, node.pos, writeKeyword, node);
97172             writeSpace();
97173             if (node.variableDeclaration) {
97174                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
97175                 emit(node.variableDeclaration);
97176                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
97177                 writeSpace();
97178             }
97179             emit(node.block);
97180         }
97181         //
97182         // Property assignments
97183         //
97184         function emitPropertyAssignment(node) {
97185             emit(node.name);
97186             writePunctuation(":");
97187             writeSpace();
97188             // This is to ensure that we emit comment in the following case:
97189             //      For example:
97190             //          obj = {
97191             //              id: /*comment1*/ ()=>void
97192             //          }
97193             // "comment1" is not considered to be leading comment for node.initializer
97194             // but rather a trailing comment on the previous node.
97195             var initializer = node.initializer;
97196             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
97197                 var commentRange = ts.getCommentRange(initializer);
97198                 emitTrailingCommentsOfPosition(commentRange.pos);
97199             }
97200             emitExpression(initializer);
97201         }
97202         function emitShorthandPropertyAssignment(node) {
97203             emit(node.name);
97204             if (node.objectAssignmentInitializer) {
97205                 writeSpace();
97206                 writePunctuation("=");
97207                 writeSpace();
97208                 emitExpression(node.objectAssignmentInitializer);
97209             }
97210         }
97211         function emitSpreadAssignment(node) {
97212             if (node.expression) {
97213                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
97214                 emitExpression(node.expression);
97215             }
97216         }
97217         //
97218         // Enum
97219         //
97220         function emitEnumMember(node) {
97221             emit(node.name);
97222             emitInitializer(node.initializer, node.name.end, node);
97223         }
97224         //
97225         // JSDoc
97226         //
97227         function emitJSDoc(node) {
97228             write("/**");
97229             if (node.comment) {
97230                 var lines = node.comment.split(/\r\n?|\n/g);
97231                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
97232                     var line = lines_2[_a];
97233                     writeLine();
97234                     writeSpace();
97235                     writePunctuation("*");
97236                     writeSpace();
97237                     write(line);
97238                 }
97239             }
97240             if (node.tags) {
97241                 if (node.tags.length === 1 && node.tags[0].kind === 320 /* JSDocTypeTag */ && !node.comment) {
97242                     writeSpace();
97243                     emit(node.tags[0]);
97244                 }
97245                 else {
97246                     emitList(node, node.tags, 33 /* JSDocComment */);
97247                 }
97248             }
97249             writeSpace();
97250             write("*/");
97251         }
97252         function emitJSDocSimpleTypedTag(tag) {
97253             emitJSDocTagName(tag.tagName);
97254             emitJSDocTypeExpression(tag.typeExpression);
97255             emitJSDocComment(tag.comment);
97256         }
97257         function emitJSDocHeritageTag(tag) {
97258             emitJSDocTagName(tag.tagName);
97259             writeSpace();
97260             writePunctuation("{");
97261             emit(tag.class);
97262             writePunctuation("}");
97263             emitJSDocComment(tag.comment);
97264         }
97265         function emitJSDocTemplateTag(tag) {
97266             emitJSDocTagName(tag.tagName);
97267             emitJSDocTypeExpression(tag.constraint);
97268             writeSpace();
97269             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
97270             emitJSDocComment(tag.comment);
97271         }
97272         function emitJSDocTypedefTag(tag) {
97273             emitJSDocTagName(tag.tagName);
97274             if (tag.typeExpression) {
97275                 if (tag.typeExpression.kind === 294 /* JSDocTypeExpression */) {
97276                     emitJSDocTypeExpression(tag.typeExpression);
97277                 }
97278                 else {
97279                     writeSpace();
97280                     writePunctuation("{");
97281                     write("Object");
97282                     if (tag.typeExpression.isArrayType) {
97283                         writePunctuation("[");
97284                         writePunctuation("]");
97285                     }
97286                     writePunctuation("}");
97287                 }
97288             }
97289             if (tag.fullName) {
97290                 writeSpace();
97291                 emit(tag.fullName);
97292             }
97293             emitJSDocComment(tag.comment);
97294             if (tag.typeExpression && tag.typeExpression.kind === 304 /* JSDocTypeLiteral */) {
97295                 emitJSDocTypeLiteral(tag.typeExpression);
97296             }
97297         }
97298         function emitJSDocCallbackTag(tag) {
97299             emitJSDocTagName(tag.tagName);
97300             if (tag.name) {
97301                 writeSpace();
97302                 emit(tag.name);
97303             }
97304             emitJSDocComment(tag.comment);
97305             emitJSDocSignature(tag.typeExpression);
97306         }
97307         function emitJSDocSimpleTag(tag) {
97308             emitJSDocTagName(tag.tagName);
97309             emitJSDocComment(tag.comment);
97310         }
97311         function emitJSDocTypeLiteral(lit) {
97312             emitList(lit, ts.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
97313         }
97314         function emitJSDocSignature(sig) {
97315             if (sig.typeParameters) {
97316                 emitList(sig, ts.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
97317             }
97318             if (sig.parameters) {
97319                 emitList(sig, ts.createNodeArray(sig.parameters), 33 /* JSDocComment */);
97320             }
97321             if (sig.type) {
97322                 writeLine();
97323                 writeSpace();
97324                 writePunctuation("*");
97325                 writeSpace();
97326                 emit(sig.type);
97327             }
97328         }
97329         function emitJSDocPropertyLikeTag(param) {
97330             emitJSDocTagName(param.tagName);
97331             emitJSDocTypeExpression(param.typeExpression);
97332             writeSpace();
97333             if (param.isBracketed) {
97334                 writePunctuation("[");
97335             }
97336             emit(param.name);
97337             if (param.isBracketed) {
97338                 writePunctuation("]");
97339             }
97340             emitJSDocComment(param.comment);
97341         }
97342         function emitJSDocTagName(tagName) {
97343             writePunctuation("@");
97344             emit(tagName);
97345         }
97346         function emitJSDocComment(comment) {
97347             if (comment) {
97348                 writeSpace();
97349                 write(comment);
97350             }
97351         }
97352         function emitJSDocTypeExpression(typeExpression) {
97353             if (typeExpression) {
97354                 writeSpace();
97355                 writePunctuation("{");
97356                 emit(typeExpression.type);
97357                 writePunctuation("}");
97358             }
97359         }
97360         //
97361         // Top-level nodes
97362         //
97363         function emitSourceFile(node) {
97364             writeLine();
97365             var statements = node.statements;
97366             if (emitBodyWithDetachedComments) {
97367                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
97368                 // The synthesized node will have no leading comment so some comments may be missed.
97369                 var shouldEmitDetachedComment = statements.length === 0 ||
97370                     !ts.isPrologueDirective(statements[0]) ||
97371                     ts.nodeIsSynthesized(statements[0]);
97372                 if (shouldEmitDetachedComment) {
97373                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
97374                     return;
97375                 }
97376             }
97377             emitSourceFileWorker(node);
97378         }
97379         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
97380             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
97381             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
97382                 var prepend = _b[_a];
97383                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
97384                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
97385                         var ref = _d[_c];
97386                         emit(ref);
97387                         writeLine();
97388                     }
97389                 }
97390             }
97391         }
97392         function emitTripleSlashDirectivesIfNeeded(node) {
97393             if (node.isDeclarationFile)
97394                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
97395         }
97396         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
97397             if (hasNoDefaultLib) {
97398                 var pos = writer.getTextPos();
97399                 writeComment("/// <reference no-default-lib=\"true\"/>");
97400                 if (bundleFileInfo)
97401                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
97402                 writeLine();
97403             }
97404             if (currentSourceFile && currentSourceFile.moduleName) {
97405                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
97406                 writeLine();
97407             }
97408             if (currentSourceFile && currentSourceFile.amdDependencies) {
97409                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
97410                     var dep = _b[_a];
97411                     if (dep.name) {
97412                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
97413                     }
97414                     else {
97415                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
97416                     }
97417                     writeLine();
97418                 }
97419             }
97420             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
97421                 var directive = files_1[_c];
97422                 var pos = writer.getTextPos();
97423                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
97424                 if (bundleFileInfo)
97425                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
97426                 writeLine();
97427             }
97428             for (var _d = 0, types_22 = types; _d < types_22.length; _d++) {
97429                 var directive = types_22[_d];
97430                 var pos = writer.getTextPos();
97431                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
97432                 if (bundleFileInfo)
97433                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
97434                 writeLine();
97435             }
97436             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
97437                 var directive = libs_1[_e];
97438                 var pos = writer.getTextPos();
97439                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
97440                 if (bundleFileInfo)
97441                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
97442                 writeLine();
97443             }
97444         }
97445         function emitSourceFileWorker(node) {
97446             var statements = node.statements;
97447             pushNameGenerationScope(node);
97448             ts.forEach(node.statements, generateNames);
97449             emitHelpers(node);
97450             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
97451             emitTripleSlashDirectivesIfNeeded(node);
97452             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
97453             popNameGenerationScope(node);
97454         }
97455         // Transformation nodes
97456         function emitPartiallyEmittedExpression(node) {
97457             emitExpression(node.expression);
97458         }
97459         function emitCommaList(node) {
97460             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
97461         }
97462         /**
97463          * Emits any prologue directives at the start of a Statement list, returning the
97464          * number of prologue directives written to the output.
97465          */
97466         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
97467             var needsToSetSourceFile = !!sourceFile;
97468             for (var i = 0; i < statements.length; i++) {
97469                 var statement = statements[i];
97470                 if (ts.isPrologueDirective(statement)) {
97471                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
97472                     if (shouldEmitPrologueDirective) {
97473                         if (needsToSetSourceFile) {
97474                             needsToSetSourceFile = false;
97475                             setSourceFile(sourceFile);
97476                         }
97477                         writeLine();
97478                         var pos = writer.getTextPos();
97479                         emit(statement);
97480                         if (recordBundleFileSection && bundleFileInfo)
97481                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
97482                         if (seenPrologueDirectives) {
97483                             seenPrologueDirectives.set(statement.expression.text, true);
97484                         }
97485                     }
97486                 }
97487                 else {
97488                     // return index of the first non prologue directive
97489                     return i;
97490                 }
97491             }
97492             return statements.length;
97493         }
97494         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
97495             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
97496                 var prologue = prologues_1[_a];
97497                 if (!seenPrologueDirectives.has(prologue.data)) {
97498                     writeLine();
97499                     var pos = writer.getTextPos();
97500                     emit(prologue);
97501                     if (bundleFileInfo)
97502                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
97503                     if (seenPrologueDirectives) {
97504                         seenPrologueDirectives.set(prologue.data, true);
97505                     }
97506                 }
97507             }
97508         }
97509         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
97510             if (ts.isSourceFile(sourceFileOrBundle)) {
97511                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
97512             }
97513             else {
97514                 var seenPrologueDirectives = ts.createMap();
97515                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97516                     var prepend = _b[_a];
97517                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
97518                 }
97519                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97520                     var sourceFile = _d[_c];
97521                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
97522                 }
97523                 setSourceFile(undefined);
97524             }
97525         }
97526         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
97527             var seenPrologueDirectives = ts.createMap();
97528             var prologues;
97529             for (var index = 0; index < bundle.sourceFiles.length; index++) {
97530                 var sourceFile = bundle.sourceFiles[index];
97531                 var directives = void 0;
97532                 var end = 0;
97533                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
97534                     var statement = _b[_a];
97535                     if (!ts.isPrologueDirective(statement))
97536                         break;
97537                     if (seenPrologueDirectives.has(statement.expression.text))
97538                         continue;
97539                     seenPrologueDirectives.set(statement.expression.text, true);
97540                     (directives || (directives = [])).push({
97541                         pos: statement.pos,
97542                         end: statement.end,
97543                         expression: {
97544                             pos: statement.expression.pos,
97545                             end: statement.expression.end,
97546                             text: statement.expression.text
97547                         }
97548                     });
97549                     end = end < statement.end ? statement.end : end;
97550                 }
97551                 if (directives)
97552                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
97553             }
97554             return prologues;
97555         }
97556         function emitShebangIfNeeded(sourceFileOrBundle) {
97557             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
97558                 var shebang = ts.getShebang(sourceFileOrBundle.text);
97559                 if (shebang) {
97560                     writeComment(shebang);
97561                     writeLine();
97562                     return true;
97563                 }
97564             }
97565             else {
97566                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
97567                     var prepend = _b[_a];
97568                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
97569                     if (emitShebangIfNeeded(prepend)) {
97570                         return true;
97571                     }
97572                 }
97573                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
97574                     var sourceFile = _d[_c];
97575                     // Emit only the first encountered shebang
97576                     if (emitShebangIfNeeded(sourceFile)) {
97577                         return true;
97578                     }
97579                 }
97580             }
97581         }
97582         //
97583         // Helpers
97584         //
97585         function emitNodeWithWriter(node, writer) {
97586             if (!node)
97587                 return;
97588             var savedWrite = write;
97589             write = writer;
97590             emit(node);
97591             write = savedWrite;
97592         }
97593         function emitModifiers(node, modifiers) {
97594             if (modifiers && modifiers.length) {
97595                 emitList(node, modifiers, 262656 /* Modifiers */);
97596                 writeSpace();
97597             }
97598         }
97599         function emitTypeAnnotation(node) {
97600             if (node) {
97601                 writePunctuation(":");
97602                 writeSpace();
97603                 emit(node);
97604             }
97605         }
97606         function emitInitializer(node, equalCommentStartPos, container) {
97607             if (node) {
97608                 writeSpace();
97609                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
97610                 writeSpace();
97611                 emitExpression(node);
97612             }
97613         }
97614         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
97615             if (node) {
97616                 prefixWriter(prefix);
97617                 emit(node);
97618             }
97619         }
97620         function emitWithLeadingSpace(node) {
97621             if (node) {
97622                 writeSpace();
97623                 emit(node);
97624             }
97625         }
97626         function emitExpressionWithLeadingSpace(node) {
97627             if (node) {
97628                 writeSpace();
97629                 emitExpression(node);
97630             }
97631         }
97632         function emitWithTrailingSpace(node) {
97633             if (node) {
97634                 emit(node);
97635                 writeSpace();
97636             }
97637         }
97638         function emitEmbeddedStatement(parent, node) {
97639             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
97640                 writeSpace();
97641                 emit(node);
97642             }
97643             else {
97644                 writeLine();
97645                 increaseIndent();
97646                 if (ts.isEmptyStatement(node)) {
97647                     pipelineEmit(5 /* EmbeddedStatement */, node);
97648                 }
97649                 else {
97650                     emit(node);
97651                 }
97652                 decreaseIndent();
97653             }
97654         }
97655         function emitDecorators(parentNode, decorators) {
97656             emitList(parentNode, decorators, 2146305 /* Decorators */);
97657         }
97658         function emitTypeArguments(parentNode, typeArguments) {
97659             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
97660         }
97661         function emitTypeParameters(parentNode, typeParameters) {
97662             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
97663                 return emitTypeArguments(parentNode, parentNode.typeArguments);
97664             }
97665             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
97666         }
97667         function emitParameters(parentNode, parameters) {
97668             emitList(parentNode, parameters, 2576 /* Parameters */);
97669         }
97670         function canEmitSimpleArrowHead(parentNode, parameters) {
97671             var parameter = ts.singleOrUndefined(parameters);
97672             return parameter
97673                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
97674                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
97675                 && !parentNode.type // arrow function may not have return type annotation
97676                 && !ts.some(parentNode.decorators) // parent may not have decorators
97677                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
97678                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
97679                 && !ts.some(parameter.decorators) // parameter may not have decorators
97680                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
97681                 && !parameter.dotDotDotToken // parameter may not be rest
97682                 && !parameter.questionToken // parameter may not be optional
97683                 && !parameter.type // parameter may not have a type annotation
97684                 && !parameter.initializer // parameter may not have an initializer
97685                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
97686         }
97687         function emitParametersForArrow(parentNode, parameters) {
97688             if (canEmitSimpleArrowHead(parentNode, parameters)) {
97689                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
97690             }
97691             else {
97692                 emitParameters(parentNode, parameters);
97693             }
97694         }
97695         function emitParametersForIndexSignature(parentNode, parameters) {
97696             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
97697         }
97698         function emitList(parentNode, children, format, start, count) {
97699             emitNodeList(emit, parentNode, children, format, start, count);
97700         }
97701         function emitExpressionList(parentNode, children, format, start, count) {
97702             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
97703         }
97704         function writeDelimiter(format) {
97705             switch (format & 60 /* DelimitersMask */) {
97706                 case 0 /* None */:
97707                     break;
97708                 case 16 /* CommaDelimited */:
97709                     writePunctuation(",");
97710                     break;
97711                 case 4 /* BarDelimited */:
97712                     writeSpace();
97713                     writePunctuation("|");
97714                     break;
97715                 case 32 /* AsteriskDelimited */:
97716                     writeSpace();
97717                     writePunctuation("*");
97718                     writeSpace();
97719                     break;
97720                 case 8 /* AmpersandDelimited */:
97721                     writeSpace();
97722                     writePunctuation("&");
97723                     break;
97724             }
97725         }
97726         function emitNodeList(emit, parentNode, children, format, start, count) {
97727             if (start === void 0) { start = 0; }
97728             if (count === void 0) { count = children ? children.length - start : 0; }
97729             var isUndefined = children === undefined;
97730             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
97731                 return;
97732             }
97733             var isEmpty = children === undefined || start >= children.length || count === 0;
97734             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
97735                 if (onBeforeEmitNodeArray) {
97736                     onBeforeEmitNodeArray(children);
97737                 }
97738                 if (onAfterEmitNodeArray) {
97739                     onAfterEmitNodeArray(children);
97740                 }
97741                 return;
97742             }
97743             if (format & 15360 /* BracketsMask */) {
97744                 writePunctuation(getOpeningBracket(format));
97745                 if (isEmpty && !isUndefined) {
97746                     // TODO: GH#18217
97747                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
97748                 }
97749             }
97750             if (onBeforeEmitNodeArray) {
97751                 onBeforeEmitNodeArray(children);
97752             }
97753             if (isEmpty) {
97754                 // Write a line terminator if the parent node was multi-line
97755                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
97756                     writeLine();
97757                 }
97758                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
97759                     writeSpace();
97760                 }
97761             }
97762             else {
97763                 // Write the opening line terminator or leading whitespace.
97764                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
97765                 var shouldEmitInterveningComments = mayEmitInterveningComments;
97766                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
97767                 if (leadingLineTerminatorCount) {
97768                     writeLine(leadingLineTerminatorCount);
97769                     shouldEmitInterveningComments = false;
97770                 }
97771                 else if (format & 256 /* SpaceBetweenBraces */) {
97772                     writeSpace();
97773                 }
97774                 // Increase the indent, if requested.
97775                 if (format & 128 /* Indented */) {
97776                     increaseIndent();
97777                 }
97778                 // Emit each child.
97779                 var previousSibling = void 0;
97780                 var previousSourceFileTextKind = void 0;
97781                 var shouldDecreaseIndentAfterEmit = false;
97782                 for (var i = 0; i < count; i++) {
97783                     var child = children[start + i];
97784                     // Write the delimiter if this is not the first node.
97785                     if (format & 32 /* AsteriskDelimited */) {
97786                         // always write JSDoc in the format "\n *"
97787                         writeLine();
97788                         writeDelimiter(format);
97789                     }
97790                     else if (previousSibling) {
97791                         // i.e
97792                         //      function commentedParameters(
97793                         //          /* Parameter a */
97794                         //          a
97795                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
97796                         //          ,
97797                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
97798                             emitLeadingCommentsOfPosition(previousSibling.end);
97799                         }
97800                         writeDelimiter(format);
97801                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97802                         // Write either a line terminator or whitespace to separate the elements.
97803                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
97804                         if (separatingLineTerminatorCount > 0) {
97805                             // If a synthesized node in a single-line list starts on a new
97806                             // line, we should increase the indent.
97807                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
97808                                 increaseIndent();
97809                                 shouldDecreaseIndentAfterEmit = true;
97810                             }
97811                             writeLine(separatingLineTerminatorCount);
97812                             shouldEmitInterveningComments = false;
97813                         }
97814                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
97815                             writeSpace();
97816                         }
97817                     }
97818                     // Emit this child.
97819                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
97820                     if (shouldEmitInterveningComments) {
97821                         if (emitTrailingCommentsOfPosition) {
97822                             var commentRange = ts.getCommentRange(child);
97823                             emitTrailingCommentsOfPosition(commentRange.pos);
97824                         }
97825                     }
97826                     else {
97827                         shouldEmitInterveningComments = mayEmitInterveningComments;
97828                     }
97829                     emit(child);
97830                     if (shouldDecreaseIndentAfterEmit) {
97831                         decreaseIndent();
97832                         shouldDecreaseIndentAfterEmit = false;
97833                     }
97834                     previousSibling = child;
97835                 }
97836                 // Write a trailing comma, if requested.
97837                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
97838                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
97839                     writePunctuation(",");
97840                 }
97841                 // Emit any trailing comment of the last element in the list
97842                 // i.e
97843                 //       var array = [...
97844                 //          2
97845                 //          /* end of element 2 */
97846                 //       ];
97847                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
97848                     emitLeadingCommentsOfPosition(previousSibling.end);
97849                 }
97850                 // Decrease the indent, if requested.
97851                 if (format & 128 /* Indented */) {
97852                     decreaseIndent();
97853                 }
97854                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
97855                 // Write the closing line terminator or closing whitespace.
97856                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
97857                 if (closingLineTerminatorCount) {
97858                     writeLine(closingLineTerminatorCount);
97859                 }
97860                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
97861                     writeSpace();
97862                 }
97863             }
97864             if (onAfterEmitNodeArray) {
97865                 onAfterEmitNodeArray(children);
97866             }
97867             if (format & 15360 /* BracketsMask */) {
97868                 if (isEmpty && !isUndefined) {
97869                     // TODO: GH#18217
97870                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
97871                 }
97872                 writePunctuation(getClosingBracket(format));
97873             }
97874         }
97875         // Writers
97876         function writeLiteral(s) {
97877             writer.writeLiteral(s);
97878         }
97879         function writeStringLiteral(s) {
97880             writer.writeStringLiteral(s);
97881         }
97882         function writeBase(s) {
97883             writer.write(s);
97884         }
97885         function writeSymbol(s, sym) {
97886             writer.writeSymbol(s, sym);
97887         }
97888         function writePunctuation(s) {
97889             writer.writePunctuation(s);
97890         }
97891         function writeTrailingSemicolon() {
97892             writer.writeTrailingSemicolon(";");
97893         }
97894         function writeKeyword(s) {
97895             writer.writeKeyword(s);
97896         }
97897         function writeOperator(s) {
97898             writer.writeOperator(s);
97899         }
97900         function writeParameter(s) {
97901             writer.writeParameter(s);
97902         }
97903         function writeComment(s) {
97904             writer.writeComment(s);
97905         }
97906         function writeSpace() {
97907             writer.writeSpace(" ");
97908         }
97909         function writeProperty(s) {
97910             writer.writeProperty(s);
97911         }
97912         function writeLine(count) {
97913             if (count === void 0) { count = 1; }
97914             for (var i = 0; i < count; i++) {
97915                 writer.writeLine(i > 0);
97916             }
97917         }
97918         function increaseIndent() {
97919             writer.increaseIndent();
97920         }
97921         function decreaseIndent() {
97922             writer.decreaseIndent();
97923         }
97924         function writeToken(token, pos, writer, contextNode) {
97925             return !sourceMapsDisabled
97926                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
97927                 : writeTokenText(token, writer, pos);
97928         }
97929         function writeTokenNode(node, writer) {
97930             if (onBeforeEmitToken) {
97931                 onBeforeEmitToken(node);
97932             }
97933             writer(ts.tokenToString(node.kind));
97934             if (onAfterEmitToken) {
97935                 onAfterEmitToken(node);
97936             }
97937         }
97938         function writeTokenText(token, writer, pos) {
97939             var tokenString = ts.tokenToString(token);
97940             writer(tokenString);
97941             return pos < 0 ? pos : pos + tokenString.length;
97942         }
97943         function writeLineOrSpace(node) {
97944             if (ts.getEmitFlags(node) & 1 /* SingleLine */) {
97945                 writeSpace();
97946             }
97947             else {
97948                 writeLine();
97949             }
97950         }
97951         function writeLines(text) {
97952             var lines = text.split(/\r\n?|\n/g);
97953             var indentation = ts.guessIndentation(lines);
97954             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
97955                 var lineText = lines_3[_a];
97956                 var line = indentation ? lineText.slice(indentation) : lineText;
97957                 if (line.length) {
97958                     writeLine();
97959                     write(line);
97960                 }
97961             }
97962         }
97963         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
97964             if (lineCount) {
97965                 increaseIndent();
97966                 writeLine(lineCount);
97967             }
97968             else if (writeSpaceIfNotIndenting) {
97969                 writeSpace();
97970             }
97971         }
97972         // Helper function to decrease the indent if we previously indented.  Allows multiple
97973         // previous indent values to be considered at a time.  This also allows caller to just
97974         // call this once, passing in all their appropriate indent values, instead of needing
97975         // to call this helper function multiple times.
97976         function decreaseIndentIf(value1, value2) {
97977             if (value1) {
97978                 decreaseIndent();
97979             }
97980             if (value2) {
97981                 decreaseIndent();
97982             }
97983         }
97984         function getLeadingLineTerminatorCount(parentNode, children, format) {
97985             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
97986                 if (format & 65536 /* PreferNewLine */) {
97987                     return 1;
97988                 }
97989                 var firstChild_1 = children[0];
97990                 if (firstChild_1 === undefined) {
97991                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
97992                 }
97993                 if (firstChild_1.kind === 11 /* JsxText */) {
97994                     // JsxText will be written with its leading whitespace, so don't add more manually.
97995                     return 0;
97996                 }
97997                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(firstChild_1) && (!firstChild_1.parent || firstChild_1.parent === parentNode)) {
97998                     if (preserveSourceNewlines) {
97999                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
98000                     }
98001                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
98002                 }
98003                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
98004                     return 1;
98005                 }
98006             }
98007             return format & 1 /* MultiLine */ ? 1 : 0;
98008         }
98009         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
98010             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98011                 if (previousNode === undefined || nextNode === undefined) {
98012                     return 0;
98013                 }
98014                 if (nextNode.kind === 11 /* JsxText */) {
98015                     // JsxText will be written with its leading whitespace, so don't add more manually.
98016                     return 0;
98017                 }
98018                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
98019                     if (preserveSourceNewlines) {
98020                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
98021                     }
98022                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
98023                 }
98024                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
98025                     return 1;
98026                 }
98027             }
98028             else if (ts.getStartsOnNewLine(nextNode)) {
98029                 return 1;
98030             }
98031             return format & 1 /* MultiLine */ ? 1 : 0;
98032         }
98033         function getClosingLineTerminatorCount(parentNode, children, format) {
98034             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
98035                 if (format & 65536 /* PreferNewLine */) {
98036                     return 1;
98037                 }
98038                 var lastChild_1 = ts.lastOrUndefined(children);
98039                 if (lastChild_1 === undefined) {
98040                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
98041                 }
98042                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild_1) && (!lastChild_1.parent || lastChild_1.parent === parentNode)) {
98043                     if (preserveSourceNewlines) {
98044                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(lastChild_1.end, parentNode.end, currentSourceFile, includeComments); });
98045                     }
98046                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild_1, currentSourceFile) ? 0 : 1;
98047                 }
98048                 if (synthesizedNodeStartsOnNewLine(lastChild_1, format)) {
98049                     return 1;
98050                 }
98051             }
98052             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
98053                 return 1;
98054             }
98055             return 0;
98056         }
98057         function getEffectiveLines(getLineDifference) {
98058             // If 'preserveSourceNewlines' is disabled, we should never call this function
98059             // because it could be more expensive than alternative approximations.
98060             ts.Debug.assert(!!preserveSourceNewlines);
98061             // We start by measuring the line difference from a position to its adjacent comments,
98062             // so that this is counted as a one-line difference, not two:
98063             //
98064             //   node1;
98065             //   // NODE2 COMMENT
98066             //   node2;
98067             var lines = getLineDifference(/*includeComments*/ true);
98068             if (lines === 0) {
98069                 // However, if the line difference considering comments was 0, we might have this:
98070                 //
98071                 //   node1; // NODE2 COMMENT
98072                 //   node2;
98073                 //
98074                 // in which case we should be ignoring node2's comment, so this too is counted as
98075                 // a one-line difference, not zero.
98076                 return getLineDifference(/*includeComments*/ false);
98077             }
98078             return lines;
98079         }
98080         function writeLineSeparatorsAndIndentBefore(node, parent) {
98081             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
98082             if (leadingNewlines) {
98083                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
98084             }
98085             return !!leadingNewlines;
98086         }
98087         function writeLineSeparatorsAfter(node, parent) {
98088             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
98089             if (trailingNewlines) {
98090                 writeLine(trailingNewlines);
98091             }
98092         }
98093         function synthesizedNodeStartsOnNewLine(node, format) {
98094             if (ts.nodeIsSynthesized(node)) {
98095                 var startsOnNewLine = ts.getStartsOnNewLine(node);
98096                 if (startsOnNewLine === undefined) {
98097                     return (format & 65536 /* PreferNewLine */) !== 0;
98098                 }
98099                 return startsOnNewLine;
98100             }
98101             return (format & 65536 /* PreferNewLine */) !== 0;
98102         }
98103         function getLinesBetweenNodes(parent, node1, node2) {
98104             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
98105                 return 0;
98106             }
98107             parent = skipSynthesizedParentheses(parent);
98108             node1 = skipSynthesizedParentheses(node1);
98109             node2 = skipSynthesizedParentheses(node2);
98110             // Always use a newline for synthesized code if the synthesizer desires it.
98111             if (ts.getStartsOnNewLine(node2)) {
98112                 return 1;
98113             }
98114             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
98115                 if (preserveSourceNewlines) {
98116                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
98117                 }
98118                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
98119             }
98120             return 0;
98121         }
98122         function isEmptyBlock(block) {
98123             return block.statements.length === 0
98124                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
98125         }
98126         function skipSynthesizedParentheses(node) {
98127             while (node.kind === 200 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
98128                 node = node.expression;
98129             }
98130             return node;
98131         }
98132         function getTextOfNode(node, includeTrivia) {
98133             if (ts.isGeneratedIdentifier(node)) {
98134                 return generateName(node);
98135             }
98136             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
98137                 return ts.idText(node);
98138             }
98139             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98140                 return getTextOfNode(node.textSourceNode, includeTrivia);
98141             }
98142             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
98143                 return node.text;
98144             }
98145             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
98146         }
98147         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
98148             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
98149                 var textSourceNode = node.textSourceNode;
98150                 if (ts.isIdentifier(textSourceNode)) {
98151                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(getTextOfNode(textSourceNode)) + "\"" :
98152                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(getTextOfNode(textSourceNode)) + "\"" :
98153                             "\"" + ts.escapeNonAsciiString(getTextOfNode(textSourceNode)) + "\"";
98154                 }
98155                 else {
98156                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
98157                 }
98158             }
98159             return ts.getLiteralText(node, currentSourceFile, neverAsciiEscape, jsxAttributeEscape);
98160         }
98161         /**
98162          * Push a new name generation scope.
98163          */
98164         function pushNameGenerationScope(node) {
98165             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98166                 return;
98167             }
98168             tempFlagsStack.push(tempFlags);
98169             tempFlags = 0;
98170             reservedNamesStack.push(reservedNames);
98171         }
98172         /**
98173          * Pop the current name generation scope.
98174          */
98175         function popNameGenerationScope(node) {
98176             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98177                 return;
98178             }
98179             tempFlags = tempFlagsStack.pop();
98180             reservedNames = reservedNamesStack.pop();
98181         }
98182         function reserveNameInNestedScopes(name) {
98183             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
98184                 reservedNames = ts.createMap();
98185             }
98186             reservedNames.set(name, true);
98187         }
98188         function generateNames(node) {
98189             if (!node)
98190                 return;
98191             switch (node.kind) {
98192                 case 223 /* Block */:
98193                     ts.forEach(node.statements, generateNames);
98194                     break;
98195                 case 238 /* LabeledStatement */:
98196                 case 236 /* WithStatement */:
98197                 case 228 /* DoStatement */:
98198                 case 229 /* WhileStatement */:
98199                     generateNames(node.statement);
98200                     break;
98201                 case 227 /* IfStatement */:
98202                     generateNames(node.thenStatement);
98203                     generateNames(node.elseStatement);
98204                     break;
98205                 case 230 /* ForStatement */:
98206                 case 232 /* ForOfStatement */:
98207                 case 231 /* ForInStatement */:
98208                     generateNames(node.initializer);
98209                     generateNames(node.statement);
98210                     break;
98211                 case 237 /* SwitchStatement */:
98212                     generateNames(node.caseBlock);
98213                     break;
98214                 case 251 /* CaseBlock */:
98215                     ts.forEach(node.clauses, generateNames);
98216                     break;
98217                 case 277 /* CaseClause */:
98218                 case 278 /* DefaultClause */:
98219                     ts.forEach(node.statements, generateNames);
98220                     break;
98221                 case 240 /* TryStatement */:
98222                     generateNames(node.tryBlock);
98223                     generateNames(node.catchClause);
98224                     generateNames(node.finallyBlock);
98225                     break;
98226                 case 280 /* CatchClause */:
98227                     generateNames(node.variableDeclaration);
98228                     generateNames(node.block);
98229                     break;
98230                 case 225 /* VariableStatement */:
98231                     generateNames(node.declarationList);
98232                     break;
98233                 case 243 /* VariableDeclarationList */:
98234                     ts.forEach(node.declarations, generateNames);
98235                     break;
98236                 case 242 /* VariableDeclaration */:
98237                 case 156 /* Parameter */:
98238                 case 191 /* BindingElement */:
98239                 case 245 /* ClassDeclaration */:
98240                     generateNameIfNeeded(node.name);
98241                     break;
98242                 case 244 /* FunctionDeclaration */:
98243                     generateNameIfNeeded(node.name);
98244                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
98245                         ts.forEach(node.parameters, generateNames);
98246                         generateNames(node.body);
98247                     }
98248                     break;
98249                 case 189 /* ObjectBindingPattern */:
98250                 case 190 /* ArrayBindingPattern */:
98251                     ts.forEach(node.elements, generateNames);
98252                     break;
98253                 case 254 /* ImportDeclaration */:
98254                     generateNames(node.importClause);
98255                     break;
98256                 case 255 /* ImportClause */:
98257                     generateNameIfNeeded(node.name);
98258                     generateNames(node.namedBindings);
98259                     break;
98260                 case 256 /* NamespaceImport */:
98261                     generateNameIfNeeded(node.name);
98262                     break;
98263                 case 262 /* NamespaceExport */:
98264                     generateNameIfNeeded(node.name);
98265                     break;
98266                 case 257 /* NamedImports */:
98267                     ts.forEach(node.elements, generateNames);
98268                     break;
98269                 case 258 /* ImportSpecifier */:
98270                     generateNameIfNeeded(node.propertyName || node.name);
98271                     break;
98272             }
98273         }
98274         function generateMemberNames(node) {
98275             if (!node)
98276                 return;
98277             switch (node.kind) {
98278                 case 281 /* PropertyAssignment */:
98279                 case 282 /* ShorthandPropertyAssignment */:
98280                 case 159 /* PropertyDeclaration */:
98281                 case 161 /* MethodDeclaration */:
98282                 case 163 /* GetAccessor */:
98283                 case 164 /* SetAccessor */:
98284                     generateNameIfNeeded(node.name);
98285                     break;
98286             }
98287         }
98288         function generateNameIfNeeded(name) {
98289             if (name) {
98290                 if (ts.isGeneratedIdentifier(name)) {
98291                     generateName(name);
98292                 }
98293                 else if (ts.isBindingPattern(name)) {
98294                     generateNames(name);
98295                 }
98296             }
98297         }
98298         /**
98299          * Generate the text for a generated identifier.
98300          */
98301         function generateName(name) {
98302             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
98303                 // Node names generate unique names based on their original node
98304                 // and are cached based on that node's id.
98305                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
98306             }
98307             else {
98308                 // Auto, Loop, and Unique names are cached based on their unique
98309                 // autoGenerateId.
98310                 var autoGenerateId = name.autoGenerateId;
98311                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
98312             }
98313         }
98314         function generateNameCached(node, flags) {
98315             var nodeId = ts.getNodeId(node);
98316             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
98317         }
98318         /**
98319          * Returns a value indicating whether a name is unique globally, within the current file,
98320          * or within the NameGenerator.
98321          */
98322         function isUniqueName(name) {
98323             return isFileLevelUniqueName(name)
98324                 && !generatedNames.has(name)
98325                 && !(reservedNames && reservedNames.has(name));
98326         }
98327         /**
98328          * Returns a value indicating whether a name is unique globally or within the current file.
98329          */
98330         function isFileLevelUniqueName(name) {
98331             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
98332         }
98333         /**
98334          * Returns a value indicating whether a name is unique within a container.
98335          */
98336         function isUniqueLocalName(name, container) {
98337             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
98338                 if (node.locals) {
98339                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
98340                     // We conservatively include alias symbols to cover cases where they're emitted as locals
98341                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
98342                         return false;
98343                     }
98344                 }
98345             }
98346             return true;
98347         }
98348         /**
98349          * Return the next available name in the pattern _a ... _z, _0, _1, ...
98350          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
98351          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
98352          */
98353         function makeTempVariableName(flags, reservedInNestedScopes) {
98354             if (flags && !(tempFlags & flags)) {
98355                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
98356                 if (isUniqueName(name)) {
98357                     tempFlags |= flags;
98358                     if (reservedInNestedScopes) {
98359                         reserveNameInNestedScopes(name);
98360                     }
98361                     return name;
98362                 }
98363             }
98364             while (true) {
98365                 var count = tempFlags & 268435455 /* CountMask */;
98366                 tempFlags++;
98367                 // Skip over 'i' and 'n'
98368                 if (count !== 8 && count !== 13) {
98369                     var name = count < 26
98370                         ? "_" + String.fromCharCode(97 /* a */ + count)
98371                         : "_" + (count - 26);
98372                     if (isUniqueName(name)) {
98373                         if (reservedInNestedScopes) {
98374                             reserveNameInNestedScopes(name);
98375                         }
98376                         return name;
98377                     }
98378                 }
98379             }
98380         }
98381         /**
98382          * Generate a name that is unique within the current file and doesn't conflict with any names
98383          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
98384          * where n is a positive integer. Note that names generated by makeTempVariableName and
98385          * makeUniqueName are guaranteed to never conflict.
98386          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
98387          */
98388         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
98389             if (checkFn === void 0) { checkFn = isUniqueName; }
98390             if (optimistic) {
98391                 if (checkFn(baseName)) {
98392                     if (scoped) {
98393                         reserveNameInNestedScopes(baseName);
98394                     }
98395                     else {
98396                         generatedNames.set(baseName, true);
98397                     }
98398                     return baseName;
98399                 }
98400             }
98401             // Find the first unique 'name_n', where n is a positive number
98402             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
98403                 baseName += "_";
98404             }
98405             var i = 1;
98406             while (true) {
98407                 var generatedName = baseName + i;
98408                 if (checkFn(generatedName)) {
98409                     if (scoped) {
98410                         reserveNameInNestedScopes(generatedName);
98411                     }
98412                     else {
98413                         generatedNames.set(generatedName, true);
98414                     }
98415                     return generatedName;
98416                 }
98417                 i++;
98418             }
98419         }
98420         function makeFileLevelOptimisticUniqueName(name) {
98421             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
98422         }
98423         /**
98424          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
98425          */
98426         function generateNameForModuleOrEnum(node) {
98427             var name = getTextOfNode(node.name);
98428             // Use module/enum name itself if it is unique, otherwise make a unique variation
98429             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
98430         }
98431         /**
98432          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
98433          */
98434         function generateNameForImportOrExportDeclaration(node) {
98435             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
98436             var baseName = ts.isStringLiteral(expr) ?
98437                 ts.makeIdentifierFromModuleName(expr.text) : "module";
98438             return makeUniqueName(baseName);
98439         }
98440         /**
98441          * Generates a unique name for a default export.
98442          */
98443         function generateNameForExportDefault() {
98444             return makeUniqueName("default");
98445         }
98446         /**
98447          * Generates a unique name for a class expression.
98448          */
98449         function generateNameForClassExpression() {
98450             return makeUniqueName("class");
98451         }
98452         function generateNameForMethodOrAccessor(node) {
98453             if (ts.isIdentifier(node.name)) {
98454                 return generateNameCached(node.name);
98455             }
98456             return makeTempVariableName(0 /* Auto */);
98457         }
98458         /**
98459          * Generates a unique name from a node.
98460          */
98461         function generateNameForNode(node, flags) {
98462             switch (node.kind) {
98463                 case 75 /* Identifier */:
98464                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
98465                 case 249 /* ModuleDeclaration */:
98466                 case 248 /* EnumDeclaration */:
98467                     return generateNameForModuleOrEnum(node);
98468                 case 254 /* ImportDeclaration */:
98469                 case 260 /* ExportDeclaration */:
98470                     return generateNameForImportOrExportDeclaration(node);
98471                 case 244 /* FunctionDeclaration */:
98472                 case 245 /* ClassDeclaration */:
98473                 case 259 /* ExportAssignment */:
98474                     return generateNameForExportDefault();
98475                 case 214 /* ClassExpression */:
98476                     return generateNameForClassExpression();
98477                 case 161 /* MethodDeclaration */:
98478                 case 163 /* GetAccessor */:
98479                 case 164 /* SetAccessor */:
98480                     return generateNameForMethodOrAccessor(node);
98481                 case 154 /* ComputedPropertyName */:
98482                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
98483                 default:
98484                     return makeTempVariableName(0 /* Auto */);
98485             }
98486         }
98487         /**
98488          * Generates a unique identifier for a node.
98489          */
98490         function makeName(name) {
98491             switch (name.autoGenerateFlags & 7 /* KindMask */) {
98492                 case 1 /* Auto */:
98493                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98494                 case 2 /* Loop */:
98495                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98496                 case 3 /* Unique */:
98497                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
98498             }
98499             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
98500         }
98501         /**
98502          * Gets the node from which a name should be generated.
98503          */
98504         function getNodeForGeneratedName(name) {
98505             var autoGenerateId = name.autoGenerateId;
98506             var node = name;
98507             var original = node.original;
98508             while (original) {
98509                 node = original;
98510                 // if "node" is a different generated name (having a different
98511                 // "autoGenerateId"), use it and stop traversing.
98512                 if (ts.isIdentifier(node)
98513                     && !!(node.autoGenerateFlags & 4 /* Node */)
98514                     && node.autoGenerateId !== autoGenerateId) {
98515                     break;
98516                 }
98517                 original = node.original;
98518             }
98519             // otherwise, return the original node for the source;
98520             return node;
98521         }
98522         // Comments
98523         function pipelineEmitWithComments(hint, node) {
98524             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98525             enterComment();
98526             hasWrittenComment = false;
98527             var emitFlags = ts.getEmitFlags(node);
98528             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
98529             var isEmittedNode = node.kind !== 325 /* NotEmittedStatement */;
98530             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
98531             // It is expensive to walk entire tree just to set one kind of node to have no comments.
98532             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
98533             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
98534             // Save current container state on the stack.
98535             var savedContainerPos = containerPos;
98536             var savedContainerEnd = containerEnd;
98537             var savedDeclarationListContainerEnd = declarationListContainerEnd;
98538             if ((pos > 0 || end > 0) && pos !== end) {
98539                 // Emit leading comments if the position is not synthesized and the node
98540                 // has not opted out from emitting leading comments.
98541                 if (!skipLeadingComments) {
98542                     emitLeadingComments(pos, isEmittedNode);
98543                 }
98544                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
98545                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
98546                     containerPos = pos;
98547                 }
98548                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
98549                     // As above.
98550                     containerEnd = end;
98551                     // To avoid invalid comment emit in a down-level binding pattern, we
98552                     // keep track of the last declaration list container's end
98553                     if (node.kind === 243 /* VariableDeclarationList */) {
98554                         declarationListContainerEnd = end;
98555                     }
98556                 }
98557             }
98558             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
98559             exitComment();
98560             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
98561             if (emitFlags & 2048 /* NoNestedComments */) {
98562                 commentsDisabled = true;
98563                 pipelinePhase(hint, node);
98564                 commentsDisabled = false;
98565             }
98566             else {
98567                 pipelinePhase(hint, node);
98568             }
98569             enterComment();
98570             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
98571             if ((pos > 0 || end > 0) && pos !== end) {
98572                 // Restore previous container state.
98573                 containerPos = savedContainerPos;
98574                 containerEnd = savedContainerEnd;
98575                 declarationListContainerEnd = savedDeclarationListContainerEnd;
98576                 // Emit trailing comments if the position is not synthesized and the node
98577                 // has not opted out from emitting leading comments and is an emitted node.
98578                 if (!skipTrailingComments && isEmittedNode) {
98579                     emitTrailingComments(end);
98580                 }
98581             }
98582             exitComment();
98583             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98584         }
98585         function emitLeadingSynthesizedComment(comment) {
98586             if (comment.kind === 2 /* SingleLineCommentTrivia */) {
98587                 writer.writeLine();
98588             }
98589             writeSynthesizedComment(comment);
98590             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
98591                 writer.writeLine();
98592             }
98593             else {
98594                 writer.writeSpace(" ");
98595             }
98596         }
98597         function emitTrailingSynthesizedComment(comment) {
98598             if (!writer.isAtStartOfLine()) {
98599                 writer.writeSpace(" ");
98600             }
98601             writeSynthesizedComment(comment);
98602             if (comment.hasTrailingNewLine) {
98603                 writer.writeLine();
98604             }
98605         }
98606         function writeSynthesizedComment(comment) {
98607             var text = formatSynthesizedComment(comment);
98608             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
98609             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
98610         }
98611         function formatSynthesizedComment(comment) {
98612             return comment.kind === 3 /* MultiLineCommentTrivia */
98613                 ? "/*" + comment.text + "*/"
98614                 : "//" + comment.text;
98615         }
98616         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
98617             enterComment();
98618             var pos = detachedRange.pos, end = detachedRange.end;
98619             var emitFlags = ts.getEmitFlags(node);
98620             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
98621             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
98622             if (!skipLeadingComments) {
98623                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
98624             }
98625             exitComment();
98626             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
98627                 commentsDisabled = true;
98628                 emitCallback(node);
98629                 commentsDisabled = false;
98630             }
98631             else {
98632                 emitCallback(node);
98633             }
98634             enterComment();
98635             if (!skipTrailingComments) {
98636                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
98637                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
98638                     writer.writeLine();
98639                 }
98640             }
98641             exitComment();
98642         }
98643         function emitLeadingComments(pos, isEmittedNode) {
98644             hasWrittenComment = false;
98645             if (isEmittedNode) {
98646                 forEachLeadingCommentToEmit(pos, emitLeadingComment);
98647             }
98648             else if (pos === 0) {
98649                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
98650                 // unless it is a triple slash comment at the top of the file.
98651                 // For Example:
98652                 //      /// <reference-path ...>
98653                 //      declare var x;
98654                 //      /// <reference-path ...>
98655                 //      interface F {}
98656                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
98657                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
98658             }
98659         }
98660         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98661             if (isTripleSlashComment(commentPos, commentEnd)) {
98662                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
98663             }
98664         }
98665         function shouldWriteComment(text, pos) {
98666             if (printerOptions.onlyPrintJsDocStyle) {
98667                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
98668             }
98669             return true;
98670         }
98671         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
98672             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98673                 return;
98674             if (!hasWrittenComment) {
98675                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
98676                 hasWrittenComment = true;
98677             }
98678             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
98679             emitPos(commentPos);
98680             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98681             emitPos(commentEnd);
98682             if (hasTrailingNewLine) {
98683                 writer.writeLine();
98684             }
98685             else if (kind === 3 /* MultiLineCommentTrivia */) {
98686                 writer.writeSpace(" ");
98687             }
98688         }
98689         function emitLeadingCommentsOfPosition(pos) {
98690             if (commentsDisabled || pos === -1) {
98691                 return;
98692             }
98693             emitLeadingComments(pos, /*isEmittedNode*/ true);
98694         }
98695         function emitTrailingComments(pos) {
98696             forEachTrailingCommentToEmit(pos, emitTrailingComment);
98697         }
98698         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98699             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98700                 return;
98701             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
98702             if (!writer.isAtStartOfLine()) {
98703                 writer.writeSpace(" ");
98704             }
98705             emitPos(commentPos);
98706             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98707             emitPos(commentEnd);
98708             if (hasTrailingNewLine) {
98709                 writer.writeLine();
98710             }
98711         }
98712         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
98713             if (commentsDisabled) {
98714                 return;
98715             }
98716             enterComment();
98717             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
98718             exitComment();
98719         }
98720         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
98721             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
98722             emitPos(commentPos);
98723             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
98724             emitPos(commentEnd);
98725             if (hasTrailingNewLine) {
98726                 writer.writeLine();
98727             }
98728             else {
98729                 writer.writeSpace(" ");
98730             }
98731         }
98732         function forEachLeadingCommentToEmit(pos, cb) {
98733             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
98734             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
98735                 if (hasDetachedComments(pos)) {
98736                     forEachLeadingCommentWithoutDetachedComments(cb);
98737                 }
98738                 else {
98739                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98740                 }
98741             }
98742         }
98743         function forEachTrailingCommentToEmit(end, cb) {
98744             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
98745             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
98746                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
98747             }
98748         }
98749         function hasDetachedComments(pos) {
98750             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
98751         }
98752         function forEachLeadingCommentWithoutDetachedComments(cb) {
98753             // get the leading comments from detachedPos
98754             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
98755             if (detachedCommentsInfo.length - 1) {
98756                 detachedCommentsInfo.pop();
98757             }
98758             else {
98759                 detachedCommentsInfo = undefined;
98760             }
98761             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
98762         }
98763         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
98764             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
98765             if (currentDetachedCommentInfo) {
98766                 if (detachedCommentsInfo) {
98767                     detachedCommentsInfo.push(currentDetachedCommentInfo);
98768                 }
98769                 else {
98770                     detachedCommentsInfo = [currentDetachedCommentInfo];
98771                 }
98772             }
98773         }
98774         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
98775             if (!shouldWriteComment(currentSourceFile.text, commentPos))
98776                 return;
98777             emitPos(commentPos);
98778             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
98779             emitPos(commentEnd);
98780         }
98781         /**
98782          * Determine if the given comment is a triple-slash
98783          *
98784          * @return true if the comment is a triple-slash comment else false
98785          */
98786         function isTripleSlashComment(commentPos, commentEnd) {
98787             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
98788         }
98789         // Source Maps
98790         function getParsedSourceMap(node) {
98791             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
98792                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
98793             }
98794             return node.parsedSourceMap || undefined;
98795         }
98796         function pipelineEmitWithSourceMap(hint, node) {
98797             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98798             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
98799             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
98800                 pipelinePhase(hint, node);
98801             }
98802             else if (ts.isUnparsedNode(node)) {
98803                 var parsed = getParsedSourceMap(node.parent);
98804                 if (parsed && sourceMapGenerator) {
98805                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
98806                 }
98807                 pipelinePhase(hint, node);
98808             }
98809             else {
98810                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
98811                 var emitFlags = ts.getEmitFlags(node);
98812                 if (node.kind !== 325 /* NotEmittedStatement */
98813                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
98814                     && pos >= 0) {
98815                     emitSourcePos(source, skipSourceTrivia(source, pos));
98816                 }
98817                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
98818                     sourceMapsDisabled = true;
98819                     pipelinePhase(hint, node);
98820                     sourceMapsDisabled = false;
98821                 }
98822                 else {
98823                     pipelinePhase(hint, node);
98824                 }
98825                 if (node.kind !== 325 /* NotEmittedStatement */
98826                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
98827                     && end >= 0) {
98828                     emitSourcePos(source, end);
98829                 }
98830             }
98831             ts.Debug.assert(lastNode === node || lastSubstitution === node);
98832         }
98833         /**
98834          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
98835          */
98836         function skipSourceTrivia(source, pos) {
98837             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
98838         }
98839         /**
98840          * Emits a mapping.
98841          *
98842          * If the position is synthetic (undefined or a negative value), no mapping will be
98843          * created.
98844          *
98845          * @param pos The position.
98846          */
98847         function emitPos(pos) {
98848             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
98849                 return;
98850             }
98851             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
98852             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
98853             /*nameIndex*/ undefined);
98854         }
98855         function emitSourcePos(source, pos) {
98856             if (source !== sourceMapSource) {
98857                 var savedSourceMapSource = sourceMapSource;
98858                 setSourceMapSource(source);
98859                 emitPos(pos);
98860                 setSourceMapSource(savedSourceMapSource);
98861             }
98862             else {
98863                 emitPos(pos);
98864             }
98865         }
98866         /**
98867          * Emits a token of a node with possible leading and trailing source maps.
98868          *
98869          * @param node The node containing the token.
98870          * @param token The token to emit.
98871          * @param tokenStartPos The start pos of the token.
98872          * @param emitCallback The callback used to emit the token.
98873          */
98874         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
98875             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
98876                 return emitCallback(token, writer, tokenPos);
98877             }
98878             var emitNode = node && node.emitNode;
98879             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
98880             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
98881             var source = range && range.source || sourceMapSource;
98882             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
98883             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
98884                 emitSourcePos(source, tokenPos);
98885             }
98886             tokenPos = emitCallback(token, writer, tokenPos);
98887             if (range)
98888                 tokenPos = range.end;
98889             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
98890                 emitSourcePos(source, tokenPos);
98891             }
98892             return tokenPos;
98893         }
98894         function setSourceMapSource(source) {
98895             if (sourceMapsDisabled) {
98896                 return;
98897             }
98898             sourceMapSource = source;
98899             if (isJsonSourceMapSource(source)) {
98900                 return;
98901             }
98902             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
98903             if (printerOptions.inlineSources) {
98904                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
98905             }
98906         }
98907         function isJsonSourceMapSource(sourceFile) {
98908             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
98909         }
98910     }
98911     ts.createPrinter = createPrinter;
98912     function createBracketsMap() {
98913         var brackets = [];
98914         brackets[1024 /* Braces */] = ["{", "}"];
98915         brackets[2048 /* Parenthesis */] = ["(", ")"];
98916         brackets[4096 /* AngleBrackets */] = ["<", ">"];
98917         brackets[8192 /* SquareBrackets */] = ["[", "]"];
98918         return brackets;
98919     }
98920     function getOpeningBracket(format) {
98921         return brackets[format & 15360 /* BracketsMask */][0];
98922     }
98923     function getClosingBracket(format) {
98924         return brackets[format & 15360 /* BracketsMask */][1];
98925     }
98926     // Flags enum to track count of temp variables and a few dedicated names
98927     var TempFlags;
98928     (function (TempFlags) {
98929         TempFlags[TempFlags["Auto"] = 0] = "Auto";
98930         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
98931         TempFlags[TempFlags["_i"] = 268435456] = "_i";
98932     })(TempFlags || (TempFlags = {}));
98933 })(ts || (ts = {}));
98934 /* @internal */
98935 var ts;
98936 (function (ts) {
98937     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
98938         if (!host.getDirectories || !host.readDirectory) {
98939             return undefined;
98940         }
98941         var cachedReadDirectoryResult = ts.createMap();
98942         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
98943         return {
98944             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
98945             fileExists: fileExists,
98946             readFile: function (path, encoding) { return host.readFile(path, encoding); },
98947             directoryExists: host.directoryExists && directoryExists,
98948             getDirectories: getDirectories,
98949             readDirectory: readDirectory,
98950             createDirectory: host.createDirectory && createDirectory,
98951             writeFile: host.writeFile && writeFile,
98952             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
98953             addOrDeleteFile: addOrDeleteFile,
98954             clearCache: clearCache,
98955             realpath: host.realpath && realpath
98956         };
98957         function toPath(fileName) {
98958             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
98959         }
98960         function getCachedFileSystemEntries(rootDirPath) {
98961             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
98962         }
98963         function getCachedFileSystemEntriesForBaseDir(path) {
98964             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
98965         }
98966         function getBaseNameOfFileName(fileName) {
98967             return ts.getBaseFileName(ts.normalizePath(fileName));
98968         }
98969         function createCachedFileSystemEntries(rootDir, rootDirPath) {
98970             var resultFromHost = {
98971                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
98972                 directories: host.getDirectories(rootDir) || []
98973             };
98974             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
98975             return resultFromHost;
98976         }
98977         /**
98978          * If the readDirectory result was already cached, it returns that
98979          * Otherwise gets result from host and caches it.
98980          * The host request is done under try catch block to avoid caching incorrect result
98981          */
98982         function tryReadDirectory(rootDir, rootDirPath) {
98983             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
98984             var cachedResult = getCachedFileSystemEntries(rootDirPath);
98985             if (cachedResult) {
98986                 return cachedResult;
98987             }
98988             try {
98989                 return createCachedFileSystemEntries(rootDir, rootDirPath);
98990             }
98991             catch (_e) {
98992                 // If there is exception to read directories, dont cache the result and direct the calls to host
98993                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
98994                 return undefined;
98995             }
98996         }
98997         function fileNameEqual(name1, name2) {
98998             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
98999         }
99000         function hasEntry(entries, name) {
99001             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
99002         }
99003         function updateFileSystemEntry(entries, baseName, isValid) {
99004             if (hasEntry(entries, baseName)) {
99005                 if (!isValid) {
99006                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
99007                 }
99008             }
99009             else if (isValid) {
99010                 return entries.push(baseName);
99011             }
99012         }
99013         function writeFile(fileName, data, writeByteOrderMark) {
99014             var path = toPath(fileName);
99015             var result = getCachedFileSystemEntriesForBaseDir(path);
99016             if (result) {
99017                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
99018             }
99019             return host.writeFile(fileName, data, writeByteOrderMark);
99020         }
99021         function fileExists(fileName) {
99022             var path = toPath(fileName);
99023             var result = getCachedFileSystemEntriesForBaseDir(path);
99024             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
99025                 host.fileExists(fileName);
99026         }
99027         function directoryExists(dirPath) {
99028             var path = toPath(dirPath);
99029             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
99030         }
99031         function createDirectory(dirPath) {
99032             var path = toPath(dirPath);
99033             var result = getCachedFileSystemEntriesForBaseDir(path);
99034             var baseFileName = getBaseNameOfFileName(dirPath);
99035             if (result) {
99036                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
99037             }
99038             host.createDirectory(dirPath);
99039         }
99040         function getDirectories(rootDir) {
99041             var rootDirPath = toPath(rootDir);
99042             var result = tryReadDirectory(rootDir, rootDirPath);
99043             if (result) {
99044                 return result.directories.slice();
99045             }
99046             return host.getDirectories(rootDir);
99047         }
99048         function readDirectory(rootDir, extensions, excludes, includes, depth) {
99049             var rootDirPath = toPath(rootDir);
99050             var result = tryReadDirectory(rootDir, rootDirPath);
99051             if (result) {
99052                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
99053             }
99054             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
99055             function getFileSystemEntries(dir) {
99056                 var path = toPath(dir);
99057                 if (path === rootDirPath) {
99058                     return result;
99059                 }
99060                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
99061             }
99062         }
99063         function realpath(s) {
99064             return host.realpath ? host.realpath(s) : s;
99065         }
99066         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
99067             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
99068             if (existingResult) {
99069                 // Just clear the cache for now
99070                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
99071                 clearCache();
99072                 return undefined;
99073             }
99074             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
99075             if (!parentResult) {
99076                 return undefined;
99077             }
99078             // This was earlier a file (hence not in cached directory contents)
99079             // or we never cached the directory containing it
99080             if (!host.directoryExists) {
99081                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
99082                 clearCache();
99083                 return undefined;
99084             }
99085             var baseName = getBaseNameOfFileName(fileOrDirectory);
99086             var fsQueryResult = {
99087                 fileExists: host.fileExists(fileOrDirectoryPath),
99088                 directoryExists: host.directoryExists(fileOrDirectoryPath)
99089             };
99090             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
99091                 // Folder added or removed, clear the cache instead of updating the folder and its structure
99092                 clearCache();
99093             }
99094             else {
99095                 // No need to update the directory structure, just files
99096                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
99097             }
99098             return fsQueryResult;
99099         }
99100         function addOrDeleteFile(fileName, filePath, eventKind) {
99101             if (eventKind === ts.FileWatcherEventKind.Changed) {
99102                 return;
99103             }
99104             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
99105             if (parentResult) {
99106                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
99107             }
99108         }
99109         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
99110             updateFileSystemEntry(parentResult.files, baseName, fileExists);
99111         }
99112         function clearCache() {
99113             cachedReadDirectoryResult.clear();
99114         }
99115     }
99116     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
99117     var ConfigFileProgramReloadLevel;
99118     (function (ConfigFileProgramReloadLevel) {
99119         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
99120         /** Update the file name list from the disk */
99121         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
99122         /** Reload completely by re-reading contents of config file from disk and updating program */
99123         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
99124     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
99125     /**
99126      * Updates the existing missing file watches with the new set of missing files after new program is created
99127      */
99128     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
99129         var missingFilePaths = program.getMissingFilePaths();
99130         var newMissingFilePathMap = ts.arrayToSet(missingFilePaths);
99131         // Update the missing file paths watcher
99132         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
99133             // Watch the missing files
99134             createNewValue: createMissingFileWatch,
99135             // Files that are no longer missing (e.g. because they are no longer required)
99136             // should no longer be watched.
99137             onDeleteValue: ts.closeFileWatcher
99138         });
99139     }
99140     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
99141     /**
99142      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
99143      * after new program is created because the config file was reloaded or program was created first time from the config file
99144      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
99145      * as wildcard directories wont change unless reloading config file
99146      */
99147     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
99148         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
99149             // Create new watch and recursive info
99150             createNewValue: createWildcardDirectoryWatcher,
99151             // Close existing watch thats not needed any more
99152             onDeleteValue: closeFileWatcherOf,
99153             // Close existing watch that doesnt match in the flags
99154             onExistingValue: updateWildcardDirectoryWatcher
99155         });
99156         function createWildcardDirectoryWatcher(directory, flags) {
99157             // Create new watch and recursive info
99158             return {
99159                 watcher: watchDirectory(directory, flags),
99160                 flags: flags
99161             };
99162         }
99163         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
99164             // Watcher needs to be updated if the recursive flags dont match
99165             if (existingWatcher.flags === flags) {
99166                 return;
99167             }
99168             existingWatcher.watcher.close();
99169             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
99170         }
99171     }
99172     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
99173     function isEmittedFileOfProgram(program, file) {
99174         if (!program) {
99175             return false;
99176         }
99177         return program.isEmittedFile(file);
99178     }
99179     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
99180     var WatchLogLevel;
99181     (function (WatchLogLevel) {
99182         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
99183         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
99184         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
99185     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
99186     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
99187         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
99188     }
99189     ts.getWatchFactory = getWatchFactory;
99190     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
99191         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
99192         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
99193         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
99194         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
99195             ts.setSysLog(function (s) { return log(s); });
99196         }
99197         return {
99198             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
99199                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99200             },
99201             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
99202                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
99203             },
99204             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
99205                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
99206             }
99207         };
99208     }
99209     function watchFile(host, file, callback, pollingInterval, options) {
99210         return host.watchFile(file, callback, pollingInterval, options);
99211     }
99212     function watchFilePath(host, file, callback, pollingInterval, options, path) {
99213         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
99214     }
99215     function watchDirectory(host, directory, callback, flags, options) {
99216         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
99217     }
99218     function getCreateFileWatcher(watchLogLevel, addWatch) {
99219         switch (watchLogLevel) {
99220             case WatchLogLevel.None:
99221                 return addWatch;
99222             case WatchLogLevel.TriggerOnly:
99223                 return createFileWatcherWithTriggerLogging;
99224             case WatchLogLevel.Verbose:
99225                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
99226         }
99227     }
99228     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99229         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99230         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99231         return {
99232             close: function () {
99233                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
99234                 watcher.close();
99235             }
99236         };
99237     }
99238     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99239         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99240         log(watchInfo);
99241         var start = ts.timestamp();
99242         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
99243         var elapsed = ts.timestamp() - start;
99244         log("Elapsed:: " + elapsed + "ms " + watchInfo);
99245         return {
99246             close: function () {
99247                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99248                 log(watchInfo);
99249                 var start = ts.timestamp();
99250                 watcher.close();
99251                 var elapsed = ts.timestamp() - start;
99252                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
99253             }
99254         };
99255     }
99256     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
99257         return addWatch(host, file, function (fileName, cbOptional) {
99258             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
99259             log(triggerredInfo);
99260             var start = ts.timestamp();
99261             cb(fileName, cbOptional, passThrough);
99262             var elapsed = ts.timestamp() - start;
99263             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
99264         }, flags, options);
99265     }
99266     function getFallbackOptions(options) {
99267         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
99268         return {
99269             watchFile: fallbackPolling !== undefined ?
99270                 fallbackPolling :
99271                 ts.WatchFileKind.PriorityPollingInterval
99272         };
99273     }
99274     ts.getFallbackOptions = getFallbackOptions;
99275     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
99276         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
99277     }
99278     function closeFileWatcherOf(objWithWatcher) {
99279         objWithWatcher.watcher.close();
99280     }
99281     ts.closeFileWatcherOf = closeFileWatcherOf;
99282 })(ts || (ts = {}));
99283 var ts;
99284 (function (ts) {
99285     function findConfigFile(searchPath, fileExists, configName) {
99286         if (configName === void 0) { configName = "tsconfig.json"; }
99287         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
99288             var fileName = ts.combinePaths(ancestor, configName);
99289             return fileExists(fileName) ? fileName : undefined;
99290         });
99291     }
99292     ts.findConfigFile = findConfigFile;
99293     function resolveTripleslashReference(moduleName, containingFile) {
99294         var basePath = ts.getDirectoryPath(containingFile);
99295         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
99296         return ts.normalizePath(referencedFileName);
99297     }
99298     ts.resolveTripleslashReference = resolveTripleslashReference;
99299     /* @internal */
99300     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
99301         var commonPathComponents;
99302         var failed = ts.forEach(fileNames, function (sourceFile) {
99303             // Each file contributes into common source file path
99304             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
99305             sourcePathComponents.pop(); // The base file name is not part of the common directory path
99306             if (!commonPathComponents) {
99307                 // first file
99308                 commonPathComponents = sourcePathComponents;
99309                 return;
99310             }
99311             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
99312             for (var i = 0; i < n; i++) {
99313                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
99314                     if (i === 0) {
99315                         // Failed to find any common path component
99316                         return true;
99317                     }
99318                     // New common path found that is 0 -> i-1
99319                     commonPathComponents.length = i;
99320                     break;
99321                 }
99322             }
99323             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
99324             if (sourcePathComponents.length < commonPathComponents.length) {
99325                 commonPathComponents.length = sourcePathComponents.length;
99326             }
99327         });
99328         // A common path can not be found when paths span multiple drives on windows, for example
99329         if (failed) {
99330             return "";
99331         }
99332         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
99333             return currentDirectory;
99334         }
99335         return ts.getPathFromPathComponents(commonPathComponents);
99336     }
99337     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
99338     function createCompilerHost(options, setParentNodes) {
99339         return createCompilerHostWorker(options, setParentNodes);
99340     }
99341     ts.createCompilerHost = createCompilerHost;
99342     /*@internal*/
99343     // TODO(shkamat): update this after reworking ts build API
99344     function createCompilerHostWorker(options, setParentNodes, system) {
99345         if (system === void 0) { system = ts.sys; }
99346         var existingDirectories = ts.createMap();
99347         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
99348         function getSourceFile(fileName, languageVersion, onError) {
99349             var text;
99350             try {
99351                 ts.performance.mark("beforeIORead");
99352                 text = compilerHost.readFile(fileName);
99353                 ts.performance.mark("afterIORead");
99354                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
99355             }
99356             catch (e) {
99357                 if (onError) {
99358                     onError(e.message);
99359                 }
99360                 text = "";
99361             }
99362             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
99363         }
99364         function directoryExists(directoryPath) {
99365             if (existingDirectories.has(directoryPath)) {
99366                 return true;
99367             }
99368             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
99369                 existingDirectories.set(directoryPath, true);
99370                 return true;
99371             }
99372             return false;
99373         }
99374         function writeFile(fileName, data, writeByteOrderMark, onError) {
99375             try {
99376                 ts.performance.mark("beforeIOWrite");
99377                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
99378                 // the system.writeFile will do its own directory creation and
99379                 // the ensureDirectoriesExist call will always be redundant.
99380                 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); });
99381                 ts.performance.mark("afterIOWrite");
99382                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
99383             }
99384             catch (e) {
99385                 if (onError) {
99386                     onError(e.message);
99387                 }
99388             }
99389         }
99390         var outputFingerprints;
99391         function writeFileWorker(fileName, data, writeByteOrderMark) {
99392             if (!ts.isWatchSet(options) || !system.createHash || !system.getModifiedTime) {
99393                 system.writeFile(fileName, data, writeByteOrderMark);
99394                 return;
99395             }
99396             if (!outputFingerprints) {
99397                 outputFingerprints = ts.createMap();
99398             }
99399             var hash = system.createHash(data);
99400             var mtimeBefore = system.getModifiedTime(fileName);
99401             if (mtimeBefore) {
99402                 var fingerprint = outputFingerprints.get(fileName);
99403                 // If output has not been changed, and the file has no external modification
99404                 if (fingerprint &&
99405                     fingerprint.byteOrderMark === writeByteOrderMark &&
99406                     fingerprint.hash === hash &&
99407                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
99408                     return;
99409                 }
99410             }
99411             system.writeFile(fileName, data, writeByteOrderMark);
99412             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
99413             outputFingerprints.set(fileName, {
99414                 hash: hash,
99415                 byteOrderMark: writeByteOrderMark,
99416                 mtime: mtimeAfter
99417             });
99418         }
99419         function getDefaultLibLocation() {
99420             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
99421         }
99422         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
99423         var realpath = system.realpath && (function (path) { return system.realpath(path); });
99424         var compilerHost = {
99425             getSourceFile: getSourceFile,
99426             getDefaultLibLocation: getDefaultLibLocation,
99427             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
99428             writeFile: writeFile,
99429             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
99430             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
99431             getCanonicalFileName: getCanonicalFileName,
99432             getNewLine: function () { return newLine; },
99433             fileExists: function (fileName) { return system.fileExists(fileName); },
99434             readFile: function (fileName) { return system.readFile(fileName); },
99435             trace: function (s) { return system.write(s + newLine); },
99436             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
99437             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
99438             getDirectories: function (path) { return system.getDirectories(path); },
99439             realpath: realpath,
99440             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
99441             createDirectory: function (d) { return system.createDirectory(d); },
99442             createHash: ts.maybeBind(system, system.createHash)
99443         };
99444         return compilerHost;
99445     }
99446     ts.createCompilerHostWorker = createCompilerHostWorker;
99447     /*@internal*/
99448     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
99449         var originalReadFile = host.readFile;
99450         var originalFileExists = host.fileExists;
99451         var originalDirectoryExists = host.directoryExists;
99452         var originalCreateDirectory = host.createDirectory;
99453         var originalWriteFile = host.writeFile;
99454         var readFileCache = ts.createMap();
99455         var fileExistsCache = ts.createMap();
99456         var directoryExistsCache = ts.createMap();
99457         var sourceFileCache = ts.createMap();
99458         var readFileWithCache = function (fileName) {
99459             var key = toPath(fileName);
99460             var value = readFileCache.get(key);
99461             if (value !== undefined)
99462                 return value !== false ? value : undefined;
99463             return setReadFileCache(key, fileName);
99464         };
99465         var setReadFileCache = function (key, fileName) {
99466             var newValue = originalReadFile.call(host, fileName);
99467             readFileCache.set(key, newValue !== undefined ? newValue : false);
99468             return newValue;
99469         };
99470         host.readFile = function (fileName) {
99471             var key = toPath(fileName);
99472             var value = readFileCache.get(key);
99473             if (value !== undefined)
99474                 return value !== false ? value : undefined; // could be .d.ts from output
99475             // Cache json or buildInfo
99476             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
99477                 return originalReadFile.call(host, fileName);
99478             }
99479             return setReadFileCache(key, fileName);
99480         };
99481         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
99482             var key = toPath(fileName);
99483             var value = sourceFileCache.get(key);
99484             if (value)
99485                 return value;
99486             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
99487             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
99488                 sourceFileCache.set(key, sourceFile);
99489             }
99490             return sourceFile;
99491         } : undefined;
99492         // fileExists for any kind of extension
99493         host.fileExists = function (fileName) {
99494             var key = toPath(fileName);
99495             var value = fileExistsCache.get(key);
99496             if (value !== undefined)
99497                 return value;
99498             var newValue = originalFileExists.call(host, fileName);
99499             fileExistsCache.set(key, !!newValue);
99500             return newValue;
99501         };
99502         if (originalWriteFile) {
99503             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
99504                 var key = toPath(fileName);
99505                 fileExistsCache.delete(key);
99506                 var value = readFileCache.get(key);
99507                 if (value !== undefined && value !== data) {
99508                     readFileCache.delete(key);
99509                     sourceFileCache.delete(key);
99510                 }
99511                 else if (getSourceFileWithCache) {
99512                     var sourceFile = sourceFileCache.get(key);
99513                     if (sourceFile && sourceFile.text !== data) {
99514                         sourceFileCache.delete(key);
99515                     }
99516                 }
99517                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
99518             };
99519         }
99520         // directoryExists
99521         if (originalDirectoryExists && originalCreateDirectory) {
99522             host.directoryExists = function (directory) {
99523                 var key = toPath(directory);
99524                 var value = directoryExistsCache.get(key);
99525                 if (value !== undefined)
99526                     return value;
99527                 var newValue = originalDirectoryExists.call(host, directory);
99528                 directoryExistsCache.set(key, !!newValue);
99529                 return newValue;
99530             };
99531             host.createDirectory = function (directory) {
99532                 var key = toPath(directory);
99533                 directoryExistsCache.delete(key);
99534                 originalCreateDirectory.call(host, directory);
99535             };
99536         }
99537         return {
99538             originalReadFile: originalReadFile,
99539             originalFileExists: originalFileExists,
99540             originalDirectoryExists: originalDirectoryExists,
99541             originalCreateDirectory: originalCreateDirectory,
99542             originalWriteFile: originalWriteFile,
99543             getSourceFileWithCache: getSourceFileWithCache,
99544             readFileWithCache: readFileWithCache
99545         };
99546     }
99547     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
99548     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
99549         var diagnostics;
99550         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
99551         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
99552         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
99553         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
99554         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
99555         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
99556             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
99557         }
99558         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
99559     }
99560     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
99561     function formatDiagnostics(diagnostics, host) {
99562         var output = "";
99563         for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) {
99564             var diagnostic = diagnostics_2[_i];
99565             output += formatDiagnostic(diagnostic, host);
99566         }
99567         return output;
99568     }
99569     ts.formatDiagnostics = formatDiagnostics;
99570     function formatDiagnostic(diagnostic, host) {
99571         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
99572         if (diagnostic.file) {
99573             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
99574             var fileName = diagnostic.file.fileName;
99575             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
99576             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
99577         }
99578         return errorMessage;
99579     }
99580     ts.formatDiagnostic = formatDiagnostic;
99581     /** @internal */
99582     var ForegroundColorEscapeSequences;
99583     (function (ForegroundColorEscapeSequences) {
99584         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
99585         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
99586         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
99587         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
99588         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
99589     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
99590     var gutterStyleSequence = "\u001b[7m";
99591     var gutterSeparator = " ";
99592     var resetEscapeSequence = "\u001b[0m";
99593     var ellipsis = "...";
99594     var halfIndent = "  ";
99595     var indent = "    ";
99596     function getCategoryFormat(category) {
99597         switch (category) {
99598             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
99599             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
99600             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
99601             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
99602         }
99603     }
99604     /** @internal */
99605     function formatColorAndReset(text, formatStyle) {
99606         return formatStyle + text + resetEscapeSequence;
99607     }
99608     ts.formatColorAndReset = formatColorAndReset;
99609     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
99610         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
99611         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
99612         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
99613         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
99614         var gutterWidth = (lastLine + 1 + "").length;
99615         if (hasMoreThanFiveLines) {
99616             gutterWidth = Math.max(ellipsis.length, gutterWidth);
99617         }
99618         var context = "";
99619         for (var i = firstLine; i <= lastLine; i++) {
99620             context += host.getNewLine();
99621             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
99622             // so we'll skip ahead to the second-to-last line.
99623             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
99624                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
99625                 i = lastLine - 1;
99626             }
99627             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
99628             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
99629             var lineContent = file.text.slice(lineStart, lineEnd);
99630             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
99631             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
99632             // Output the gutter and the actual contents of the line.
99633             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
99634             context += lineContent + host.getNewLine();
99635             // Output the gutter and the error span for the line using tildes.
99636             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
99637             context += squiggleColor;
99638             if (i === firstLine) {
99639                 // If we're on the last line, then limit it to the last character of the last line.
99640                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
99641                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
99642                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
99643                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
99644             }
99645             else if (i === lastLine) {
99646                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
99647             }
99648             else {
99649                 // Squiggle the entire line.
99650                 context += lineContent.replace(/./g, "~");
99651             }
99652             context += resetEscapeSequence;
99653         }
99654         return context;
99655     }
99656     /* @internal */
99657     function formatLocation(file, start, host, color) {
99658         if (color === void 0) { color = formatColorAndReset; }
99659         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
99660         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
99661         var output = "";
99662         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
99663         output += ":";
99664         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
99665         output += ":";
99666         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
99667         return output;
99668     }
99669     ts.formatLocation = formatLocation;
99670     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
99671         var output = "";
99672         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
99673             var diagnostic = diagnostics_3[_i];
99674             if (diagnostic.file) {
99675                 var file = diagnostic.file, start = diagnostic.start;
99676                 output += formatLocation(file, start, host); // TODO: GH#18217
99677                 output += " - ";
99678             }
99679             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
99680             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
99681             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
99682             if (diagnostic.file) {
99683                 output += host.getNewLine();
99684                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
99685                 if (diagnostic.relatedInformation) {
99686                     output += host.getNewLine();
99687                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
99688                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
99689                         if (file) {
99690                             output += host.getNewLine();
99691                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
99692                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
99693                         }
99694                         output += host.getNewLine();
99695                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
99696                     }
99697                 }
99698             }
99699             output += host.getNewLine();
99700         }
99701         return output;
99702     }
99703     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
99704     function flattenDiagnosticMessageText(diag, newLine, indent) {
99705         if (indent === void 0) { indent = 0; }
99706         if (ts.isString(diag)) {
99707             return diag;
99708         }
99709         else if (diag === undefined) {
99710             return "";
99711         }
99712         var result = "";
99713         if (indent) {
99714             result += newLine;
99715             for (var i = 0; i < indent; i++) {
99716                 result += "  ";
99717             }
99718         }
99719         result += diag.messageText;
99720         indent++;
99721         if (diag.next) {
99722             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
99723                 var kid = _a[_i];
99724                 result += flattenDiagnosticMessageText(kid, newLine, indent);
99725             }
99726         }
99727         return result;
99728     }
99729     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
99730     /* @internal */
99731     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
99732         if (names.length === 0) {
99733             return [];
99734         }
99735         var resolutions = [];
99736         var cache = ts.createMap();
99737         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
99738             var name = names_2[_i];
99739             var result = void 0;
99740             if (cache.has(name)) {
99741                 result = cache.get(name);
99742             }
99743             else {
99744                 cache.set(name, result = loader(name, containingFile, redirectedReference));
99745             }
99746             resolutions.push(result);
99747         }
99748         return resolutions;
99749     }
99750     ts.loadWithLocalCache = loadWithLocalCache;
99751     /* @internal */
99752     ts.inferredTypesContainingFile = "__inferred type names__.ts";
99753     /**
99754      * Determines if program structure is upto date or needs to be recreated
99755      */
99756     /* @internal */
99757     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
99758         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
99759         if (!program || hasChangedAutomaticTypeDirectiveNames) {
99760             return false;
99761         }
99762         // If root file names don't match
99763         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
99764             return false;
99765         }
99766         var seenResolvedRefs;
99767         // If project references don't match
99768         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
99769             return false;
99770         }
99771         // If any file is not up-to-date, then the whole program is not up-to-date
99772         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
99773             return false;
99774         }
99775         // If any of the missing file paths are now created
99776         if (program.getMissingFilePaths().some(fileExists)) {
99777             return false;
99778         }
99779         var currentOptions = program.getCompilerOptions();
99780         // If the compilation settings do no match, then the program is not up-to-date
99781         if (!ts.compareDataObjects(currentOptions, newOptions)) {
99782             return false;
99783         }
99784         // If everything matches but the text of config file is changed,
99785         // error locations can change for program options, so update the program
99786         if (currentOptions.configFile && newOptions.configFile) {
99787             return currentOptions.configFile.text === newOptions.configFile.text;
99788         }
99789         return true;
99790         function sourceFileNotUptoDate(sourceFile) {
99791             return !sourceFileVersionUptoDate(sourceFile) ||
99792                 hasInvalidatedResolution(sourceFile.path);
99793         }
99794         function sourceFileVersionUptoDate(sourceFile) {
99795             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
99796         }
99797         function projectReferenceUptoDate(oldRef, newRef, index) {
99798             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
99799                 return false;
99800             }
99801             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
99802         }
99803         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
99804             if (oldResolvedRef) {
99805                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
99806                     // Assume true
99807                     return true;
99808                 }
99809                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
99810                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
99811                     return false;
99812                 }
99813                 // Add to seen before checking the referenced paths of this config file
99814                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
99815                 // If child project references are upto date, this project reference is uptodate
99816                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
99817                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
99818                 });
99819             }
99820             // In old program, not able to resolve project reference path,
99821             // so if config file doesnt exist, it is uptodate.
99822             return !fileExists(resolveProjectReferencePath(oldRef));
99823         }
99824     }
99825     ts.isProgramUptoDate = isProgramUptoDate;
99826     function getConfigFileParsingDiagnostics(configFileParseResult) {
99827         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
99828             configFileParseResult.errors;
99829     }
99830     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
99831     /**
99832      * Determine if source file needs to be re-created even if its text hasn't changed
99833      */
99834     function shouldProgramCreateNewSourceFiles(program, newOptions) {
99835         if (!program)
99836             return false;
99837         // If any compiler options change, we can't reuse old source file even if version match
99838         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
99839         var oldOptions = program.getCompilerOptions();
99840         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
99841             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
99842         });
99843     }
99844     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
99845         return {
99846             rootNames: rootNames,
99847             options: options,
99848             host: host,
99849             oldProgram: oldProgram,
99850             configFileParsingDiagnostics: configFileParsingDiagnostics
99851         };
99852     }
99853     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
99854         var _a;
99855         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
99856         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
99857         var oldProgram = createProgramOptions.oldProgram;
99858         var processingDefaultLibFiles;
99859         var processingOtherFiles;
99860         var files;
99861         var symlinks;
99862         var commonSourceDirectory;
99863         var diagnosticsProducingTypeChecker;
99864         var noDiagnosticsTypeChecker;
99865         var classifiableNames;
99866         var ambientModuleNameToUnmodifiedFileName = ts.createMap();
99867         // Todo:: Use this to report why file was included in --extendedDiagnostics
99868         var refFileMap;
99869         var cachedBindAndCheckDiagnosticsForFile = {};
99870         var cachedDeclarationDiagnosticsForFile = {};
99871         var resolvedTypeReferenceDirectives = ts.createMap();
99872         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
99873         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
99874         // This works as imported modules are discovered recursively in a depth first manner, specifically:
99875         // - For each root file, findSourceFile is called.
99876         // - This calls processImportedModules for each module imported in the source file.
99877         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
99878         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
99879         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
99880         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
99881         var currentNodeModulesDepth = 0;
99882         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
99883         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
99884         var modulesWithElidedImports = ts.createMap();
99885         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
99886         var sourceFilesFoundSearchingNodeModules = ts.createMap();
99887         ts.performance.mark("beforeProgram");
99888         var host = createProgramOptions.host || createCompilerHost(options);
99889         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
99890         var skipDefaultLib = options.noLib;
99891         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
99892         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
99893         var programDiagnostics = ts.createDiagnosticCollection();
99894         var currentDirectory = host.getCurrentDirectory();
99895         var supportedExtensions = ts.getSupportedExtensions(options);
99896         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
99897         // Map storing if there is emit blocking diagnostics for given input
99898         var hasEmitBlockingDiagnostics = ts.createMap();
99899         var _compilerOptionsObjectLiteralSyntax;
99900         var moduleResolutionCache;
99901         var actualResolveModuleNamesWorker;
99902         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
99903         if (host.resolveModuleNames) {
99904             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
99905                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
99906                 if (!resolved || resolved.extension !== undefined) {
99907                     return resolved;
99908                 }
99909                 var withExtension = ts.clone(resolved);
99910                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
99911                 return withExtension;
99912             }); };
99913         }
99914         else {
99915             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
99916             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
99917             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
99918         }
99919         var actualResolveTypeReferenceDirectiveNamesWorker;
99920         if (host.resolveTypeReferenceDirectives) {
99921             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
99922         }
99923         else {
99924             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
99925             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
99926         }
99927         // Map from a stringified PackageId to the source file with that id.
99928         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
99929         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
99930         var packageIdToSourceFile = ts.createMap();
99931         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
99932         var sourceFileToPackageName = ts.createMap();
99933         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
99934         var redirectTargetsMap = ts.createMultiMap();
99935         /**
99936          * map with
99937          * - SourceFile if present
99938          * - false if sourceFile missing for source of project reference redirect
99939          * - undefined otherwise
99940          */
99941         var filesByName = ts.createMap();
99942         var missingFilePaths;
99943         // stores 'filename -> file association' ignoring case
99944         // used to track cases when two file names differ only in casing
99945         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createMap() : undefined;
99946         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
99947         var resolvedProjectReferences;
99948         var projectReferenceRedirects;
99949         var mapFromFileToProjectReferenceRedirects;
99950         var mapFromToProjectReferenceRedirectSource;
99951         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
99952             !options.disableSourceOfProjectReferenceRedirect;
99953         var _b = updateHostForUseSourceOfProjectReferenceRedirect({
99954             compilerHost: host,
99955             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
99956             toPath: toPath,
99957             getResolvedProjectReferences: getResolvedProjectReferences,
99958             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
99959             forEachResolvedProjectReference: forEachResolvedProjectReference
99960         }), onProgramCreateComplete = _b.onProgramCreateComplete, fileExists = _b.fileExists;
99961         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
99962         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
99963         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
99964         var structuralIsReused;
99965         structuralIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
99966         if (structuralIsReused !== 2 /* Completely */) {
99967             processingDefaultLibFiles = [];
99968             processingOtherFiles = [];
99969             if (projectReferences) {
99970                 if (!resolvedProjectReferences) {
99971                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
99972                 }
99973                 if (rootNames.length) {
99974                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
99975                         var parsedRef = resolvedProjectReferences_1[_i];
99976                         if (!parsedRef)
99977                             continue;
99978                         var out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
99979                         if (useSourceOfProjectReferenceRedirect) {
99980                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
99981                                 for (var _c = 0, _d = parsedRef.commandLine.fileNames; _c < _d.length; _c++) {
99982                                     var fileName = _d[_c];
99983                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99984                                 }
99985                             }
99986                         }
99987                         else {
99988                             if (out) {
99989                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99990                             }
99991                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
99992                                 for (var _e = 0, _f = parsedRef.commandLine.fileNames; _e < _f.length; _e++) {
99993                                     var fileName = _f[_e];
99994                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
99995                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
99996                                     }
99997                                 }
99998                             }
99999                         }
100000                     }
100001                 }
100002             }
100003             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
100004             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
100005             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
100006             if (typeReferences.length) {
100007                 // This containingFilename needs to match with the one used in managed-side
100008                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
100009                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
100010                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
100011                 for (var i = 0; i < typeReferences.length; i++) {
100012                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
100013                 }
100014             }
100015             // Do not process the default library if:
100016             //  - The '--noLib' flag is used.
100017             //  - A 'no-default-lib' reference comment is encountered in
100018             //      processing the root files.
100019             if (rootNames.length && !skipDefaultLib) {
100020                 // If '--lib' is not specified, include default library file according to '--target'
100021                 // otherwise, using options specified in '--lib' instead of '--target' default library file
100022                 var defaultLibraryFileName = getDefaultLibraryFileName();
100023                 if (!options.lib && defaultLibraryFileName) {
100024                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100025                 }
100026                 else {
100027                     ts.forEach(options.lib, function (libFileName) {
100028                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
100029                     });
100030                 }
100031             }
100032             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
100033                 var path = _a[0], file = _a[1];
100034                 return file === undefined ? path : undefined;
100035             }));
100036             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
100037             processingDefaultLibFiles = undefined;
100038             processingOtherFiles = undefined;
100039         }
100040         ts.Debug.assert(!!missingFilePaths);
100041         // Release any files we have acquired in the old program but are
100042         // not part of the new program.
100043         if (oldProgram && host.onReleaseOldSourceFile) {
100044             var oldSourceFiles = oldProgram.getSourceFiles();
100045             for (var _g = 0, oldSourceFiles_1 = oldSourceFiles; _g < oldSourceFiles_1.length; _g++) {
100046                 var oldSourceFile = oldSourceFiles_1[_g];
100047                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
100048                 if (shouldCreateNewSourceFile || !newFile ||
100049                     // old file wasnt redirect but new file is
100050                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
100051                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
100052                 }
100053             }
100054             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference, resolvedProjectReferencePath) {
100055                 if (resolvedProjectReference && !getResolvedProjectReferenceByPath(resolvedProjectReferencePath)) {
100056                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
100057                 }
100058             });
100059         }
100060         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
100061         oldProgram = undefined;
100062         var program = {
100063             getRootFileNames: function () { return rootNames; },
100064             getSourceFile: getSourceFile,
100065             getSourceFileByPath: getSourceFileByPath,
100066             getSourceFiles: function () { return files; },
100067             getMissingFilePaths: function () { return missingFilePaths; },
100068             getRefFileMap: function () { return refFileMap; },
100069             getFilesByNameMap: function () { return filesByName; },
100070             getCompilerOptions: function () { return options; },
100071             getSyntacticDiagnostics: getSyntacticDiagnostics,
100072             getOptionsDiagnostics: getOptionsDiagnostics,
100073             getGlobalDiagnostics: getGlobalDiagnostics,
100074             getSemanticDiagnostics: getSemanticDiagnostics,
100075             getSuggestionDiagnostics: getSuggestionDiagnostics,
100076             getDeclarationDiagnostics: getDeclarationDiagnostics,
100077             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
100078             getProgramDiagnostics: getProgramDiagnostics,
100079             getTypeChecker: getTypeChecker,
100080             getClassifiableNames: getClassifiableNames,
100081             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
100082             getCommonSourceDirectory: getCommonSourceDirectory,
100083             emit: emit,
100084             getCurrentDirectory: function () { return currentDirectory; },
100085             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
100086             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
100087             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
100088             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
100089             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
100090             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
100091             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
100092             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
100093             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100094             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
100095             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
100096             getSourceFileFromReference: getSourceFileFromReference,
100097             getLibFileFromReference: getLibFileFromReference,
100098             sourceFileToPackageName: sourceFileToPackageName,
100099             redirectTargetsMap: redirectTargetsMap,
100100             isEmittedFile: isEmittedFile,
100101             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
100102             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
100103             getProjectReferences: getProjectReferences,
100104             getResolvedProjectReferences: getResolvedProjectReferences,
100105             getProjectReferenceRedirect: getProjectReferenceRedirect,
100106             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100107             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
100108             forEachResolvedProjectReference: forEachResolvedProjectReference,
100109             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100110             emitBuildInfo: emitBuildInfo,
100111             fileExists: fileExists,
100112             getProbableSymlinks: getProbableSymlinks,
100113             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100114         };
100115         onProgramCreateComplete();
100116         verifyCompilerOptions();
100117         ts.performance.mark("afterProgram");
100118         ts.performance.measure("Program", "beforeProgram", "afterProgram");
100119         return program;
100120         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference) {
100121             ts.performance.mark("beforeResolveModule");
100122             var result = actualResolveModuleNamesWorker(moduleNames, containingFile, reusedNames, redirectedReference);
100123             ts.performance.mark("afterResolveModule");
100124             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
100125             return result;
100126         }
100127         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference) {
100128             ts.performance.mark("beforeResolveTypeReference");
100129             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, redirectedReference);
100130             ts.performance.mark("afterResolveTypeReference");
100131             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
100132             return result;
100133         }
100134         function compareDefaultLibFiles(a, b) {
100135             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
100136         }
100137         function getDefaultLibFilePriority(a) {
100138             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
100139                 var basename = ts.getBaseFileName(a.fileName);
100140                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
100141                     return 0;
100142                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
100143                 var index = ts.libs.indexOf(name);
100144                 if (index !== -1)
100145                     return index + 1;
100146             }
100147             return ts.libs.length + 2;
100148         }
100149         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
100150             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
100151         }
100152         function toPath(fileName) {
100153             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
100154         }
100155         function getCommonSourceDirectory() {
100156             if (commonSourceDirectory === undefined) {
100157                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
100158                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
100159                     // If a rootDir is specified use it as the commonSourceDirectory
100160                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
100161                 }
100162                 else if (options.composite && options.configFilePath) {
100163                     // Project compilations never infer their root from the input source paths
100164                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
100165                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
100166                 }
100167                 else {
100168                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
100169                 }
100170                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
100171                     // Make sure directory path ends with directory separator so this string can directly
100172                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
100173                     // start with / making it rooted path
100174                     commonSourceDirectory += ts.directorySeparator;
100175                 }
100176             }
100177             return commonSourceDirectory;
100178         }
100179         function getClassifiableNames() {
100180             if (!classifiableNames) {
100181                 // Initialize a checker so that all our files are bound.
100182                 getTypeChecker();
100183                 classifiableNames = ts.createUnderscoreEscapedMap();
100184                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
100185                     var sourceFile = files_2[_i];
100186                     ts.copyEntries(sourceFile.classifiableNames, classifiableNames);
100187                 }
100188             }
100189             return classifiableNames;
100190         }
100191         function resolveModuleNamesReusingOldState(moduleNames, containingFile, file) {
100192             if (structuralIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
100193                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
100194                 // the best we can do is fallback to the default logic.
100195                 return resolveModuleNamesWorker(moduleNames, containingFile, /*reusedNames*/ undefined, getResolvedProjectReferenceToRedirect(file.originalFileName));
100196             }
100197             var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile);
100198             if (oldSourceFile !== file && file.resolvedModules) {
100199                 // `file` was created for the new program.
100200                 //
100201                 // We only set `file.resolvedModules` via work from the current function,
100202                 // so it is defined iff we already called the current function on `file`.
100203                 // That call happened no later than the creation of the `file` object,
100204                 // which per above occurred during the current program creation.
100205                 // Since we assume the filesystem does not change during program creation,
100206                 // it is safe to reuse resolutions from the earlier call.
100207                 var result_11 = [];
100208                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
100209                     var moduleName = moduleNames_1[_i];
100210                     var resolvedModule = file.resolvedModules.get(moduleName);
100211                     result_11.push(resolvedModule);
100212                 }
100213                 return result_11;
100214             }
100215             // At this point, we know at least one of the following hold:
100216             // - file has local declarations for ambient modules
100217             // - old program state is available
100218             // With this information, we can infer some module resolutions without performing resolution.
100219             /** An ordered list of module names for which we cannot recover the resolution. */
100220             var unknownModuleNames;
100221             /**
100222              * The indexing of elements in this list matches that of `moduleNames`.
100223              *
100224              * Before combining results, result[i] is in one of the following states:
100225              * * undefined: needs to be recomputed,
100226              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
100227              * Needs to be reset to undefined before returning,
100228              * * ResolvedModuleFull instance: can be reused.
100229              */
100230             var result;
100231             var reusedNames;
100232             /** A transient placeholder used to mark predicted resolution in the result list. */
100233             var predictedToResolveToAmbientModuleMarker = {};
100234             for (var i = 0; i < moduleNames.length; i++) {
100235                 var moduleName = moduleNames[i];
100236                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
100237                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
100238                     var oldResolvedModule = oldSourceFile && oldSourceFile.resolvedModules.get(moduleName);
100239                     if (oldResolvedModule) {
100240                         if (ts.isTraceEnabled(options, host)) {
100241                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, containingFile);
100242                         }
100243                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
100244                         (reusedNames || (reusedNames = [])).push(moduleName);
100245                         continue;
100246                     }
100247                 }
100248                 // We know moduleName resolves to an ambient module provided that moduleName:
100249                 // - is in the list of ambient modules locally declared in the current source file.
100250                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
100251                 //   (so the same module declaration will land in the new program)
100252                 var resolvesToAmbientModuleInNonModifiedFile = false;
100253                 if (ts.contains(file.ambientModuleNames, moduleName)) {
100254                     resolvesToAmbientModuleInNonModifiedFile = true;
100255                     if (ts.isTraceEnabled(options, host)) {
100256                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, containingFile);
100257                     }
100258                 }
100259                 else {
100260                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
100261                 }
100262                 if (resolvesToAmbientModuleInNonModifiedFile) {
100263                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
100264                 }
100265                 else {
100266                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
100267                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
100268                 }
100269             }
100270             var resolutions = unknownModuleNames && unknownModuleNames.length
100271                 ? resolveModuleNamesWorker(unknownModuleNames, containingFile, reusedNames, getResolvedProjectReferenceToRedirect(file.originalFileName))
100272                 : ts.emptyArray;
100273             // Combine results of resolutions and predicted results
100274             if (!result) {
100275                 // There were no unresolved/ambient resolutions.
100276                 ts.Debug.assert(resolutions.length === moduleNames.length);
100277                 return resolutions;
100278             }
100279             var j = 0;
100280             for (var i = 0; i < result.length; i++) {
100281                 if (result[i]) {
100282                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
100283                     // If it is the former, we can leave it as is.
100284                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
100285                         result[i] = undefined; // TODO: GH#18217
100286                     }
100287                 }
100288                 else {
100289                     result[i] = resolutions[j];
100290                     j++;
100291                 }
100292             }
100293             ts.Debug.assert(j === resolutions.length);
100294             return result;
100295             // If we change our policy of rechecking failed lookups on each program create,
100296             // we should adjust the value returned here.
100297             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
100298                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
100299                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
100300                 if (resolutionToFile && resolvedFile) {
100301                     // In the old program, we resolved to an ambient module that was in the same
100302                     //   place as we expected to find an actual module file.
100303                     // We actually need to return 'false' here even though this seems like a 'true' case
100304                     //   because the normal module resolution algorithm will find this anyway.
100305                     return false;
100306                 }
100307                 // at least one of declarations should come from non-modified source file
100308                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
100309                 if (!unmodifiedFile) {
100310                     return false;
100311                 }
100312                 if (ts.isTraceEnabled(options, host)) {
100313                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
100314                 }
100315                 return true;
100316             }
100317         }
100318         function canReuseProjectReferences() {
100319             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, index, parent) {
100320                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
100321                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
100322                 if (oldResolvedRef) {
100323                     // Resolved project reference has gone missing or changed
100324                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
100325                 }
100326                 else {
100327                     // A previously-unresolved reference may be resolved now
100328                     return newResolvedRef !== undefined;
100329                 }
100330             }, function (oldProjectReferences, parent) {
100331                 // If array of references is changed, we cant resue old program
100332                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
100333                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
100334             });
100335         }
100336         function tryReuseStructureFromOldProgram() {
100337             if (!oldProgram) {
100338                 return 0 /* Not */;
100339             }
100340             // check properties that can affect structure of the program or module resolution strategy
100341             // if any of these properties has changed - structure cannot be reused
100342             var oldOptions = oldProgram.getCompilerOptions();
100343             if (ts.changesAffectModuleResolution(oldOptions, options)) {
100344                 return oldProgram.structureIsReused = 0 /* Not */;
100345             }
100346             ts.Debug.assert(!(oldProgram.structureIsReused & (2 /* Completely */ | 1 /* SafeModules */)));
100347             // there is an old program, check if we can reuse its structure
100348             var oldRootNames = oldProgram.getRootFileNames();
100349             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
100350                 return oldProgram.structureIsReused = 0 /* Not */;
100351             }
100352             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
100353                 return oldProgram.structureIsReused = 0 /* Not */;
100354             }
100355             // Check if any referenced project tsconfig files are different
100356             if (!canReuseProjectReferences()) {
100357                 return oldProgram.structureIsReused = 0 /* Not */;
100358             }
100359             if (projectReferences) {
100360                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
100361             }
100362             // check if program source files has changed in the way that can affect structure of the program
100363             var newSourceFiles = [];
100364             var modifiedSourceFiles = [];
100365             oldProgram.structureIsReused = 2 /* Completely */;
100366             // If the missing file paths are now present, it can change the progam structure,
100367             // and hence cant reuse the structure.
100368             // This is same as how we dont reuse the structure if one of the file from old program is now missing
100369             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
100370                 return oldProgram.structureIsReused = 0 /* Not */;
100371             }
100372             var oldSourceFiles = oldProgram.getSourceFiles();
100373             var SeenPackageName;
100374             (function (SeenPackageName) {
100375                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
100376                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
100377             })(SeenPackageName || (SeenPackageName = {}));
100378             var seenPackageNames = ts.createMap();
100379             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
100380                 var oldSourceFile = oldSourceFiles_2[_i];
100381                 var newSourceFile = host.getSourceFileByPath
100382                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
100383                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
100384                 if (!newSourceFile) {
100385                     return oldProgram.structureIsReused = 0 /* Not */;
100386                 }
100387                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
100388                 var fileChanged = void 0;
100389                 if (oldSourceFile.redirectInfo) {
100390                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
100391                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
100392                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
100393                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
100394                         return oldProgram.structureIsReused = 0 /* Not */;
100395                     }
100396                     fileChanged = false;
100397                     newSourceFile = oldSourceFile; // Use the redirect.
100398                 }
100399                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
100400                     // If a redirected-to source file changes, the redirect may be broken.
100401                     if (newSourceFile !== oldSourceFile) {
100402                         return oldProgram.structureIsReused = 0 /* Not */;
100403                     }
100404                     fileChanged = false;
100405                 }
100406                 else {
100407                     fileChanged = newSourceFile !== oldSourceFile;
100408                 }
100409                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
100410                 newSourceFile.path = oldSourceFile.path;
100411                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
100412                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
100413                 newSourceFile.fileName = oldSourceFile.fileName;
100414                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
100415                 if (packageName !== undefined) {
100416                     // If there are 2 different source files for the same package name and at least one of them changes,
100417                     // they might become redirects. So we must rebuild the program.
100418                     var prevKind = seenPackageNames.get(packageName);
100419                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
100420                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
100421                         return oldProgram.structureIsReused = 0 /* Not */;
100422                     }
100423                     seenPackageNames.set(packageName, newKind);
100424                 }
100425                 if (fileChanged) {
100426                     // The `newSourceFile` object was created for the new program.
100427                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
100428                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
100429                         return oldProgram.structureIsReused = 0 /* Not */;
100430                     }
100431                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
100432                         // value of no-default-lib has changed
100433                         // this will affect if default library is injected into the list of files
100434                         oldProgram.structureIsReused = 1 /* SafeModules */;
100435                     }
100436                     // check tripleslash references
100437                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
100438                         // tripleslash references has changed
100439                         oldProgram.structureIsReused = 1 /* SafeModules */;
100440                     }
100441                     // check imports and module augmentations
100442                     collectExternalModuleReferences(newSourceFile);
100443                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
100444                         // imports has changed
100445                         oldProgram.structureIsReused = 1 /* SafeModules */;
100446                     }
100447                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
100448                         // moduleAugmentations has changed
100449                         oldProgram.structureIsReused = 1 /* SafeModules */;
100450                     }
100451                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
100452                         // dynamicImport has changed
100453                         oldProgram.structureIsReused = 1 /* SafeModules */;
100454                     }
100455                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
100456                         // 'types' references has changed
100457                         oldProgram.structureIsReused = 1 /* SafeModules */;
100458                     }
100459                     // tentatively approve the file
100460                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100461                 }
100462                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
100463                     // 'module/types' references could have changed
100464                     oldProgram.structureIsReused = 1 /* SafeModules */;
100465                     // add file to the modified list so that we will resolve it later
100466                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
100467                 }
100468                 // if file has passed all checks it should be safe to reuse it
100469                 newSourceFiles.push(newSourceFile);
100470             }
100471             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100472                 return oldProgram.structureIsReused;
100473             }
100474             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
100475             for (var _a = 0, oldSourceFiles_3 = oldSourceFiles; _a < oldSourceFiles_3.length; _a++) {
100476                 var oldFile = oldSourceFiles_3[_a];
100477                 if (!ts.contains(modifiedFiles, oldFile)) {
100478                     for (var _b = 0, _c = oldFile.ambientModuleNames; _b < _c.length; _b++) {
100479                         var moduleName = _c[_b];
100480                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
100481                     }
100482                 }
100483             }
100484             // try to verify results of module resolution
100485             for (var _d = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _d < modifiedSourceFiles_1.length; _d++) {
100486                 var _e = modifiedSourceFiles_1[_d], oldSourceFile = _e.oldFile, newSourceFile = _e.newFile;
100487                 var newSourceFilePath = ts.getNormalizedAbsolutePath(newSourceFile.originalFileName, currentDirectory);
100488                 var moduleNames = getModuleNames(newSourceFile);
100489                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFilePath, newSourceFile);
100490                 // ensure that module resolution results are still correct
100491                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
100492                 if (resolutionsChanged) {
100493                     oldProgram.structureIsReused = 1 /* SafeModules */;
100494                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
100495                 }
100496                 else {
100497                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
100498                 }
100499                 if (resolveTypeReferenceDirectiveNamesWorker) {
100500                     // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
100501                     var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
100502                     var resolutions_1 = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath, getResolvedProjectReferenceToRedirect(newSourceFile.originalFileName));
100503                     // ensure that types resolutions are still correct
100504                     var resolutionsChanged_1 = ts.hasChangesInResolutions(typesReferenceDirectives, resolutions_1, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
100505                     if (resolutionsChanged_1) {
100506                         oldProgram.structureIsReused = 1 /* SafeModules */;
100507                         newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, resolutions_1);
100508                     }
100509                     else {
100510                         newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
100511                     }
100512                 }
100513             }
100514             if (oldProgram.structureIsReused !== 2 /* Completely */) {
100515                 return oldProgram.structureIsReused;
100516             }
100517             if (host.hasChangedAutomaticTypeDirectiveNames) {
100518                 return oldProgram.structureIsReused = 1 /* SafeModules */;
100519             }
100520             missingFilePaths = oldProgram.getMissingFilePaths();
100521             refFileMap = oldProgram.getRefFileMap();
100522             // update fileName -> file mapping
100523             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
100524             for (var _f = 0, newSourceFiles_1 = newSourceFiles; _f < newSourceFiles_1.length; _f++) {
100525                 var newSourceFile = newSourceFiles_1[_f];
100526                 filesByName.set(newSourceFile.path, newSourceFile);
100527             }
100528             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
100529             oldFilesByNameMap.forEach(function (oldFile, path) {
100530                 if (!oldFile) {
100531                     filesByName.set(path, oldFile);
100532                     return;
100533                 }
100534                 if (oldFile.path === path) {
100535                     // Set the file as found during node modules search if it was found that way in old progra,
100536                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
100537                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
100538                     }
100539                     return;
100540                 }
100541                 filesByName.set(path, filesByName.get(oldFile.path));
100542             });
100543             files = newSourceFiles;
100544             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
100545             for (var _g = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _g < modifiedSourceFiles_2.length; _g++) {
100546                 var modifiedFile = modifiedSourceFiles_2[_g];
100547                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
100548             }
100549             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
100550             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
100551             redirectTargetsMap = oldProgram.redirectTargetsMap;
100552             return oldProgram.structureIsReused = 2 /* Completely */;
100553         }
100554         function getEmitHost(writeFileCallback) {
100555             return {
100556                 getPrependNodes: getPrependNodes,
100557                 getCanonicalFileName: getCanonicalFileName,
100558                 getCommonSourceDirectory: program.getCommonSourceDirectory,
100559                 getCompilerOptions: program.getCompilerOptions,
100560                 getCurrentDirectory: function () { return currentDirectory; },
100561                 getNewLine: function () { return host.getNewLine(); },
100562                 getSourceFile: program.getSourceFile,
100563                 getSourceFileByPath: program.getSourceFileByPath,
100564                 getSourceFiles: program.getSourceFiles,
100565                 getLibFileFromReference: program.getLibFileFromReference,
100566                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
100567                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
100568                 getProjectReferenceRedirect: getProjectReferenceRedirect,
100569                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
100570                 getProbableSymlinks: getProbableSymlinks,
100571                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
100572                 isEmitBlocked: isEmitBlocked,
100573                 readFile: function (f) { return host.readFile(f); },
100574                 fileExists: function (f) {
100575                     // Use local caches
100576                     var path = toPath(f);
100577                     if (getSourceFileByPath(path))
100578                         return true;
100579                     if (ts.contains(missingFilePaths, path))
100580                         return false;
100581                     // Before falling back to the host
100582                     return host.fileExists(f);
100583                 },
100584                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
100585                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
100586                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
100587                 redirectTargetsMap: redirectTargetsMap,
100588             };
100589         }
100590         function emitBuildInfo(writeFileCallback) {
100591             ts.Debug.assert(!options.out && !options.outFile);
100592             ts.performance.mark("beforeEmit");
100593             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
100594             /*targetSourceFile*/ undefined, 
100595             /*transformers*/ ts.noTransformers, 
100596             /*emitOnlyDtsFiles*/ false, 
100597             /*onlyBuildInfo*/ true);
100598             ts.performance.mark("afterEmit");
100599             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100600             return emitResult;
100601         }
100602         function getResolvedProjectReferences() {
100603             return resolvedProjectReferences;
100604         }
100605         function getProjectReferences() {
100606             return projectReferences;
100607         }
100608         function getPrependNodes() {
100609             return createPrependNodes(projectReferences, function (_ref, index) { return resolvedProjectReferences[index].commandLine; }, function (fileName) {
100610                 var path = toPath(fileName);
100611                 var sourceFile = getSourceFileByPath(path);
100612                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
100613             });
100614         }
100615         function isSourceFileFromExternalLibrary(file) {
100616             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
100617         }
100618         function isSourceFileDefaultLibrary(file) {
100619             if (file.hasNoDefaultLib) {
100620                 return true;
100621             }
100622             if (!options.noLib) {
100623                 return false;
100624             }
100625             // If '--lib' is not specified, include default library file according to '--target'
100626             // otherwise, using options specified in '--lib' instead of '--target' default library file
100627             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
100628             if (!options.lib) {
100629                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
100630             }
100631             else {
100632                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
100633             }
100634         }
100635         function getDiagnosticsProducingTypeChecker() {
100636             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
100637         }
100638         function dropDiagnosticsProducingTypeChecker() {
100639             diagnosticsProducingTypeChecker = undefined;
100640         }
100641         function getTypeChecker() {
100642             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
100643         }
100644         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
100645             return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
100646         }
100647         function isEmitBlocked(emitFileName) {
100648             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
100649         }
100650         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
100651             if (!forceDtsEmit) {
100652                 var result = handleNoEmitOptions(program, sourceFile, cancellationToken);
100653                 if (result)
100654                     return result;
100655             }
100656             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
100657             // any cost associated with it (like type checking) are appropriate associated with
100658             // the type-checking counter.
100659             //
100660             // If the -out option is specified, we should not pass the source file to getEmitResolver.
100661             // This is because in the -out scenario all files need to be emitted, and therefore all
100662             // files need to be type checked. And the way to specify that all files need to be type
100663             // checked is to not pass the file to getEmitResolver.
100664             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken);
100665             ts.performance.mark("beforeEmit");
100666             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
100667             /*onlyBuildInfo*/ false, forceDtsEmit);
100668             ts.performance.mark("afterEmit");
100669             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
100670             return emitResult;
100671         }
100672         function getSourceFile(fileName) {
100673             return getSourceFileByPath(toPath(fileName));
100674         }
100675         function getSourceFileByPath(path) {
100676             return filesByName.get(path) || undefined;
100677         }
100678         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
100679             if (sourceFile) {
100680                 return getDiagnostics(sourceFile, cancellationToken);
100681             }
100682             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
100683                 if (cancellationToken) {
100684                     cancellationToken.throwIfCancellationRequested();
100685                 }
100686                 return getDiagnostics(sourceFile, cancellationToken);
100687             }));
100688         }
100689         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
100690             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
100691         }
100692         function getSemanticDiagnostics(sourceFile, cancellationToken) {
100693             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
100694         }
100695         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
100696             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
100697         }
100698         function getProgramDiagnostics(sourceFile) {
100699             if (ts.skipTypeChecking(sourceFile, options, program)) {
100700                 return ts.emptyArray;
100701             }
100702             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
100703             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
100704             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
100705         }
100706         function getMergedProgramDiagnostics(sourceFile) {
100707             var _a;
100708             var allDiagnostics = [];
100709             for (var _i = 1; _i < arguments.length; _i++) {
100710                 allDiagnostics[_i - 1] = arguments[_i];
100711             }
100712             var flatDiagnostics = ts.flatten(allDiagnostics);
100713             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100714                 return flatDiagnostics;
100715             }
100716             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
100717         }
100718         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
100719             var options = program.getCompilerOptions();
100720             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
100721             if (!sourceFile || options.out || options.outFile) {
100722                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
100723             }
100724             else {
100725                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
100726             }
100727         }
100728         function getSyntacticDiagnosticsForFile(sourceFile) {
100729             // For JavaScript files, we report semantic errors for using TypeScript-only
100730             // constructs from within a JavaScript file as syntactic errors.
100731             if (ts.isSourceFileJS(sourceFile)) {
100732                 if (!sourceFile.additionalSyntacticDiagnostics) {
100733                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
100734                 }
100735                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
100736             }
100737             return sourceFile.parseDiagnostics;
100738         }
100739         function runWithCancellationToken(func) {
100740             try {
100741                 return func();
100742             }
100743             catch (e) {
100744                 if (e instanceof ts.OperationCanceledException) {
100745                     // We were canceled while performing the operation.  Because our type checker
100746                     // might be a bad state, we need to throw it away.
100747                     //
100748                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
100749                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
100750                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
100751                     // cancel when the user has made a change anyways.  And, in that case, we (the
100752                     // program instance) will get thrown away anyways.  So trying to keep one of
100753                     // these type checkers alive doesn't serve much purpose.
100754                     noDiagnosticsTypeChecker = undefined;
100755                     diagnosticsProducingTypeChecker = undefined;
100756                 }
100757                 throw e;
100758             }
100759         }
100760         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
100761             return ts.concatenate(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), getProgramDiagnostics(sourceFile));
100762         }
100763         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
100764             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
100765         }
100766         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
100767             return runWithCancellationToken(function () {
100768                 if (ts.skipTypeChecking(sourceFile, options, program)) {
100769                     return ts.emptyArray;
100770                 }
100771                 var typeChecker = getDiagnosticsProducingTypeChecker();
100772                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
100773                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
100774                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
100775                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
100776                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
100777                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
100778                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
100779                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
100780                 return getMergedBindAndCheckDiagnostics(sourceFile, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
100781             });
100782         }
100783         function getMergedBindAndCheckDiagnostics(sourceFile) {
100784             var _a;
100785             var allDiagnostics = [];
100786             for (var _i = 1; _i < arguments.length; _i++) {
100787                 allDiagnostics[_i - 1] = arguments[_i];
100788             }
100789             var flatDiagnostics = ts.flatten(allDiagnostics);
100790             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
100791                 return flatDiagnostics;
100792             }
100793             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
100794             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
100795                 var errorExpectation = _d[_c];
100796                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
100797             }
100798             return diagnostics;
100799         }
100800         /**
100801          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
100802          * Comments that match to any of those diagnostics are marked as used.
100803          */
100804         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
100805             // Diagnostics are only reported if there is no comment directive preceding them
100806             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
100807             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
100808             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
100809             return { diagnostics: diagnostics, directives: directives };
100810         }
100811         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
100812             return runWithCancellationToken(function () {
100813                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
100814             });
100815         }
100816         /**
100817          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
100818          */
100819         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
100820             var file = diagnostic.file, start = diagnostic.start;
100821             if (!file) {
100822                 return -1;
100823             }
100824             // Start out with the line just before the text
100825             var lineStarts = ts.getLineStarts(file);
100826             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
100827             while (line >= 0) {
100828                 // As soon as that line is known to have a comment directive, use that
100829                 if (directives.markUsed(line)) {
100830                     return line;
100831                 }
100832                 // Stop searching if the line is not empty and not a comment
100833                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
100834                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
100835                     return -1;
100836                 }
100837                 line--;
100838             }
100839             return -1;
100840         }
100841         function getJSSyntacticDiagnosticsForFile(sourceFile) {
100842             return runWithCancellationToken(function () {
100843                 var diagnostics = [];
100844                 walk(sourceFile, sourceFile);
100845                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
100846                 return diagnostics;
100847                 function walk(node, parent) {
100848                     // Return directly from the case if the given node doesnt want to visit each child
100849                     // Otherwise break to visit each child
100850                     switch (parent.kind) {
100851                         case 156 /* Parameter */:
100852                         case 159 /* PropertyDeclaration */:
100853                         case 161 /* MethodDeclaration */:
100854                             if (parent.questionToken === node) {
100855                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
100856                                 return "skip";
100857                             }
100858                         // falls through
100859                         case 160 /* MethodSignature */:
100860                         case 162 /* Constructor */:
100861                         case 163 /* GetAccessor */:
100862                         case 164 /* SetAccessor */:
100863                         case 201 /* FunctionExpression */:
100864                         case 244 /* FunctionDeclaration */:
100865                         case 202 /* ArrowFunction */:
100866                         case 242 /* VariableDeclaration */:
100867                             // type annotation
100868                             if (parent.type === node) {
100869                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
100870                                 return "skip";
100871                             }
100872                     }
100873                     switch (node.kind) {
100874                         case 255 /* ImportClause */:
100875                             if (node.isTypeOnly) {
100876                                 diagnostics.push(createDiagnosticForNode(node.parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
100877                                 return "skip";
100878                             }
100879                             break;
100880                         case 260 /* ExportDeclaration */:
100881                             if (node.isTypeOnly) {
100882                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
100883                                 return "skip";
100884                             }
100885                             break;
100886                         case 253 /* ImportEqualsDeclaration */:
100887                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
100888                             return "skip";
100889                         case 259 /* ExportAssignment */:
100890                             if (node.isExportEquals) {
100891                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
100892                                 return "skip";
100893                             }
100894                             break;
100895                         case 279 /* HeritageClause */:
100896                             var heritageClause = node;
100897                             if (heritageClause.token === 113 /* ImplementsKeyword */) {
100898                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
100899                                 return "skip";
100900                             }
100901                             break;
100902                         case 246 /* InterfaceDeclaration */:
100903                             var interfaceKeyword = ts.tokenToString(114 /* InterfaceKeyword */);
100904                             ts.Debug.assertIsDefined(interfaceKeyword);
100905                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
100906                             return "skip";
100907                         case 249 /* ModuleDeclaration */:
100908                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(136 /* NamespaceKeyword */) : ts.tokenToString(135 /* ModuleKeyword */);
100909                             ts.Debug.assertIsDefined(moduleKeyword);
100910                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
100911                             return "skip";
100912                         case 247 /* TypeAliasDeclaration */:
100913                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
100914                             return "skip";
100915                         case 248 /* EnumDeclaration */:
100916                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(88 /* EnumKeyword */));
100917                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
100918                             return "skip";
100919                         case 218 /* NonNullExpression */:
100920                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
100921                             return "skip";
100922                         case 217 /* AsExpression */:
100923                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
100924                             return "skip";
100925                         case 199 /* TypeAssertionExpression */:
100926                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
100927                     }
100928                 }
100929                 function walkArray(nodes, parent) {
100930                     if (parent.decorators === nodes && !options.experimentalDecorators) {
100931                         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));
100932                     }
100933                     switch (parent.kind) {
100934                         case 245 /* ClassDeclaration */:
100935                         case 214 /* ClassExpression */:
100936                         case 161 /* MethodDeclaration */:
100937                         case 162 /* Constructor */:
100938                         case 163 /* GetAccessor */:
100939                         case 164 /* SetAccessor */:
100940                         case 201 /* FunctionExpression */:
100941                         case 244 /* FunctionDeclaration */:
100942                         case 202 /* ArrowFunction */:
100943                             // Check type parameters
100944                             if (nodes === parent.typeParameters) {
100945                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
100946                                 return "skip";
100947                             }
100948                         // falls through
100949                         case 225 /* VariableStatement */:
100950                             // Check modifiers
100951                             if (nodes === parent.modifiers) {
100952                                 checkModifiers(parent.modifiers, parent.kind === 225 /* VariableStatement */);
100953                                 return "skip";
100954                             }
100955                             break;
100956                         case 159 /* PropertyDeclaration */:
100957                             // Check modifiers of property declaration
100958                             if (nodes === parent.modifiers) {
100959                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
100960                                     var modifier = _a[_i];
100961                                     if (modifier.kind !== 120 /* StaticKeyword */) {
100962                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
100963                                     }
100964                                 }
100965                                 return "skip";
100966                             }
100967                             break;
100968                         case 156 /* Parameter */:
100969                             // Check modifiers of parameter declaration
100970                             if (nodes === parent.modifiers) {
100971                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
100972                                 return "skip";
100973                             }
100974                             break;
100975                         case 196 /* CallExpression */:
100976                         case 197 /* NewExpression */:
100977                         case 216 /* ExpressionWithTypeArguments */:
100978                         case 267 /* JsxSelfClosingElement */:
100979                         case 268 /* JsxOpeningElement */:
100980                         case 198 /* TaggedTemplateExpression */:
100981                             // Check type arguments
100982                             if (nodes === parent.typeArguments) {
100983                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
100984                                 return "skip";
100985                             }
100986                             break;
100987                     }
100988                 }
100989                 function checkModifiers(modifiers, isConstValid) {
100990                     for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
100991                         var modifier = modifiers_1[_i];
100992                         switch (modifier.kind) {
100993                             case 81 /* ConstKeyword */:
100994                                 if (isConstValid) {
100995                                     continue;
100996                                 }
100997                             // to report error,
100998                             // falls through
100999                             case 119 /* PublicKeyword */:
101000                             case 117 /* PrivateKeyword */:
101001                             case 118 /* ProtectedKeyword */:
101002                             case 138 /* ReadonlyKeyword */:
101003                             case 130 /* DeclareKeyword */:
101004                             case 122 /* AbstractKeyword */:
101005                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
101006                                 break;
101007                             // These are all legal modifiers.
101008                             case 120 /* StaticKeyword */:
101009                             case 89 /* ExportKeyword */:
101010                             case 84 /* DefaultKeyword */:
101011                         }
101012                     }
101013                 }
101014                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
101015                     var start = nodes.pos;
101016                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
101017                 }
101018                 // Since these are syntactic diagnostics, parent might not have been set
101019                 // this means the sourceFile cannot be infered from the node
101020                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
101021                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
101022                 }
101023             });
101024         }
101025         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
101026             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
101027         }
101028         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
101029             return runWithCancellationToken(function () {
101030                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
101031                 // Don't actually write any files since we're just getting diagnostics.
101032                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
101033             });
101034         }
101035         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
101036             var cachedResult = sourceFile
101037                 ? cache.perFile && cache.perFile.get(sourceFile.path)
101038                 : cache.allDiagnostics;
101039             if (cachedResult) {
101040                 return cachedResult;
101041             }
101042             var result = getDiagnostics(sourceFile, cancellationToken);
101043             if (sourceFile) {
101044                 if (!cache.perFile) {
101045                     cache.perFile = ts.createMap();
101046                 }
101047                 cache.perFile.set(sourceFile.path, result);
101048             }
101049             else {
101050                 cache.allDiagnostics = result;
101051             }
101052             return result;
101053         }
101054         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
101055             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
101056         }
101057         function getOptionsDiagnostics() {
101058             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
101059         }
101060         function getOptionsDiagnosticsOfConfigFile() {
101061             if (!options.configFile) {
101062                 return ts.emptyArray;
101063             }
101064             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
101065             forEachResolvedProjectReference(function (resolvedRef) {
101066                 if (resolvedRef) {
101067                     diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
101068                 }
101069             });
101070             return diagnostics;
101071         }
101072         function getGlobalDiagnostics() {
101073             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
101074         }
101075         function getConfigFileParsingDiagnostics() {
101076             return configFileParsingDiagnostics || ts.emptyArray;
101077         }
101078         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
101079             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
101080         }
101081         function fileReferenceIsEqualTo(a, b) {
101082             return a.fileName === b.fileName;
101083         }
101084         function moduleNameIsEqualTo(a, b) {
101085             return a.kind === 75 /* Identifier */
101086                 ? b.kind === 75 /* Identifier */ && a.escapedText === b.escapedText
101087                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
101088         }
101089         function collectExternalModuleReferences(file) {
101090             if (file.imports) {
101091                 return;
101092             }
101093             var isJavaScriptFile = ts.isSourceFileJS(file);
101094             var isExternalModuleFile = ts.isExternalModule(file);
101095             // file.imports may not be undefined if there exists dynamic import
101096             var imports;
101097             var moduleAugmentations;
101098             var ambientModules;
101099             // If we are importing helpers, we need to add a synthetic reference to resolve the
101100             // helpers library.
101101             if (options.importHelpers
101102                 && (options.isolatedModules || isExternalModuleFile)
101103                 && !file.isDeclarationFile) {
101104                 // synthesize 'import "tslib"' declaration
101105                 var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText);
101106                 var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
101107                 ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
101108                 externalHelpersModuleReference.parent = importDecl;
101109                 importDecl.parent = file;
101110                 imports = [externalHelpersModuleReference];
101111             }
101112             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
101113                 var node = _a[_i];
101114                 collectModuleReferences(node, /*inAmbientModule*/ false);
101115             }
101116             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
101117                 collectDynamicImportOrRequireCalls(file);
101118             }
101119             file.imports = imports || ts.emptyArray;
101120             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
101121             file.ambientModuleNames = ambientModules || ts.emptyArray;
101122             return;
101123             function collectModuleReferences(node, inAmbientModule) {
101124                 if (ts.isAnyImportOrReExport(node)) {
101125                     var moduleNameExpr = ts.getExternalModuleName(node);
101126                     // TypeScript 1.0 spec (April 2014): 12.1.6
101127                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
101128                     // only through top - level external module names. Relative external module names are not permitted.
101129                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
101130                         imports = ts.append(imports, moduleNameExpr);
101131                     }
101132                 }
101133                 else if (ts.isModuleDeclaration(node)) {
101134                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
101135                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
101136                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
101137                         // This will happen in two cases:
101138                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
101139                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
101140                         //   immediately nested in top level ambient module declaration .
101141                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
101142                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
101143                         }
101144                         else if (!inAmbientModule) {
101145                             if (file.isDeclarationFile) {
101146                                 // for global .d.ts files record name of ambient module
101147                                 (ambientModules || (ambientModules = [])).push(nameText);
101148                             }
101149                             // An AmbientExternalModuleDeclaration declares an external module.
101150                             // This type of declaration is permitted only in the global module.
101151                             // The StringLiteral must specify a top - level external module name.
101152                             // Relative external module names are not permitted
101153                             // NOTE: body of ambient module is always a module block, if it exists
101154                             var body = node.body;
101155                             if (body) {
101156                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
101157                                     var statement = _a[_i];
101158                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
101159                                 }
101160                             }
101161                         }
101162                     }
101163                 }
101164             }
101165             function collectDynamicImportOrRequireCalls(file) {
101166                 var r = /import|require/g;
101167                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
101168                     var node = getNodeAtPosition(file, r.lastIndex);
101169                     if (ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
101170                         imports = ts.append(imports, node.arguments[0]);
101171                     }
101172                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
101173                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
101174                         imports = ts.append(imports, node.arguments[0]);
101175                     }
101176                     else if (ts.isLiteralImportTypeNode(node)) {
101177                         imports = ts.append(imports, node.argument.literal);
101178                     }
101179                 }
101180             }
101181             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
101182             function getNodeAtPosition(sourceFile, position) {
101183                 var current = sourceFile;
101184                 var getContainingChild = function (child) {
101185                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
101186                         return child;
101187                     }
101188                 };
101189                 while (true) {
101190                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
101191                     if (!child) {
101192                         return current;
101193                     }
101194                     current = child;
101195                 }
101196             }
101197         }
101198         function getLibFileFromReference(ref) {
101199             var libName = ts.toFileNameLowerCase(ref.fileName);
101200             var libFileName = ts.libMap.get(libName);
101201             if (libFileName) {
101202                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
101203             }
101204         }
101205         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
101206         function getSourceFileFromReference(referencingFile, ref) {
101207             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
101208         }
101209         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
101210             if (ts.hasExtension(fileName)) {
101211                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
101212                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
101213                     if (fail) {
101214                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
101215                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
101216                         }
101217                         else {
101218                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101219                         }
101220                     }
101221                     return undefined;
101222                 }
101223                 var sourceFile = getSourceFile(fileName);
101224                 if (fail) {
101225                     if (!sourceFile) {
101226                         var redirect = getProjectReferenceRedirect(fileName);
101227                         if (redirect) {
101228                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
101229                         }
101230                         else {
101231                             fail(ts.Diagnostics.File_0_not_found, fileName);
101232                         }
101233                     }
101234                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
101235                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
101236                     }
101237                 }
101238                 return sourceFile;
101239             }
101240             else {
101241                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
101242                 if (sourceFileNoExtension)
101243                     return sourceFileNoExtension;
101244                 if (fail && options.allowNonTsExtensions) {
101245                     fail(ts.Diagnostics.File_0_not_found, fileName);
101246                     return undefined;
101247                 }
101248                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
101249                 if (fail && !sourceFileWithAddedExtension)
101250                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
101251                 return sourceFileWithAddedExtension;
101252             }
101253         }
101254         /** This has side effects through `findSourceFile`. */
101255         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
101256             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
101257             function (diagnostic) {
101258                 var args = [];
101259                 for (var _i = 1; _i < arguments.length; _i++) {
101260                     args[_i - 1] = arguments[_i];
101261                 }
101262                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
101263             }, refFile && refFile.file);
101264         }
101265         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
101266             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
101267             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
101268             fileProcessingDiagnostics.add(refToReportErrorOn ?
101269                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
101270                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
101271         }
101272         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
101273             var redirect = Object.create(redirectTarget);
101274             redirect.fileName = fileName;
101275             redirect.path = path;
101276             redirect.resolvedPath = resolvedPath;
101277             redirect.originalFileName = originalFileName;
101278             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
101279             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101280             Object.defineProperties(redirect, {
101281                 id: {
101282                     get: function () { return this.redirectInfo.redirectTarget.id; },
101283                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
101284                 },
101285                 symbol: {
101286                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
101287                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
101288                 },
101289             });
101290             return redirect;
101291         }
101292         // Get source file from normalized fileName
101293         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
101294             if (useSourceOfProjectReferenceRedirect) {
101295                 var source = getSourceOfProjectReferenceRedirect(fileName);
101296                 // If preserveSymlinks is true, module resolution wont jump the symlink
101297                 // but the resolved real path may be the .d.ts from project reference
101298                 // Note:: Currently we try the real path only if the
101299                 // file is from node_modules to avoid having to run real path on all file paths
101300                 if (!source &&
101301                     host.realpath &&
101302                     options.preserveSymlinks &&
101303                     ts.isDeclarationFileName(fileName) &&
101304                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
101305                     var realPath = host.realpath(fileName);
101306                     if (realPath !== fileName)
101307                         source = getSourceOfProjectReferenceRedirect(realPath);
101308                 }
101309                 if (source) {
101310                     var file_1 = ts.isString(source) ?
101311                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
101312                         undefined;
101313                     if (file_1)
101314                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
101315                     return file_1;
101316                 }
101317             }
101318             var originalFileName = fileName;
101319             if (filesByName.has(path)) {
101320                 var file_2 = filesByName.get(path);
101321                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
101322                 // try to check if we've already seen this file but with a different casing in path
101323                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
101324                 if (file_2 && options.forceConsistentCasingInFileNames) {
101325                     var checkedName = file_2.fileName;
101326                     var isRedirect = toPath(checkedName) !== toPath(fileName);
101327                     if (isRedirect) {
101328                         fileName = getProjectReferenceRedirect(fileName) || fileName;
101329                     }
101330                     // Check if it differs only in drive letters its ok to ignore that error:
101331                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
101332                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
101333                     if (checkedAbsolutePath !== inputAbsolutePath) {
101334                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
101335                     }
101336                 }
101337                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
101338                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
101339                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
101340                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
101341                     if (!options.noResolve) {
101342                         processReferencedFiles(file_2, isDefaultLib);
101343                         processTypeReferenceDirectives(file_2);
101344                     }
101345                     if (!options.noLib) {
101346                         processLibReferenceDirectives(file_2);
101347                     }
101348                     modulesWithElidedImports.set(file_2.path, false);
101349                     processImportedModules(file_2);
101350                 }
101351                 // See if we need to reprocess the imports due to prior skipped imports
101352                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
101353                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
101354                         modulesWithElidedImports.set(file_2.path, false);
101355                         processImportedModules(file_2);
101356                     }
101357                 }
101358                 return file_2 || undefined;
101359             }
101360             var redirectedPath;
101361             if (refFile && !useSourceOfProjectReferenceRedirect) {
101362                 var redirectProject = getProjectReferenceRedirectProject(fileName);
101363                 if (redirectProject) {
101364                     if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
101365                         // Shouldnt create many to 1 mapping file in --out scenario
101366                         return undefined;
101367                     }
101368                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
101369                     fileName = redirect;
101370                     // Once we start redirecting to a file, we can potentially come back to it
101371                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
101372                     // end up trying to add it to the program *again* because we were tracking it via its
101373                     // original (un-redirected) name. So we have to map both the original path and the redirected path
101374                     // to the source file we're about to find/create
101375                     redirectedPath = toPath(redirect);
101376                 }
101377             }
101378             // We haven't looked for this file, do so now and cache result
101379             var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { return fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); }, shouldCreateNewSourceFile);
101380             if (packageId) {
101381                 var packageIdKey = ts.packageIdToString(packageId);
101382                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
101383                 if (fileFromPackageId) {
101384                     // Some other SourceFile already exists with this package name and version.
101385                     // Instead of creating a duplicate, just redirect to the existing one.
101386                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
101387                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
101388                     addFileToFilesByName(dupFile, path, redirectedPath);
101389                     sourceFileToPackageName.set(path, packageId.name);
101390                     processingOtherFiles.push(dupFile);
101391                     return dupFile;
101392                 }
101393                 else if (file) {
101394                     // This is the first source file to have this packageId.
101395                     packageIdToSourceFile.set(packageIdKey, file);
101396                     sourceFileToPackageName.set(path, packageId.name);
101397                 }
101398             }
101399             addFileToFilesByName(file, path, redirectedPath);
101400             if (file) {
101401                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
101402                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
101403                 file.path = path;
101404                 file.resolvedPath = toPath(fileName);
101405                 file.originalFileName = originalFileName;
101406                 addFileToRefFileMap(fileName, file, refFile);
101407                 if (host.useCaseSensitiveFileNames()) {
101408                     var pathLowerCase = ts.toFileNameLowerCase(path);
101409                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
101410                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
101411                     if (existingFile) {
101412                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
101413                     }
101414                     else {
101415                         filesByNameIgnoreCase.set(pathLowerCase, file);
101416                     }
101417                 }
101418                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
101419                 if (!options.noResolve) {
101420                     processReferencedFiles(file, isDefaultLib);
101421                     processTypeReferenceDirectives(file);
101422                 }
101423                 if (!options.noLib) {
101424                     processLibReferenceDirectives(file);
101425                 }
101426                 // always process imported modules to record module name resolutions
101427                 processImportedModules(file);
101428                 if (isDefaultLib) {
101429                     processingDefaultLibFiles.push(file);
101430                 }
101431                 else {
101432                     processingOtherFiles.push(file);
101433                 }
101434             }
101435             return file;
101436         }
101437         function addFileToRefFileMap(referencedFileName, file, refFile) {
101438             if (refFile && file) {
101439                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
101440                     referencedFileName: referencedFileName,
101441                     kind: refFile.kind,
101442                     index: refFile.index,
101443                     file: refFile.file.path
101444                 });
101445             }
101446         }
101447         function addFileToFilesByName(file, path, redirectedPath) {
101448             if (redirectedPath) {
101449                 filesByName.set(redirectedPath, file);
101450                 filesByName.set(path, file || false);
101451             }
101452             else {
101453                 filesByName.set(path, file);
101454             }
101455         }
101456         function getProjectReferenceRedirect(fileName) {
101457             var referencedProject = getProjectReferenceRedirectProject(fileName);
101458             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
101459         }
101460         function getProjectReferenceRedirectProject(fileName) {
101461             // Ignore dts or any json files
101462             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101463                 return undefined;
101464             }
101465             // If this file is produced by a referenced project, we need to rewrite it to
101466             // look in the output folder of the referenced project rather than the input
101467             return getResolvedProjectReferenceToRedirect(fileName);
101468         }
101469         function getProjectReferenceOutputName(referencedProject, fileName) {
101470             var out = referencedProject.commandLine.options.outFile || referencedProject.commandLine.options.out;
101471             return out ?
101472                 ts.changeExtension(out, ".d.ts" /* Dts */) :
101473                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
101474         }
101475         /**
101476          * Get the referenced project if the file is input file from that reference project
101477          */
101478         function getResolvedProjectReferenceToRedirect(fileName) {
101479             if (mapFromFileToProjectReferenceRedirects === undefined) {
101480                 mapFromFileToProjectReferenceRedirects = ts.createMap();
101481                 forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) {
101482                     // not input file from the referenced project, ignore
101483                     if (referencedProject &&
101484                         toPath(options.configFilePath) !== referenceProjectPath) {
101485                         referencedProject.commandLine.fileNames.forEach(function (f) {
101486                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referenceProjectPath);
101487                         });
101488                     }
101489                 });
101490             }
101491             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
101492             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
101493         }
101494         function forEachResolvedProjectReference(cb) {
101495             return forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
101496                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
101497                 var resolvedRefPath = toPath(resolveProjectReferencePath(ref));
101498                 return cb(resolvedRef, resolvedRefPath);
101499             });
101500         }
101501         function getSourceOfProjectReferenceRedirect(file) {
101502             if (!ts.isDeclarationFileName(file))
101503                 return undefined;
101504             if (mapFromToProjectReferenceRedirectSource === undefined) {
101505                 mapFromToProjectReferenceRedirectSource = ts.createMap();
101506                 forEachResolvedProjectReference(function (resolvedRef) {
101507                     if (resolvedRef) {
101508                         var out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
101509                         if (out) {
101510                             // Dont know which source file it means so return true?
101511                             var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
101512                             mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
101513                         }
101514                         else {
101515                             ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
101516                                 if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
101517                                     var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
101518                                     mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
101519                                 }
101520                             });
101521                         }
101522                     }
101523                 });
101524             }
101525             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
101526         }
101527         function isSourceOfProjectReferenceRedirect(fileName) {
101528             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
101529         }
101530         function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
101531             var seenResolvedRefs;
101532             return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined, cbResolvedRef, cbRef);
101533             function worker(projectReferences, resolvedProjectReferences, parent, cbResolvedRef, cbRef) {
101534                 // Visit project references first
101535                 if (cbRef) {
101536                     var result = cbRef(projectReferences, parent);
101537                     if (result) {
101538                         return result;
101539                     }
101540                 }
101541                 return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
101542                     if (ts.contains(seenResolvedRefs, resolvedRef)) {
101543                         // ignore recursives
101544                         return undefined;
101545                     }
101546                     var result = cbResolvedRef(resolvedRef, index, parent);
101547                     if (result) {
101548                         return result;
101549                     }
101550                     if (!resolvedRef)
101551                         return undefined;
101552                     (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
101553                     return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef, cbResolvedRef, cbRef);
101554                 });
101555             }
101556         }
101557         function getResolvedProjectReferenceByPath(projectReferencePath) {
101558             if (!projectReferenceRedirects) {
101559                 return undefined;
101560             }
101561             return projectReferenceRedirects.get(projectReferencePath) || undefined;
101562         }
101563         function processReferencedFiles(file, isDefaultLib) {
101564             ts.forEach(file.referencedFiles, function (ref, index) {
101565                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.originalFileName);
101566                 processSourceFile(referencedFileName, isDefaultLib, 
101567                 /*ignoreNoDefaultLib*/ false, 
101568                 /*packageId*/ undefined, {
101569                     kind: ts.RefFileKind.ReferenceFile,
101570                     index: index,
101571                     file: file,
101572                     pos: ref.pos,
101573                     end: ref.end
101574                 });
101575             });
101576         }
101577         function processTypeReferenceDirectives(file) {
101578             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
101579             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
101580             if (!typeDirectives) {
101581                 return;
101582             }
101583             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.originalFileName, getResolvedProjectReferenceToRedirect(file.originalFileName));
101584             for (var i = 0; i < typeDirectives.length; i++) {
101585                 var ref = file.typeReferenceDirectives[i];
101586                 var resolvedTypeReferenceDirective = resolutions[i];
101587                 // store resolved type directive on the file
101588                 var fileName = ts.toFileNameLowerCase(ref.fileName);
101589                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
101590                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
101591                     kind: ts.RefFileKind.TypeReferenceDirective,
101592                     index: i,
101593                     file: file,
101594                     pos: ref.pos,
101595                     end: ref.end
101596                 });
101597             }
101598         }
101599         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
101600             // If we already found this library as a primary reference - nothing to do
101601             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
101602             if (previousResolution && previousResolution.primary) {
101603                 return;
101604             }
101605             var saveResolution = true;
101606             if (resolvedTypeReferenceDirective) {
101607                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101608                     currentNodeModulesDepth++;
101609                 if (resolvedTypeReferenceDirective.primary) {
101610                     // resolved from the primary path
101611                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
101612                 }
101613                 else {
101614                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
101615                     // for sameness and possibly issue an error
101616                     if (previousResolution) {
101617                         // Don't bother reading the file again if it's the same file.
101618                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
101619                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
101620                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
101621                             if (otherFileText !== existingFile_1.text) {
101622                                 // Try looking up ref for original file
101623                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
101624                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
101625                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
101626                                     createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName) :
101627                                     createRefFileDiagnostic(refFile, ts.Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName));
101628                             }
101629                         }
101630                         // don't overwrite previous resolution result
101631                         saveResolution = false;
101632                     }
101633                     else {
101634                         // First resolution of this library
101635                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
101636                     }
101637                 }
101638                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
101639                     currentNodeModulesDepth--;
101640             }
101641             else {
101642                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
101643             }
101644             if (saveResolution) {
101645                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
101646             }
101647         }
101648         function processLibReferenceDirectives(file) {
101649             ts.forEach(file.libReferenceDirectives, function (libReference) {
101650                 var libName = ts.toFileNameLowerCase(libReference.fileName);
101651                 var libFileName = ts.libMap.get(libName);
101652                 if (libFileName) {
101653                     // we ignore any 'no-default-lib' reference set on this file.
101654                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
101655                 }
101656                 else {
101657                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
101658                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
101659                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
101660                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
101661                 }
101662             });
101663         }
101664         function createRefFileDiagnostic(refFile, message) {
101665             var args = [];
101666             for (var _i = 2; _i < arguments.length; _i++) {
101667                 args[_i - 2] = arguments[_i];
101668             }
101669             if (!refFile) {
101670                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
101671             }
101672             else {
101673                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
101674             }
101675         }
101676         function getCanonicalFileName(fileName) {
101677             return host.getCanonicalFileName(fileName);
101678         }
101679         function processImportedModules(file) {
101680             collectExternalModuleReferences(file);
101681             if (file.imports.length || file.moduleAugmentations.length) {
101682                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
101683                 var moduleNames = getModuleNames(file);
101684                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory), file);
101685                 ts.Debug.assert(resolutions.length === moduleNames.length);
101686                 for (var i = 0; i < moduleNames.length; i++) {
101687                     var resolution = resolutions[i];
101688                     ts.setResolvedModule(file, moduleNames[i], resolution);
101689                     if (!resolution) {
101690                         continue;
101691                     }
101692                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
101693                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
101694                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
101695                     var resolvedFileName = resolution.resolvedFileName;
101696                     if (isFromNodeModulesSearch) {
101697                         currentNodeModulesDepth++;
101698                     }
101699                     // add file to program only if:
101700                     // - resolution was successful
101701                     // - noResolve is falsy
101702                     // - module name comes from the list of imports
101703                     // - it's not a top level JavaScript module that exceeded the search max
101704                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
101705                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
101706                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
101707                     var shouldAddFile = resolvedFileName
101708                         && !getResolutionDiagnostic(options, resolution)
101709                         && !options.noResolve
101710                         && i < file.imports.length
101711                         && !elideImport
101712                         && !(isJsFile && !options.allowJs)
101713                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
101714                     if (elideImport) {
101715                         modulesWithElidedImports.set(file.path, true);
101716                     }
101717                     else if (shouldAddFile) {
101718                         var path = toPath(resolvedFileName);
101719                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
101720                         findSourceFile(resolvedFileName, path, 
101721                         /*isDefaultLib*/ false, 
101722                         /*ignoreNoDefaultLib*/ false, {
101723                             kind: ts.RefFileKind.Import,
101724                             index: i,
101725                             file: file,
101726                             pos: pos,
101727                             end: file.imports[i].end
101728                         }, resolution.packageId);
101729                     }
101730                     if (isFromNodeModulesSearch) {
101731                         currentNodeModulesDepth--;
101732                     }
101733                 }
101734             }
101735             else {
101736                 // no imports - drop cached module resolutions
101737                 file.resolvedModules = undefined;
101738             }
101739         }
101740         function computeCommonSourceDirectory(sourceFiles) {
101741             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
101742             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
101743         }
101744         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
101745             var allFilesBelongToPath = true;
101746             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
101747             var rootPaths;
101748             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
101749                 var sourceFile = sourceFiles_2[_i];
101750                 if (!sourceFile.isDeclarationFile) {
101751                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
101752                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
101753                         if (!rootPaths)
101754                             rootPaths = ts.arrayToSet(rootNames, toPath);
101755                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
101756                         allFilesBelongToPath = false;
101757                     }
101758                 }
101759             }
101760             return allFilesBelongToPath;
101761         }
101762         function parseProjectReferenceConfigFile(ref) {
101763             if (!projectReferenceRedirects) {
101764                 projectReferenceRedirects = ts.createMap();
101765             }
101766             // The actual filename (i.e. add "/tsconfig.json" if necessary)
101767             var refPath = resolveProjectReferencePath(ref);
101768             var sourceFilePath = toPath(refPath);
101769             var fromCache = projectReferenceRedirects.get(sourceFilePath);
101770             if (fromCache !== undefined) {
101771                 return fromCache || undefined;
101772             }
101773             var commandLine;
101774             var sourceFile;
101775             if (host.getParsedCommandLine) {
101776                 commandLine = host.getParsedCommandLine(refPath);
101777                 if (!commandLine) {
101778                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
101779                     projectReferenceRedirects.set(sourceFilePath, false);
101780                     return undefined;
101781                 }
101782                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
101783                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
101784                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101785             }
101786             else {
101787                 // An absolute path pointing to the containing directory of the config file
101788                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
101789                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
101790                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
101791                 if (sourceFile === undefined) {
101792                     projectReferenceRedirects.set(sourceFilePath, false);
101793                     return undefined;
101794                 }
101795                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
101796             }
101797             sourceFile.fileName = refPath;
101798             sourceFile.path = sourceFilePath;
101799             sourceFile.resolvedPath = sourceFilePath;
101800             sourceFile.originalFileName = refPath;
101801             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
101802             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
101803             if (commandLine.projectReferences) {
101804                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
101805             }
101806             return resolvedRef;
101807         }
101808         function verifyCompilerOptions() {
101809             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
101810                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
101811             }
101812             if (options.isolatedModules) {
101813                 if (options.out) {
101814                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
101815                 }
101816                 if (options.outFile) {
101817                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
101818                 }
101819             }
101820             if (options.inlineSourceMap) {
101821                 if (options.sourceMap) {
101822                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
101823                 }
101824                 if (options.mapRoot) {
101825                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
101826                 }
101827             }
101828             if (options.paths && options.baseUrl === undefined) {
101829                 createDiagnosticForOptionName(ts.Diagnostics.Option_paths_cannot_be_used_without_specifying_baseUrl_option, "paths");
101830             }
101831             if (options.composite) {
101832                 if (options.declaration === false) {
101833                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
101834                 }
101835                 if (options.incremental === false) {
101836                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
101837                 }
101838             }
101839             if (options.tsBuildInfoFile) {
101840                 if (!ts.isIncrementalCompilation(options)) {
101841                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
101842                 }
101843             }
101844             else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) {
101845                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
101846             }
101847             if (!options.listFilesOnly && options.noEmit && ts.isIncrementalCompilation(options)) {
101848                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
101849             }
101850             verifyProjectReferences();
101851             // List of collected files is complete; validate exhautiveness if this is a project with a file list
101852             if (options.composite) {
101853                 var rootPaths = ts.arrayToSet(rootNames, toPath);
101854                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
101855                     var file = files_3[_i];
101856                     // Ignore file that is not emitted
101857                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
101858                         addProgramDiagnosticAtRefPath(file, rootPaths, ts.Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, file.fileName, options.configFilePath || "");
101859                     }
101860                 }
101861             }
101862             if (options.paths) {
101863                 for (var key in options.paths) {
101864                     if (!ts.hasProperty(options.paths, key)) {
101865                         continue;
101866                     }
101867                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
101868                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
101869                     }
101870                     if (ts.isArray(options.paths[key])) {
101871                         var len = options.paths[key].length;
101872                         if (len === 0) {
101873                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
101874                         }
101875                         for (var i = 0; i < len; i++) {
101876                             var subst = options.paths[key][i];
101877                             var typeOfSubst = typeof subst;
101878                             if (typeOfSubst === "string") {
101879                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
101880                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
101881                                 }
101882                             }
101883                             else {
101884                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
101885                             }
101886                         }
101887                     }
101888                     else {
101889                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
101890                     }
101891                 }
101892             }
101893             if (!options.sourceMap && !options.inlineSourceMap) {
101894                 if (options.inlineSources) {
101895                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
101896                 }
101897                 if (options.sourceRoot) {
101898                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
101899                 }
101900             }
101901             if (options.out && options.outFile) {
101902                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
101903             }
101904             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
101905                 // Error to specify --mapRoot without --sourcemap
101906                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
101907             }
101908             if (options.declarationDir) {
101909                 if (!ts.getEmitDeclarations(options)) {
101910                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
101911                 }
101912                 if (options.out || options.outFile) {
101913                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
101914                 }
101915             }
101916             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
101917                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
101918             }
101919             if (options.lib && options.noLib) {
101920                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
101921             }
101922             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
101923                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
101924             }
101925             var languageVersion = options.target || 0 /* ES3 */;
101926             var outFile = options.outFile || options.out;
101927             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
101928             if (options.isolatedModules) {
101929                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
101930                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
101931                 }
101932                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
101933                 if (firstNonExternalModuleSourceFile) {
101934                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
101935                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.All_files_must_be_modules_when_the_isolatedModules_flag_is_provided));
101936                 }
101937             }
101938             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
101939                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
101940                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101941                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
101942             }
101943             // Cannot specify module gen that isn't amd or system with --out
101944             if (outFile && !options.emitDeclarationOnly) {
101945                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
101946                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
101947                 }
101948                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
101949                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
101950                     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"));
101951                 }
101952             }
101953             if (options.resolveJsonModule) {
101954                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
101955                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
101956                 }
101957                 // Any emit other than common js, amd, es2015 or esnext is error
101958                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
101959                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
101960                 }
101961             }
101962             // there has to be common source directory if user specified --outdir || --sourceRoot
101963             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
101964             if (options.outDir || // there is --outDir specified
101965                 options.sourceRoot || // there is --sourceRoot specified
101966                 options.mapRoot) { // there is --mapRoot specified
101967                 // Precalculate and cache the common source directory
101968                 var dir = getCommonSourceDirectory();
101969                 // 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
101970                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
101971                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
101972                 }
101973             }
101974             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
101975                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
101976             }
101977             if (options.checkJs && !options.allowJs) {
101978                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
101979             }
101980             if (options.emitDeclarationOnly) {
101981                 if (!ts.getEmitDeclarations(options)) {
101982                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
101983                 }
101984                 if (options.noEmit) {
101985                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
101986                 }
101987             }
101988             if (options.emitDecoratorMetadata &&
101989                 !options.experimentalDecorators) {
101990                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
101991             }
101992             if (options.jsxFactory) {
101993                 if (options.reactNamespace) {
101994                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
101995                 }
101996                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
101997                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
101998                 }
101999             }
102000             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
102001                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
102002             }
102003             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
102004             if (!options.noEmit && !options.suppressOutputPathCheck) {
102005                 var emitHost = getEmitHost();
102006                 var emitFilesSeen_1 = ts.createMap();
102007                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
102008                     if (!options.emitDeclarationOnly) {
102009                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
102010                     }
102011                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
102012                 });
102013             }
102014             // Verify that all the emit files are unique and don't overwrite input files
102015             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
102016                 if (emitFileName) {
102017                     var emitFilePath = toPath(emitFileName);
102018                     // Report error if the output overwrites input file
102019                     if (filesByName.has(emitFilePath)) {
102020                         var chain = void 0;
102021                         if (!options.configFilePath) {
102022                             // The program is from either an inferred project or an external project
102023                             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);
102024                         }
102025                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
102026                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
102027                     }
102028                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
102029                     // Report error if multiple files write into same file
102030                     if (emitFilesSeen.has(emitFileKey)) {
102031                         // Already seen the same emit file - report error
102032                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
102033                     }
102034                     else {
102035                         emitFilesSeen.set(emitFileKey, true);
102036                     }
102037                 }
102038             }
102039         }
102040         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
102041             var _a, _b;
102042             var args = [];
102043             for (var _i = 2; _i < arguments.length; _i++) {
102044                 args[_i - 2] = arguments[_i];
102045             }
102046             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
102047             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
102048             var pos, end;
102049             switch (kind) {
102050                 case ts.RefFileKind.Import:
102051                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
102052                     end = refFile.imports[index].end;
102053                     break;
102054                 case ts.RefFileKind.ReferenceFile:
102055                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
102056                     break;
102057                 case ts.RefFileKind.TypeReferenceDirective:
102058                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
102059                     break;
102060                 default:
102061                     return ts.Debug.assertNever(kind);
102062             }
102063             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
102064         }
102065         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
102066             var args = [];
102067             for (var _i = 3; _i < arguments.length; _i++) {
102068                 args[_i - 3] = arguments[_i];
102069             }
102070             var refPaths = refFileMap && refFileMap.get(file.path);
102071             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
102072                 ts.elementAt(refPaths, 0);
102073             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
102074         }
102075         function verifyProjectReferences() {
102076             var buildInfoPath = !options.noEmit && !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
102077             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, index, parent) {
102078                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
102079                 var parentFile = parent && parent.sourceFile;
102080                 if (!resolvedRef) {
102081                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
102082                     return;
102083                 }
102084                 var options = resolvedRef.commandLine.options;
102085                 if (!options.composite) {
102086                     // ok to not have composite if the current program is container only
102087                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
102088                     if (inputs.length) {
102089                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
102090                     }
102091                 }
102092                 if (ref.prepend) {
102093                     var out = options.outFile || options.out;
102094                     if (out) {
102095                         if (!host.fileExists(out)) {
102096                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
102097                         }
102098                     }
102099                     else {
102100                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
102101                     }
102102                 }
102103                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
102104                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
102105                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
102106                 }
102107             });
102108         }
102109         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
102110             var needCompilerDiagnostic = true;
102111             var pathsSyntax = getOptionPathsSyntax();
102112             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
102113                 var pathProp = pathsSyntax_1[_i];
102114                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
102115                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
102116                         var keyProps = _b[_a];
102117                         var initializer = keyProps.initializer;
102118                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
102119                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
102120                             needCompilerDiagnostic = false;
102121                         }
102122                     }
102123                 }
102124             }
102125             if (needCompilerDiagnostic) {
102126                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102127             }
102128         }
102129         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
102130             var needCompilerDiagnostic = true;
102131             var pathsSyntax = getOptionPathsSyntax();
102132             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
102133                 var pathProp = pathsSyntax_2[_i];
102134                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
102135                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
102136                     needCompilerDiagnostic = false;
102137                 }
102138             }
102139             if (needCompilerDiagnostic) {
102140                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
102141             }
102142         }
102143         function getOptionsSyntaxByName(name) {
102144             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102145             if (compilerOptionsObjectLiteralSyntax) {
102146                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
102147             }
102148             return undefined;
102149         }
102150         function getOptionPathsSyntax() {
102151             return getOptionsSyntaxByName("paths") || ts.emptyArray;
102152         }
102153         function createDiagnosticForOptionName(message, option1, option2, option3) {
102154             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
102155         }
102156         function createOptionValueDiagnostic(option1, message, arg0) {
102157             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
102158         }
102159         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
102160             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
102161             if (referencesSyntax && referencesSyntax.elements.length > index) {
102162                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
102163             }
102164             else {
102165                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
102166             }
102167         }
102168         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
102169             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
102170             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
102171                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
102172             if (needCompilerDiagnostic) {
102173                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
102174             }
102175         }
102176         function getCompilerOptionsObjectLiteralSyntax() {
102177             if (_compilerOptionsObjectLiteralSyntax === undefined) {
102178                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
102179                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
102180                 if (jsonObjectLiteral) {
102181                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
102182                         var prop = _a[_i];
102183                         if (ts.isObjectLiteralExpression(prop.initializer)) {
102184                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
102185                             break;
102186                         }
102187                     }
102188                 }
102189             }
102190             return _compilerOptionsObjectLiteralSyntax;
102191         }
102192         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
102193             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
102194             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
102195                 var prop = props_3[_i];
102196                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
102197             }
102198             return !!props.length;
102199         }
102200         function blockEmittingOfFile(emitFileName, diag) {
102201             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
102202             programDiagnostics.add(diag);
102203         }
102204         function isEmittedFile(file) {
102205             if (options.noEmit) {
102206                 return false;
102207             }
102208             // If this is source file, its not emitted file
102209             var filePath = toPath(file);
102210             if (getSourceFileByPath(filePath)) {
102211                 return false;
102212             }
102213             // If options have --outFile or --out just check that
102214             var out = options.outFile || options.out;
102215             if (out) {
102216                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
102217             }
102218             // If declarationDir is specified, return if its a file in that directory
102219             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
102220                 return true;
102221             }
102222             // If --outDir, check if file is in that directory
102223             if (options.outDir) {
102224                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
102225             }
102226             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
102227                 // Otherwise just check if sourceFile with the name exists
102228                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
102229                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
102230                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
102231             }
102232             return false;
102233         }
102234         function isSameFile(file1, file2) {
102235             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
102236         }
102237         function getProbableSymlinks() {
102238             if (host.getSymlinks) {
102239                 return host.getSymlinks();
102240             }
102241             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
102242         }
102243     }
102244     ts.createProgram = createProgram;
102245     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
102246         var mapOfDeclarationDirectories;
102247         var symlinkedDirectories;
102248         var symlinkedFiles;
102249         var originalFileExists = host.compilerHost.fileExists;
102250         var originalDirectoryExists = host.compilerHost.directoryExists;
102251         var originalGetDirectories = host.compilerHost.getDirectories;
102252         var originalRealpath = host.compilerHost.realpath;
102253         if (!host.useSourceOfProjectReferenceRedirect)
102254             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
102255         host.compilerHost.fileExists = fileExists;
102256         if (originalDirectoryExists) {
102257             // This implementation of directoryExists checks if the directory being requested is
102258             // directory of .d.ts file for the referenced Project.
102259             // If it is it returns true irrespective of whether that directory exists on host
102260             host.compilerHost.directoryExists = function (path) {
102261                 if (originalDirectoryExists.call(host.compilerHost, path)) {
102262                     handleDirectoryCouldBeSymlink(path);
102263                     return true;
102264                 }
102265                 if (!host.getResolvedProjectReferences())
102266                     return false;
102267                 if (!mapOfDeclarationDirectories) {
102268                     mapOfDeclarationDirectories = ts.createMap();
102269                     host.forEachResolvedProjectReference(function (ref) {
102270                         if (!ref)
102271                             return;
102272                         var out = ref.commandLine.options.outFile || ref.commandLine.options.out;
102273                         if (out) {
102274                             mapOfDeclarationDirectories.set(ts.getDirectoryPath(host.toPath(out)), true);
102275                         }
102276                         else {
102277                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
102278                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
102279                             if (declarationDir) {
102280                                 mapOfDeclarationDirectories.set(host.toPath(declarationDir), true);
102281                             }
102282                         }
102283                     });
102284                 }
102285                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
102286             };
102287         }
102288         if (originalGetDirectories) {
102289             // Call getDirectories only if directory actually present on the host
102290             // This is needed to ensure that we arent getting directories that we fake about presence for
102291             host.compilerHost.getDirectories = function (path) {
102292                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
102293                     originalGetDirectories.call(host.compilerHost, path) :
102294                     [];
102295             };
102296         }
102297         // This is something we keep for life time of the host
102298         if (originalRealpath) {
102299             host.compilerHost.realpath = function (s) {
102300                 return (symlinkedFiles === null || symlinkedFiles === void 0 ? void 0 : symlinkedFiles.get(host.toPath(s))) ||
102301                     originalRealpath.call(host.compilerHost, s);
102302             };
102303         }
102304         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists };
102305         function onProgramCreateComplete() {
102306             host.compilerHost.fileExists = originalFileExists;
102307             host.compilerHost.directoryExists = originalDirectoryExists;
102308             host.compilerHost.getDirectories = originalGetDirectories;
102309             // DO not revert realpath as it could be used later
102310         }
102311         // This implementation of fileExists checks if the file being requested is
102312         // .d.ts file for the referenced Project.
102313         // If it is it returns true irrespective of whether that file exists on host
102314         function fileExists(file) {
102315             if (originalFileExists.call(host.compilerHost, file))
102316                 return true;
102317             if (!host.getResolvedProjectReferences())
102318                 return false;
102319             if (!ts.isDeclarationFileName(file))
102320                 return false;
102321             // Project references go to source file instead of .d.ts file
102322             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
102323         }
102324         function fileExistsIfProjectReferenceDts(file) {
102325             var source = host.getSourceOfProjectReferenceRedirect(file);
102326             return source !== undefined ?
102327                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
102328                 undefined;
102329         }
102330         function directoryExistsIfProjectReferenceDeclDir(dir) {
102331             var dirPath = host.toPath(dir);
102332             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
102333             return ts.forEachKey(mapOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
102334                 // Any parent directory of declaration dir
102335                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
102336                 // Any directory inside declaration dir
102337                 ts.startsWith(dirPath, declDirPath + "/"); });
102338         }
102339         function handleDirectoryCouldBeSymlink(directory) {
102340             if (!host.getResolvedProjectReferences())
102341                 return;
102342             // Because we already watch node_modules, handle symlinks in there
102343             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
102344                 return;
102345             if (!symlinkedDirectories)
102346                 symlinkedDirectories = ts.createMap();
102347             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
102348             if (symlinkedDirectories.has(directoryPath))
102349                 return;
102350             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
102351             var realPath;
102352             if (real === directory ||
102353                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
102354                 // not symlinked
102355                 symlinkedDirectories.set(directoryPath, false);
102356                 return;
102357             }
102358             symlinkedDirectories.set(directoryPath, {
102359                 real: ts.ensureTrailingDirectorySeparator(real),
102360                 realPath: realPath
102361             });
102362         }
102363         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
102364             var fileOrDirectoryExistsUsingSource = isFile ?
102365                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
102366                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
102367             // Check current directory or file
102368             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
102369             if (result !== undefined)
102370                 return result;
102371             if (!symlinkedDirectories)
102372                 return false;
102373             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
102374             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
102375                 return false;
102376             if (isFile && symlinkedFiles && symlinkedFiles.has(fileOrDirectoryPath))
102377                 return true;
102378             // If it contains node_modules check if its one of the symlinked path we know of
102379             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
102380                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
102381                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
102382                     return undefined;
102383                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
102384                 if (isFile && result) {
102385                     if (!symlinkedFiles)
102386                         symlinkedFiles = ts.createMap();
102387                     // Store the real path for the file'
102388                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
102389                     symlinkedFiles.set(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
102390                 }
102391                 return result;
102392             }) || false;
102393         }
102394     }
102395     /*@internal*/
102396     function handleNoEmitOptions(program, sourceFile, cancellationToken) {
102397         var options = program.getCompilerOptions();
102398         if (options.noEmit) {
102399             return { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
102400         }
102401         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
102402         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
102403         // get any preEmit diagnostics, not just the ones
102404         if (!options.noEmitOnError)
102405             return undefined;
102406         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
102407         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
102408             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
102409         }
102410         return diagnostics.length > 0 ?
102411             { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true } :
102412             undefined;
102413     }
102414     ts.handleNoEmitOptions = handleNoEmitOptions;
102415     /* @internal */
102416     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
102417         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
102418         return {
102419             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
102420             readDirectory: function (root, extensions, excludes, includes, depth) {
102421                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
102422                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
102423             },
102424             readFile: function (f) { return directoryStructureHost.readFile(f); },
102425             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
102426             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
102427             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
102428             trace: host.trace ? function (s) { return host.trace(s); } : undefined
102429         };
102430     }
102431     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
102432     /* @internal */
102433     function createPrependNodes(projectReferences, getCommandLine, readFile) {
102434         if (!projectReferences)
102435             return ts.emptyArray;
102436         var nodes;
102437         for (var i = 0; i < projectReferences.length; i++) {
102438             var ref = projectReferences[i];
102439             var resolvedRefOpts = getCommandLine(ref, i);
102440             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
102441                 var out = resolvedRefOpts.options.outFile || resolvedRefOpts.options.out;
102442                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
102443                 if (!out)
102444                     continue;
102445                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
102446                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
102447                 (nodes || (nodes = [])).push(node);
102448             }
102449         }
102450         return nodes || ts.emptyArray;
102451     }
102452     ts.createPrependNodes = createPrependNodes;
102453     function resolveProjectReferencePath(hostOrRef, ref) {
102454         var passedInRef = ref ? ref : hostOrRef;
102455         return ts.resolveConfigFileProjectName(passedInRef.path);
102456     }
102457     ts.resolveProjectReferencePath = resolveProjectReferencePath;
102458     /* @internal */
102459     /**
102460      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
102461      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
102462      * This returns a diagnostic even if the module will be an untyped module.
102463      */
102464     function getResolutionDiagnostic(options, _a) {
102465         var extension = _a.extension;
102466         switch (extension) {
102467             case ".ts" /* Ts */:
102468             case ".d.ts" /* Dts */:
102469                 // These are always allowed.
102470                 return undefined;
102471             case ".tsx" /* Tsx */:
102472                 return needJsx();
102473             case ".jsx" /* Jsx */:
102474                 return needJsx() || needAllowJs();
102475             case ".js" /* Js */:
102476                 return needAllowJs();
102477             case ".json" /* Json */:
102478                 return needResolveJsonModule();
102479         }
102480         function needJsx() {
102481             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
102482         }
102483         function needAllowJs() {
102484             return options.allowJs || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
102485         }
102486         function needResolveJsonModule() {
102487             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
102488         }
102489     }
102490     ts.getResolutionDiagnostic = getResolutionDiagnostic;
102491     function getModuleNames(_a) {
102492         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
102493         var res = imports.map(function (i) { return i.text; });
102494         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
102495             var aug = moduleAugmentations_1[_i];
102496             if (aug.kind === 10 /* StringLiteral */) {
102497                 res.push(aug.text);
102498             }
102499             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
102500         }
102501         return res;
102502     }
102503 })(ts || (ts = {}));
102504 /*@internal*/
102505 var ts;
102506 (function (ts) {
102507     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
102508         var outputFiles = [];
102509         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
102510         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
102511         function writeFile(fileName, text, writeByteOrderMark) {
102512             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
102513         }
102514     }
102515     ts.getFileEmitOutput = getFileEmitOutput;
102516     var BuilderState;
102517     (function (BuilderState) {
102518         /**
102519          * Get the referencedFile from the imported module symbol
102520          */
102521         function getReferencedFileFromImportedModuleSymbol(symbol) {
102522             if (symbol.declarations && symbol.declarations[0]) {
102523                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
102524                 return declarationSourceFile && declarationSourceFile.resolvedPath;
102525             }
102526         }
102527         /**
102528          * Get the referencedFile from the import name node from file
102529          */
102530         function getReferencedFileFromImportLiteral(checker, importName) {
102531             var symbol = checker.getSymbolAtLocation(importName);
102532             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
102533         }
102534         /**
102535          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
102536          */
102537         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
102538             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
102539         }
102540         /**
102541          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
102542          */
102543         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
102544             var referencedFiles;
102545             // We need to use a set here since the code can contain the same import twice,
102546             // but that will only be one dependency.
102547             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
102548             if (sourceFile.imports && sourceFile.imports.length > 0) {
102549                 var checker = program.getTypeChecker();
102550                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
102551                     var importName = _a[_i];
102552                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
102553                     if (declarationSourceFilePath) {
102554                         addReferencedFile(declarationSourceFilePath);
102555                     }
102556                 }
102557             }
102558             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
102559             // Handle triple slash references
102560             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
102561                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
102562                     var referencedFile = _c[_b];
102563                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
102564                     addReferencedFile(referencedPath);
102565                 }
102566             }
102567             // Handle type reference directives
102568             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
102569                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
102570                     if (!resolvedTypeReferenceDirective) {
102571                         return;
102572                     }
102573                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
102574                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
102575                     addReferencedFile(typeFilePath);
102576                 });
102577             }
102578             // Add module augmentation as references
102579             if (sourceFile.moduleAugmentations.length) {
102580                 var checker = program.getTypeChecker();
102581                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
102582                     var moduleName = _e[_d];
102583                     if (!ts.isStringLiteral(moduleName)) {
102584                         continue;
102585                     }
102586                     var symbol = checker.getSymbolAtLocation(moduleName);
102587                     if (!symbol) {
102588                         continue;
102589                     }
102590                     // Add any file other than our own as reference
102591                     addReferenceFromAmbientModule(symbol);
102592                 }
102593             }
102594             // From ambient modules
102595             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
102596                 var ambientModule = _g[_f];
102597                 if (ambientModule.declarations.length > 1) {
102598                     addReferenceFromAmbientModule(ambientModule);
102599                 }
102600             }
102601             return referencedFiles;
102602             function addReferenceFromAmbientModule(symbol) {
102603                 // Add any file other than our own as reference
102604                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
102605                     var declaration = _a[_i];
102606                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
102607                     if (declarationSourceFile &&
102608                         declarationSourceFile !== sourceFile) {
102609                         addReferencedFile(declarationSourceFile.resolvedPath);
102610                     }
102611                 }
102612             }
102613             function addReferencedFile(referencedPath) {
102614                 if (!referencedFiles) {
102615                     referencedFiles = ts.createMap();
102616                 }
102617                 referencedFiles.set(referencedPath, true);
102618             }
102619         }
102620         /**
102621          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
102622          */
102623         function canReuseOldState(newReferencedMap, oldState) {
102624             return oldState && !oldState.referencedMap === !newReferencedMap;
102625         }
102626         BuilderState.canReuseOldState = canReuseOldState;
102627         /**
102628          * Creates the state of file references and signature for the new program from oldState if it is safe
102629          */
102630         function create(newProgram, getCanonicalFileName, oldState) {
102631             var fileInfos = ts.createMap();
102632             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined;
102633             var exportedModulesMap = referencedMap ? ts.createMap() : undefined;
102634             var hasCalledUpdateShapeSignature = ts.createMap();
102635             var useOldState = canReuseOldState(referencedMap, oldState);
102636             // Create the reference map, and set the file infos
102637             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
102638                 var sourceFile = _a[_i];
102639                 var version_1 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
102640                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
102641                 if (referencedMap) {
102642                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
102643                     if (newReferences) {
102644                         referencedMap.set(sourceFile.resolvedPath, newReferences);
102645                     }
102646                     // Copy old visible to outside files map
102647                     if (useOldState) {
102648                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
102649                         if (exportedModules) {
102650                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
102651                         }
102652                     }
102653                 }
102654                 fileInfos.set(sourceFile.resolvedPath, { version: version_1, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
102655             }
102656             return {
102657                 fileInfos: fileInfos,
102658                 referencedMap: referencedMap,
102659                 exportedModulesMap: exportedModulesMap,
102660                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
102661             };
102662         }
102663         BuilderState.create = create;
102664         /**
102665          * Releases needed properties
102666          */
102667         function releaseCache(state) {
102668             state.allFilesExcludingDefaultLibraryFile = undefined;
102669             state.allFileNames = undefined;
102670         }
102671         BuilderState.releaseCache = releaseCache;
102672         /**
102673          * Creates a clone of the state
102674          */
102675         function clone(state) {
102676             var fileInfos = ts.createMap();
102677             state.fileInfos.forEach(function (value, key) {
102678                 fileInfos.set(key, __assign({}, value));
102679             });
102680             // Dont need to backup allFiles info since its cache anyway
102681             return {
102682                 fileInfos: fileInfos,
102683                 referencedMap: cloneMapOrUndefined(state.referencedMap),
102684                 exportedModulesMap: cloneMapOrUndefined(state.exportedModulesMap),
102685                 hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature),
102686             };
102687         }
102688         BuilderState.clone = clone;
102689         /**
102690          * Gets the files affected by the path from the program
102691          */
102692         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
102693             // Since the operation could be cancelled, the signatures are always stored in the cache
102694             // They will be committed once it is safe to use them
102695             // eg when calling this api from tsserver, if there is no cancellation of the operation
102696             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
102697             var signatureCache = cacheToUpdateSignature || ts.createMap();
102698             var sourceFile = programOfThisState.getSourceFileByPath(path);
102699             if (!sourceFile) {
102700                 return ts.emptyArray;
102701             }
102702             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
102703                 return [sourceFile];
102704             }
102705             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
102706             if (!cacheToUpdateSignature) {
102707                 // Commit all the signatures in the signature cache
102708                 updateSignaturesFromCache(state, signatureCache);
102709             }
102710             return result;
102711         }
102712         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
102713         /**
102714          * Updates the signatures from the cache into state's fileinfo signatures
102715          * This should be called whenever it is safe to commit the state of the builder
102716          */
102717         function updateSignaturesFromCache(state, signatureCache) {
102718             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
102719         }
102720         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
102721         function updateSignatureOfFile(state, signature, path) {
102722             state.fileInfos.get(path).signature = signature;
102723             state.hasCalledUpdateShapeSignature.set(path, true);
102724         }
102725         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
102726         /**
102727          * Returns if the shape of the signature has changed since last emit
102728          */
102729         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102730             ts.Debug.assert(!!sourceFile);
102731             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
102732             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
102733             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
102734                 return false;
102735             }
102736             var info = state.fileInfos.get(sourceFile.resolvedPath);
102737             if (!info)
102738                 return ts.Debug.fail();
102739             var prevSignature = info.signature;
102740             var latestSignature;
102741             if (sourceFile.isDeclarationFile) {
102742                 latestSignature = sourceFile.version;
102743                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
102744                     // All the references in this file are exported
102745                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
102746                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
102747                 }
102748             }
102749             else {
102750                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
102751                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
102752                 /*customTransformers*/ undefined, 
102753                 /*forceDtsEmit*/ true);
102754                 var firstDts_1 = emitOutput_1.outputFiles &&
102755                     programOfThisState.getCompilerOptions().declarationMap ?
102756                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
102757                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
102758                 if (firstDts_1) {
102759                     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; })); });
102760                     latestSignature = computeHash(firstDts_1.text);
102761                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
102762                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
102763                     }
102764                 }
102765                 else {
102766                     latestSignature = prevSignature; // TODO: GH#18217
102767                 }
102768             }
102769             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
102770             return !prevSignature || latestSignature !== prevSignature;
102771         }
102772         BuilderState.updateShapeSignature = updateShapeSignature;
102773         /**
102774          * Coverts the declaration emit result into exported modules map
102775          */
102776         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
102777             if (!exportedModulesFromDeclarationEmit) {
102778                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
102779                 return;
102780             }
102781             var exportedModules;
102782             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
102783             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
102784             function addExportedModule(exportedModulePath) {
102785                 if (exportedModulePath) {
102786                     if (!exportedModules) {
102787                         exportedModules = ts.createMap();
102788                     }
102789                     exportedModules.set(exportedModulePath, true);
102790                 }
102791             }
102792         }
102793         /**
102794          * Updates the exported modules from cache into state's exported modules map
102795          * This should be called whenever it is safe to commit the state of the builder
102796          */
102797         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
102798             if (exportedModulesMapCache) {
102799                 ts.Debug.assert(!!state.exportedModulesMap);
102800                 exportedModulesMapCache.forEach(function (exportedModules, path) {
102801                     if (exportedModules) {
102802                         state.exportedModulesMap.set(path, exportedModules);
102803                     }
102804                     else {
102805                         state.exportedModulesMap.delete(path);
102806                     }
102807                 });
102808             }
102809         }
102810         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
102811         /**
102812          * Get all the dependencies of the sourceFile
102813          */
102814         function getAllDependencies(state, programOfThisState, sourceFile) {
102815             var compilerOptions = programOfThisState.getCompilerOptions();
102816             // With --out or --outFile all outputs go into single file, all files depend on each other
102817             if (compilerOptions.outFile || compilerOptions.out) {
102818                 return getAllFileNames(state, programOfThisState);
102819             }
102820             // If this is non module emit, or its a global file, it depends on all the source files
102821             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
102822                 return getAllFileNames(state, programOfThisState);
102823             }
102824             // Get the references, traversing deep from the referenceMap
102825             var seenMap = ts.createMap();
102826             var queue = [sourceFile.resolvedPath];
102827             while (queue.length) {
102828                 var path = queue.pop();
102829                 if (!seenMap.has(path)) {
102830                     seenMap.set(path, true);
102831                     var references = state.referencedMap.get(path);
102832                     if (references) {
102833                         var iterator = references.keys();
102834                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
102835                             queue.push(iterResult.value);
102836                         }
102837                     }
102838                 }
102839             }
102840             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) {
102841                 var file = programOfThisState.getSourceFileByPath(path);
102842                 return file ? file.fileName : path;
102843             }));
102844         }
102845         BuilderState.getAllDependencies = getAllDependencies;
102846         /**
102847          * Gets the names of all files from the program
102848          */
102849         function getAllFileNames(state, programOfThisState) {
102850             if (!state.allFileNames) {
102851                 var sourceFiles = programOfThisState.getSourceFiles();
102852                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
102853             }
102854             return state.allFileNames;
102855         }
102856         /**
102857          * Gets the files referenced by the the file path
102858          */
102859         function getReferencedByPaths(state, referencedFilePath) {
102860             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
102861                 var filePath = _a[0], referencesInFile = _a[1];
102862                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
102863             }));
102864         }
102865         BuilderState.getReferencedByPaths = getReferencedByPaths;
102866         /**
102867          * For script files that contains only ambient external modules, although they are not actually external module files,
102868          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
102869          * there are no point to rebuild all script files if these special files have changed. However, if any statement
102870          * in the file is not ambient external module, we treat it as a regular script file.
102871          */
102872         function containsOnlyAmbientModules(sourceFile) {
102873             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
102874                 var statement = _a[_i];
102875                 if (!ts.isModuleWithStringLiteralName(statement)) {
102876                     return false;
102877                 }
102878             }
102879             return true;
102880         }
102881         /**
102882          * Return true if file contains anything that augments to global scope we need to build them as if
102883          * they are global files as well as module
102884          */
102885         function containsGlobalScopeAugmentation(sourceFile) {
102886             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
102887         }
102888         /**
102889          * Return true if the file will invalidate all files because it affectes global scope
102890          */
102891         function isFileAffectingGlobalScope(sourceFile) {
102892             return containsGlobalScopeAugmentation(sourceFile) ||
102893                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
102894         }
102895         /**
102896          * Gets all files of the program excluding the default library file
102897          */
102898         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
102899             // Use cached result
102900             if (state.allFilesExcludingDefaultLibraryFile) {
102901                 return state.allFilesExcludingDefaultLibraryFile;
102902             }
102903             var result;
102904             if (firstSourceFile)
102905                 addSourceFile(firstSourceFile);
102906             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
102907                 var sourceFile = _a[_i];
102908                 if (sourceFile !== firstSourceFile) {
102909                     addSourceFile(sourceFile);
102910                 }
102911             }
102912             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
102913             return state.allFilesExcludingDefaultLibraryFile;
102914             function addSourceFile(sourceFile) {
102915                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
102916                     (result || (result = [])).push(sourceFile);
102917                 }
102918             }
102919         }
102920         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
102921         /**
102922          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
102923          */
102924         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
102925             var compilerOptions = programOfThisState.getCompilerOptions();
102926             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
102927             // so returning the file itself is good enough.
102928             if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) {
102929                 return [sourceFileWithUpdatedShape];
102930             }
102931             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102932         }
102933         /**
102934          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
102935          */
102936         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
102937             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
102938                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
102939             }
102940             var compilerOptions = programOfThisState.getCompilerOptions();
102941             if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) {
102942                 return [sourceFileWithUpdatedShape];
102943             }
102944             // Now we need to if each file in the referencedBy list has a shape change as well.
102945             // Because if so, its own referencedBy files need to be saved as well to make the
102946             // emitting result consistent with files on disk.
102947             var seenFileNamesMap = ts.createMap();
102948             // Start with the paths this file was referenced by
102949             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
102950             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
102951             while (queue.length > 0) {
102952                 var currentPath = queue.pop();
102953                 if (!seenFileNamesMap.has(currentPath)) {
102954                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
102955                     seenFileNamesMap.set(currentPath, currentSourceFile);
102956                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217
102957                         queue.push.apply(// TODO: GH#18217
102958                         queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
102959                     }
102960                 }
102961             }
102962             // Return array of values that needs emit
102963             // Return array of values that needs emit
102964             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
102965         }
102966     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
102967     function cloneMapOrUndefined(map) {
102968         return map ? ts.cloneMap(map) : undefined;
102969     }
102970     ts.cloneMapOrUndefined = cloneMapOrUndefined;
102971 })(ts || (ts = {}));
102972 /*@internal*/
102973 var ts;
102974 (function (ts) {
102975     var BuilderFileEmit;
102976     (function (BuilderFileEmit) {
102977         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
102978         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
102979     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
102980     function hasSameKeys(map1, map2) {
102981         // Has same size and every key is present in both maps
102982         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
102983     }
102984     /**
102985      * Create the state so that we can iterate on changedFiles/affected files
102986      */
102987     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
102988         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
102989         state.program = newProgram;
102990         var compilerOptions = newProgram.getCompilerOptions();
102991         state.compilerOptions = compilerOptions;
102992         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
102993         if (!compilerOptions.outFile && !compilerOptions.out) {
102994             state.semanticDiagnosticsPerFile = ts.createMap();
102995         }
102996         state.changedFilesSet = ts.createMap();
102997         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
102998         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
102999         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
103000             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
103001         if (useOldState) {
103002             // Verify the sanity of old state
103003             if (!oldState.currentChangedFilePath) {
103004                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
103005                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
103006             }
103007             var changedFilesSet = oldState.changedFilesSet;
103008             if (canCopySemanticDiagnostics) {
103009                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
103010             }
103011             // Copy old state's changed files set
103012             if (changedFilesSet) {
103013                 ts.copyEntries(changedFilesSet, state.changedFilesSet);
103014             }
103015             if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) {
103016                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
103017                 state.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(oldState.affectedFilesPendingEmitKind);
103018                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
103019                 state.seenAffectedFiles = ts.createMap();
103020             }
103021         }
103022         // Update changed files and copy semantic diagnostics if we can
103023         var referencedMap = state.referencedMap;
103024         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
103025         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
103026         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
103027         state.fileInfos.forEach(function (info, sourceFilePath) {
103028             var oldInfo;
103029             var newReferences;
103030             // if not using old state, every file is changed
103031             if (!useOldState ||
103032                 // File wasnt present in old state
103033                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
103034                 // versions dont match
103035                 oldInfo.version !== info.version ||
103036                 // Referenced files changed
103037                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
103038                 // Referenced file was deleted in the new program
103039                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
103040                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
103041                 state.changedFilesSet.set(sourceFilePath, true);
103042             }
103043             else if (canCopySemanticDiagnostics) {
103044                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
103045                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
103046                     return;
103047                 }
103048                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
103049                     return;
103050                 }
103051                 // Unchanged file copy diagnostics
103052                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
103053                 if (diagnostics) {
103054                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
103055                     if (!state.semanticDiagnosticsFromOldState) {
103056                         state.semanticDiagnosticsFromOldState = ts.createMap();
103057                     }
103058                     state.semanticDiagnosticsFromOldState.set(sourceFilePath, true);
103059                 }
103060             }
103061         });
103062         // If the global file is removed, add all files as changed
103063         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
103064             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
103065                 .forEach(function (file) { return state.changedFilesSet.set(file.resolvedPath, true); });
103066         }
103067         else if (oldCompilerOptions && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
103068             // Add all files to affectedFilesPendingEmit since emit changed
103069             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
103070             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
103071             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103072         }
103073         state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
103074         return state;
103075     }
103076     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
103077         if (!diagnostics.length)
103078             return ts.emptyArray;
103079         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
103080         return diagnostics.map(function (diagnostic) {
103081             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
103082             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103083             result.source = diagnostic.source;
103084             var relatedInformation = diagnostic.relatedInformation;
103085             result.relatedInformation = relatedInformation ?
103086                 relatedInformation.length ?
103087                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
103088                     ts.emptyArray :
103089                 undefined;
103090             return result;
103091         });
103092         function toPath(path) {
103093             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103094         }
103095     }
103096     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
103097         var file = diagnostic.file;
103098         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
103099     }
103100     /**
103101      * Releases program and other related not needed properties
103102      */
103103     function releaseCache(state) {
103104         ts.BuilderState.releaseCache(state);
103105         state.program = undefined;
103106     }
103107     /**
103108      * Creates a clone of the state
103109      */
103110     function cloneBuilderProgramState(state) {
103111         var newState = ts.BuilderState.clone(state);
103112         newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile);
103113         newState.changedFilesSet = ts.cloneMap(state.changedFilesSet);
103114         newState.affectedFiles = state.affectedFiles;
103115         newState.affectedFilesIndex = state.affectedFilesIndex;
103116         newState.currentChangedFilePath = state.currentChangedFilePath;
103117         newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures);
103118         newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap);
103119         newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles);
103120         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
103121         newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState);
103122         newState.program = state.program;
103123         newState.compilerOptions = state.compilerOptions;
103124         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
103125         newState.affectedFilesPendingEmitKind = ts.cloneMapOrUndefined(state.affectedFilesPendingEmitKind);
103126         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
103127         newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles);
103128         newState.programEmitComplete = state.programEmitComplete;
103129         return newState;
103130     }
103131     /**
103132      * Verifies that source file is ok to be used in calls that arent handled by next
103133      */
103134     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
103135         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
103136     }
103137     /**
103138      * This function returns the next affected file to be processed.
103139      * Note that until doneAffected is called it would keep reporting same result
103140      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
103141      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
103142      */
103143     function getNextAffectedFile(state, cancellationToken, computeHash) {
103144         while (true) {
103145             var affectedFiles = state.affectedFiles;
103146             if (affectedFiles) {
103147                 var seenAffectedFiles = state.seenAffectedFiles;
103148                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
103149                 while (affectedFilesIndex < affectedFiles.length) {
103150                     var affectedFile = affectedFiles[affectedFilesIndex];
103151                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
103152                         // Set the next affected file as seen and remove the cached semantic diagnostics
103153                         state.affectedFilesIndex = affectedFilesIndex;
103154                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
103155                         return affectedFile;
103156                     }
103157                     affectedFilesIndex++;
103158                 }
103159                 // Remove the changed file from the change set
103160                 state.changedFilesSet.delete(state.currentChangedFilePath);
103161                 state.currentChangedFilePath = undefined;
103162                 // Commit the changes in file signature
103163                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
103164                 state.currentAffectedFilesSignatures.clear();
103165                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
103166                 state.affectedFiles = undefined;
103167             }
103168             // Get next changed file
103169             var nextKey = state.changedFilesSet.keys().next();
103170             if (nextKey.done) {
103171                 // Done
103172                 return undefined;
103173             }
103174             // With --out or --outFile all outputs go into single file
103175             // so operations are performed directly on program, return program
103176             var program = ts.Debug.checkDefined(state.program);
103177             var compilerOptions = program.getCompilerOptions();
103178             if (compilerOptions.outFile || compilerOptions.out) {
103179                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103180                 return program;
103181             }
103182             // Get next batch of affected files
103183             state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap();
103184             if (state.exportedModulesMap) {
103185                 state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap();
103186             }
103187             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
103188             state.currentChangedFilePath = nextKey.value;
103189             state.affectedFilesIndex = 0;
103190             state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap();
103191         }
103192     }
103193     /**
103194      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
103195      */
103196     function getNextAffectedFilePendingEmit(state) {
103197         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
103198         if (affectedFilesPendingEmit) {
103199             var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap());
103200             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
103201                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
103202                 if (affectedFile) {
103203                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
103204                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
103205                     if (seenKind === undefined || seenKind < emitKind) {
103206                         // emit this file
103207                         state.affectedFilesPendingEmitIndex = i;
103208                         return { affectedFile: affectedFile, emitKind: emitKind };
103209                     }
103210                 }
103211             }
103212             state.affectedFilesPendingEmit = undefined;
103213             state.affectedFilesPendingEmitKind = undefined;
103214             state.affectedFilesPendingEmitIndex = undefined;
103215         }
103216         return undefined;
103217     }
103218     /**
103219      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
103220      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
103221      */
103222     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
103223         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
103224         // If affected files is everything except default library, then nothing more to do
103225         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
103226             if (!state.cleanedDiagnosticsOfLibFiles) {
103227                 state.cleanedDiagnosticsOfLibFiles = true;
103228                 var program_1 = ts.Debug.checkDefined(state.program);
103229                 var options_2 = program_1.getCompilerOptions();
103230                 ts.forEach(program_1.getSourceFiles(), function (f) {
103231                     return program_1.isSourceFileDefaultLibrary(f) &&
103232                         !ts.skipTypeChecking(f, options_2, program_1) &&
103233                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
103234                 });
103235             }
103236             return;
103237         }
103238         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
103239             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
103240         }
103241     }
103242     /**
103243      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
103244      * Also we need to make sure signature is updated for these files
103245      */
103246     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
103247         removeSemanticDiagnosticsOf(state, path);
103248         if (!state.changedFilesSet.has(path)) {
103249             var program = ts.Debug.checkDefined(state.program);
103250             var sourceFile = program.getSourceFileByPath(path);
103251             if (sourceFile) {
103252                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
103253                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
103254                 // This ensures that we dont later during incremental builds considering wrong signature.
103255                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
103256                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
103257                 // If not dts emit, nothing more to do
103258                 if (ts.getEmitDeclarations(state.compilerOptions)) {
103259                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
103260                 }
103261             }
103262         }
103263         return false;
103264     }
103265     /**
103266      * Removes semantic diagnostics for path and
103267      * returns true if there are no more semantic diagnostics from the old state
103268      */
103269     function removeSemanticDiagnosticsOf(state, path) {
103270         if (!state.semanticDiagnosticsFromOldState) {
103271             return true;
103272         }
103273         state.semanticDiagnosticsFromOldState.delete(path);
103274         state.semanticDiagnosticsPerFile.delete(path);
103275         return !state.semanticDiagnosticsFromOldState.size;
103276     }
103277     function isChangedSignagure(state, path) {
103278         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
103279         var oldSignagure = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
103280         return newSignature !== oldSignagure;
103281     }
103282     /**
103283      * Iterate on referencing modules that export entities from affected file
103284      */
103285     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
103286         // If there was change in signature (dts output) for the changed file,
103287         // then only we need to handle pending file emit
103288         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
103289             return;
103290         }
103291         if (!isChangedSignagure(state, affectedFile.resolvedPath))
103292             return;
103293         // Since isolated modules dont change js files, files affected by change in signature is itself
103294         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
103295         if (state.compilerOptions.isolatedModules) {
103296             var seenFileNamesMap = ts.createMap();
103297             seenFileNamesMap.set(affectedFile.resolvedPath, true);
103298             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
103299             while (queue.length > 0) {
103300                 var currentPath = queue.pop();
103301                 if (!seenFileNamesMap.has(currentPath)) {
103302                     seenFileNamesMap.set(currentPath, true);
103303                     var result = fn(state, currentPath);
103304                     if (result && isChangedSignagure(state, currentPath)) {
103305                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
103306                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
103307                     }
103308                 }
103309             }
103310         }
103311         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103312         var seenFileAndExportsOfFile = ts.createMap();
103313         // Go through exported modules from cache first
103314         // If exported modules has path, all files referencing file exported from are affected
103315         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103316             return exportedModules &&
103317                 exportedModules.has(affectedFile.resolvedPath) &&
103318                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103319         })) {
103320             return;
103321         }
103322         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103323         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103324             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103325                 exportedModules.has(affectedFile.resolvedPath) &&
103326                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103327         });
103328     }
103329     /**
103330      * Iterate on files referencing referencedPath
103331      */
103332     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
103333         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
103334             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
103335         });
103336     }
103337     /**
103338      * fn on file and iterate on anything that exports this file
103339      */
103340     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
103341         if (!ts.addToSeen(seenFileAndExportsOfFile, filePath)) {
103342             return false;
103343         }
103344         if (fn(state, filePath)) {
103345             // If there are no more diagnostics from old cache, done
103346             return true;
103347         }
103348         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
103349         // Go through exported modules from cache first
103350         // If exported modules has path, all files referencing file exported from are affected
103351         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
103352             return exportedModules &&
103353                 exportedModules.has(filePath) &&
103354                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103355         })) {
103356             return true;
103357         }
103358         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
103359         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
103360             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
103361                 exportedModules.has(filePath) &&
103362                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
103363         })) {
103364             return true;
103365         }
103366         // Remove diagnostics of files that import this file (without going to exports of referencing files)
103367         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
103368             return referencesInFile.has(filePath) &&
103369                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
103370                 fn(state, referencingFilePath);
103371         } // Dont add to seen since this is not yet done with the export removal
103372         );
103373     }
103374     /**
103375      * This is called after completing operation on the next affected file.
103376      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
103377      */
103378     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103379         if (isBuildInfoEmit) {
103380             state.emittedBuildInfo = true;
103381         }
103382         else if (affected === state.program) {
103383             state.changedFilesSet.clear();
103384             state.programEmitComplete = true;
103385         }
103386         else {
103387             state.seenAffectedFiles.set(affected.resolvedPath, true);
103388             if (emitKind !== undefined) {
103389                 (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.resolvedPath, emitKind);
103390             }
103391             if (isPendingEmit) {
103392                 state.affectedFilesPendingEmitIndex++;
103393             }
103394             else {
103395                 state.affectedFilesIndex++;
103396             }
103397         }
103398     }
103399     /**
103400      * Returns the result with affected file
103401      */
103402     function toAffectedFileResult(state, result, affected) {
103403         doneWithAffectedFile(state, affected);
103404         return { result: result, affected: affected };
103405     }
103406     /**
103407      * Returns the result with affected file
103408      */
103409     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
103410         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
103411         return { result: result, affected: affected };
103412     }
103413     /**
103414      * Gets semantic diagnostics for the file which are
103415      * bindAndCheckDiagnostics (from cache) and program diagnostics
103416      */
103417     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103418         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
103419     }
103420     /**
103421      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
103422      * 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
103423      */
103424     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
103425         var path = sourceFile.resolvedPath;
103426         if (state.semanticDiagnosticsPerFile) {
103427             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
103428             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
103429             if (cachedDiagnostics) {
103430                 return cachedDiagnostics;
103431             }
103432         }
103433         // Diagnostics werent cached, get them from program, and cache the result
103434         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
103435         if (state.semanticDiagnosticsPerFile) {
103436             state.semanticDiagnosticsPerFile.set(path, diagnostics);
103437         }
103438         return diagnostics;
103439     }
103440     /**
103441      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
103442      */
103443     function getProgramBuildInfo(state, getCanonicalFileName) {
103444         if (state.compilerOptions.outFile || state.compilerOptions.out)
103445             return undefined;
103446         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
103447         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
103448         var fileInfos = {};
103449         state.fileInfos.forEach(function (value, key) {
103450             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
103451             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
103452         });
103453         var result = {
103454             fileInfos: fileInfos,
103455             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
103456         };
103457         if (state.referencedMap) {
103458             var referencedMap = {};
103459             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
103460                 var key = _a[_i];
103461                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103462             }
103463             result.referencedMap = referencedMap;
103464         }
103465         if (state.exportedModulesMap) {
103466             var exportedModulesMap = {};
103467             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
103468                 var key = _c[_b];
103469                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
103470                 // Not in temporary cache, use existing value
103471                 if (newValue === undefined)
103472                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103473                 // Value in cache and has updated value map, use that
103474                 else if (newValue)
103475                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
103476             }
103477             result.exportedModulesMap = exportedModulesMap;
103478         }
103479         if (state.semanticDiagnosticsPerFile) {
103480             var semanticDiagnosticsPerFile = [];
103481             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
103482                 var key = _e[_d];
103483                 var value = state.semanticDiagnosticsPerFile.get(key);
103484                 semanticDiagnosticsPerFile.push(value.length ?
103485                     [
103486                         relativeToBuildInfo(key),
103487                         state.hasReusableDiagnostic ?
103488                             value :
103489                             convertToReusableDiagnostics(value, relativeToBuildInfo)
103490                     ] :
103491                     relativeToBuildInfo(key));
103492             }
103493             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
103494         }
103495         return result;
103496         function relativeToBuildInfoEnsuringAbsolutePath(path) {
103497             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
103498         }
103499         function relativeToBuildInfo(path) {
103500             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
103501         }
103502     }
103503     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
103504         var result = {};
103505         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
103506         for (var name in options) {
103507             if (ts.hasProperty(options, name)) {
103508                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
103509             }
103510         }
103511         if (result.configFilePath) {
103512             result.configFilePath = relativeToBuildInfo(result.configFilePath);
103513         }
103514         return result;
103515     }
103516     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
103517         if (option) {
103518             if (option.type === "list") {
103519                 var values = value;
103520                 if (option.element.isFilePath && values.length) {
103521                     return values.map(relativeToBuildInfo);
103522                 }
103523             }
103524             else if (option.isFilePath) {
103525                 return relativeToBuildInfo(value);
103526             }
103527         }
103528         return value;
103529     }
103530     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
103531         ts.Debug.assert(!!diagnostics.length);
103532         return diagnostics.map(function (diagnostic) {
103533             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
103534             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
103535             result.source = diagnostic.source;
103536             var relatedInformation = diagnostic.relatedInformation;
103537             result.relatedInformation = relatedInformation ?
103538                 relatedInformation.length ?
103539                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
103540                     ts.emptyArray :
103541                 undefined;
103542             return result;
103543         });
103544     }
103545     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
103546         var file = diagnostic.file;
103547         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
103548     }
103549     var BuilderProgramKind;
103550     (function (BuilderProgramKind) {
103551         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
103552         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
103553     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
103554     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103555         var host;
103556         var newProgram;
103557         var oldProgram;
103558         if (newProgramOrRootNames === undefined) {
103559             ts.Debug.assert(hostOrOptions === undefined);
103560             host = oldProgramOrHost;
103561             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103562             ts.Debug.assert(!!oldProgram);
103563             newProgram = oldProgram.getProgram();
103564         }
103565         else if (ts.isArray(newProgramOrRootNames)) {
103566             oldProgram = configFileParsingDiagnosticsOrOldProgram;
103567             newProgram = ts.createProgram({
103568                 rootNames: newProgramOrRootNames,
103569                 options: hostOrOptions,
103570                 host: oldProgramOrHost,
103571                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
103572                 configFileParsingDiagnostics: configFileParsingDiagnostics,
103573                 projectReferences: projectReferences
103574             });
103575             host = oldProgramOrHost;
103576         }
103577         else {
103578             newProgram = newProgramOrRootNames;
103579             host = hostOrOptions;
103580             oldProgram = oldProgramOrHost;
103581             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
103582         }
103583         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
103584     }
103585     ts.getBuilderCreationParameters = getBuilderCreationParameters;
103586     function createBuilderProgram(kind, _a) {
103587         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103588         // Return same program if underlying program doesnt change
103589         var oldState = oldProgram && oldProgram.getState();
103590         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
103591             newProgram = undefined; // TODO: GH#18217
103592             oldState = undefined;
103593             return oldProgram;
103594         }
103595         /**
103596          * Create the canonical file name for identity
103597          */
103598         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103599         /**
103600          * Computing hash to for signature verification
103601          */
103602         var computeHash = host.createHash || ts.generateDjb2Hash;
103603         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
103604         var backupState;
103605         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
103606         // To ensure that we arent storing any references to old program or new program without state
103607         newProgram = undefined; // TODO: GH#18217
103608         oldProgram = undefined;
103609         oldState = undefined;
103610         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
103611         builderProgram.getState = function () { return state; };
103612         builderProgram.backupState = function () {
103613             ts.Debug.assert(backupState === undefined);
103614             backupState = cloneBuilderProgramState(state);
103615         };
103616         builderProgram.restoreState = function () {
103617             state = ts.Debug.checkDefined(backupState);
103618             backupState = undefined;
103619         };
103620         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
103621         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
103622         builderProgram.emit = emit;
103623         builderProgram.releaseProgram = function () {
103624             releaseCache(state);
103625             backupState = undefined;
103626         };
103627         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
103628             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103629         }
103630         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103631             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
103632             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
103633         }
103634         else {
103635             ts.notImplemented();
103636         }
103637         return builderProgram;
103638         /**
103639          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
103640          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103641          * in that order would be used to write the files
103642          */
103643         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103644             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103645             var emitKind = 1 /* Full */;
103646             var isPendingEmitFile = false;
103647             if (!affected) {
103648                 if (!state.compilerOptions.out && !state.compilerOptions.outFile) {
103649                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
103650                     if (!pendingAffectedFile) {
103651                         if (state.emittedBuildInfo) {
103652                             return undefined;
103653                         }
103654                         var affected_1 = ts.Debug.checkDefined(state.program);
103655                         return toAffectedFileEmitResult(state, 
103656                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103657                         // Otherwise just affected file
103658                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
103659                         /*isPendingEmitFile*/ false, 
103660                         /*isBuildInfoEmit*/ true);
103661                     }
103662                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
103663                     isPendingEmitFile = true;
103664                 }
103665                 else {
103666                     var program = ts.Debug.checkDefined(state.program);
103667                     if (state.programEmitComplete)
103668                         return undefined;
103669                     affected = program;
103670                 }
103671             }
103672             return toAffectedFileEmitResult(state, 
103673             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
103674             // Otherwise just affected file
103675             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);
103676         }
103677         /**
103678          * Emits the JavaScript and declaration files.
103679          * When targetSource file is specified, emits the files corresponding to that source file,
103680          * otherwise for the whole program.
103681          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
103682          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
103683          * it will only emit all the affected files instead of whole program
103684          *
103685          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
103686          * in that order would be used to write the files
103687          */
103688         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
103689             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103690                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
103691                 var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, cancellationToken);
103692                 if (result)
103693                     return result;
103694                 if (!targetSourceFile) {
103695                     // Emit and report any errors we ran into.
103696                     var sourceMaps = [];
103697                     var emitSkipped = false;
103698                     var diagnostics = void 0;
103699                     var emittedFiles = [];
103700                     var affectedEmitResult = void 0;
103701                     while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
103702                         emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
103703                         diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
103704                         emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
103705                         sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
103706                     }
103707                     return {
103708                         emitSkipped: emitSkipped,
103709                         diagnostics: diagnostics || ts.emptyArray,
103710                         emittedFiles: emittedFiles,
103711                         sourceMaps: sourceMaps
103712                     };
103713                 }
103714             }
103715             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
103716         }
103717         /**
103718          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
103719          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
103720          */
103721         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
103722             while (true) {
103723                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
103724                 if (!affected) {
103725                     // Done
103726                     return undefined;
103727                 }
103728                 else if (affected === state.program) {
103729                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
103730                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
103731                 }
103732                 // Add file to affected file pending emit to handle for later emit time
103733                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
103734                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
103735                 }
103736                 // Get diagnostics for the affected file if its not ignored
103737                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
103738                     // Get next affected file
103739                     doneWithAffectedFile(state, affected);
103740                     continue;
103741                 }
103742                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
103743             }
103744         }
103745         /**
103746          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
103747          * The semantic diagnostics are cached and managed here
103748          * Note that it is assumed that when asked about semantic diagnostics through this API,
103749          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
103750          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
103751          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
103752          */
103753         function getSemanticDiagnostics(sourceFile, cancellationToken) {
103754             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
103755             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
103756             if (compilerOptions.outFile || compilerOptions.out) {
103757                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
103758                 // We dont need to cache the diagnostics just return them from program
103759                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
103760             }
103761             if (sourceFile) {
103762                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
103763             }
103764             // When semantic builder asks for diagnostics of the whole program,
103765             // ensure that all the affected files are handled
103766             // eslint-disable-next-line no-empty
103767             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
103768             }
103769             var diagnostics;
103770             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
103771                 var sourceFile_1 = _a[_i];
103772                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
103773             }
103774             return diagnostics || ts.emptyArray;
103775         }
103776     }
103777     ts.createBuilderProgram = createBuilderProgram;
103778     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
103779         if (!state.affectedFilesPendingEmit)
103780             state.affectedFilesPendingEmit = [];
103781         if (!state.affectedFilesPendingEmitKind)
103782             state.affectedFilesPendingEmitKind = ts.createMap();
103783         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
103784         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
103785         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
103786         // affectedFilesPendingEmitIndex === undefined
103787         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
103788         //   so start from 0 as array would be affectedFilesPendingEmit
103789         // else, continue to iterate from existing index, the current set is appended to existing files
103790         if (state.affectedFilesPendingEmitIndex === undefined) {
103791             state.affectedFilesPendingEmitIndex = 0;
103792         }
103793     }
103794     function getMapOfReferencedSet(mapLike, toPath) {
103795         if (!mapLike)
103796             return undefined;
103797         var map = ts.createMap();
103798         // Copies keys/values from template. Note that for..in will not throw if
103799         // template is undefined, and instead will just exit the loop.
103800         for (var key in mapLike) {
103801             if (ts.hasProperty(mapLike, key)) {
103802                 map.set(toPath(key), ts.arrayToSet(mapLike[key], toPath));
103803             }
103804         }
103805         return map;
103806     }
103807     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
103808         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
103809         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
103810         var fileInfos = ts.createMap();
103811         for (var key in program.fileInfos) {
103812             if (ts.hasProperty(program.fileInfos, key)) {
103813                 fileInfos.set(toPath(key), program.fileInfos[key]);
103814             }
103815         }
103816         var state = {
103817             fileInfos: fileInfos,
103818             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
103819             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
103820             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
103821             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]; }),
103822             hasReusableDiagnostic: true
103823         };
103824         return {
103825             getState: function () { return state; },
103826             backupState: ts.noop,
103827             restoreState: ts.noop,
103828             getProgram: ts.notImplemented,
103829             getProgramOrUndefined: ts.returnUndefined,
103830             releaseProgram: ts.noop,
103831             getCompilerOptions: function () { return state.compilerOptions; },
103832             getSourceFile: ts.notImplemented,
103833             getSourceFiles: ts.notImplemented,
103834             getOptionsDiagnostics: ts.notImplemented,
103835             getGlobalDiagnostics: ts.notImplemented,
103836             getConfigFileParsingDiagnostics: ts.notImplemented,
103837             getSyntacticDiagnostics: ts.notImplemented,
103838             getDeclarationDiagnostics: ts.notImplemented,
103839             getSemanticDiagnostics: ts.notImplemented,
103840             emit: ts.notImplemented,
103841             getAllDependencies: ts.notImplemented,
103842             getCurrentDirectory: ts.notImplemented,
103843             emitNextAffectedFile: ts.notImplemented,
103844             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
103845             close: ts.noop,
103846         };
103847         function toPath(path) {
103848             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
103849         }
103850         function toAbsolutePath(path) {
103851             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
103852         }
103853     }
103854     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
103855     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
103856         return {
103857             getState: ts.notImplemented,
103858             backupState: ts.noop,
103859             restoreState: ts.noop,
103860             getProgram: getProgram,
103861             getProgramOrUndefined: function () { return state.program; },
103862             releaseProgram: function () { return state.program = undefined; },
103863             getCompilerOptions: function () { return state.compilerOptions; },
103864             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
103865             getSourceFiles: function () { return getProgram().getSourceFiles(); },
103866             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
103867             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
103868             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
103869             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
103870             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
103871             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
103872             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
103873             getAllDependencies: ts.notImplemented,
103874             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
103875             close: ts.noop,
103876         };
103877         function getProgram() {
103878             return ts.Debug.checkDefined(state.program);
103879         }
103880     }
103881     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
103882 })(ts || (ts = {}));
103883 var ts;
103884 (function (ts) {
103885     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103886         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103887     }
103888     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
103889     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103890         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
103891     }
103892     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
103893     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
103894         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
103895         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
103896     }
103897     ts.createAbstractBuilder = createAbstractBuilder;
103898 })(ts || (ts = {}));
103899 /*@internal*/
103900 var ts;
103901 (function (ts) {
103902     function removeIgnoredPath(path) {
103903         // Consider whole staging folder as if node_modules changed.
103904         if (ts.endsWith(path, "/node_modules/.staging")) {
103905             return ts.removeSuffix(path, "/.staging");
103906         }
103907         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
103908             undefined :
103909             path;
103910     }
103911     ts.removeIgnoredPath = removeIgnoredPath;
103912     /**
103913      * Filter out paths like
103914      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
103915      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
103916      * @param dirPath
103917      */
103918     function canWatchDirectory(dirPath) {
103919         var rootLength = ts.getRootLength(dirPath);
103920         if (dirPath.length === rootLength) {
103921             // Ignore "/", "c:/"
103922             return false;
103923         }
103924         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
103925         if (nextDirectorySeparator === -1) {
103926             // ignore "/user", "c:/users" or "c:/folderAtRoot"
103927             return false;
103928         }
103929         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
103930         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
103931         if (isNonDirectorySeparatorRoot &&
103932             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
103933             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
103934             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
103935             if (nextDirectorySeparator === -1) {
103936                 // ignore "//vda1cs4850/c$/folderAtRoot"
103937                 return false;
103938             }
103939             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
103940         }
103941         if (isNonDirectorySeparatorRoot &&
103942             pathPartForUserCheck.search(/users\//i) !== 0) {
103943             // Paths like c:/folderAtRoot/subFolder are allowed
103944             return true;
103945         }
103946         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
103947             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
103948             if (searchIndex === 0) {
103949                 // Folder isnt at expected minimum levels
103950                 return false;
103951             }
103952         }
103953         return true;
103954     }
103955     ts.canWatchDirectory = canWatchDirectory;
103956     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
103957         var filesWithChangedSetOfUnresolvedImports;
103958         var filesWithInvalidatedResolutions;
103959         var filesWithInvalidatedNonRelativeUnresolvedImports;
103960         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
103961         var resolutionsWithFailedLookups = [];
103962         var resolvedFileToResolution = ts.createMultiMap();
103963         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
103964         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
103965         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
103966         // The key in the map is source file's path.
103967         // The values are Map of resolutions with key being name lookedup.
103968         var resolvedModuleNames = ts.createMap();
103969         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
103970         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
103971         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
103972         var resolvedTypeReferenceDirectives = ts.createMap();
103973         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
103974         /**
103975          * These are the extensions that failed lookup files will have by default,
103976          * any other extension of failed lookup will be store that path in custom failed lookup path
103977          * This helps in not having to comb through all resolutions when files are added/removed
103978          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
103979          */
103980         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
103981         var customFailedLookupPaths = ts.createMap();
103982         var directoryWatchesOfFailedLookups = ts.createMap();
103983         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
103984         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
103985         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
103986         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
103987         var typeRootsWatches = ts.createMap();
103988         return {
103989             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
103990             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
103991             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
103992             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
103993             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
103994             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
103995             resolveModuleNames: resolveModuleNames,
103996             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
103997             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
103998             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
103999             removeResolutionsOfFile: removeResolutionsOfFile,
104000             invalidateResolutionOfFile: invalidateResolutionOfFile,
104001             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
104002             createHasInvalidatedResolution: createHasInvalidatedResolution,
104003             updateTypeRootsWatch: updateTypeRootsWatch,
104004             closeTypeRootsWatch: closeTypeRootsWatch,
104005             clear: clear
104006         };
104007         function getResolvedModule(resolution) {
104008             return resolution.resolvedModule;
104009         }
104010         function getResolvedTypeReferenceDirective(resolution) {
104011             return resolution.resolvedTypeReferenceDirective;
104012         }
104013         function isInDirectoryPath(dir, file) {
104014             if (dir === undefined || file.length <= dir.length) {
104015                 return false;
104016             }
104017             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
104018         }
104019         function clear() {
104020             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
104021             customFailedLookupPaths.clear();
104022             nonRelativeExternalModuleResolutions.clear();
104023             closeTypeRootsWatch();
104024             resolvedModuleNames.clear();
104025             resolvedTypeReferenceDirectives.clear();
104026             resolvedFileToResolution.clear();
104027             resolutionsWithFailedLookups.length = 0;
104028             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
104029             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
104030             clearPerDirectoryResolutions();
104031         }
104032         function startRecordingFilesWithChangedResolutions() {
104033             filesWithChangedSetOfUnresolvedImports = [];
104034         }
104035         function finishRecordingFilesWithChangedResolutions() {
104036             var collected = filesWithChangedSetOfUnresolvedImports;
104037             filesWithChangedSetOfUnresolvedImports = undefined;
104038             return collected;
104039         }
104040         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
104041             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
104042                 return false;
104043             }
104044             // Invalidated if file has unresolved imports
104045             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
104046             return !!value && !!value.length;
104047         }
104048         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
104049             if (forceAllFilesAsInvalidated) {
104050                 // Any file asked would have invalidated resolution
104051                 filesWithInvalidatedResolutions = undefined;
104052                 return ts.returnTrue;
104053             }
104054             var collected = filesWithInvalidatedResolutions;
104055             filesWithInvalidatedResolutions = undefined;
104056             return function (path) { return (!!collected && collected.has(path)) ||
104057                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
104058         }
104059         function clearPerDirectoryResolutions() {
104060             perDirectoryResolvedModuleNames.clear();
104061             nonRelativeModuleNameCache.clear();
104062             perDirectoryResolvedTypeReferenceDirectives.clear();
104063             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
104064             nonRelativeExternalModuleResolutions.clear();
104065         }
104066         function finishCachingPerDirectoryResolution() {
104067             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
104068             clearPerDirectoryResolutions();
104069             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
104070                 if (watcher.refCount === 0) {
104071                     directoryWatchesOfFailedLookups.delete(path);
104072                     watcher.watcher.close();
104073                 }
104074             });
104075         }
104076         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
104077             var _a;
104078             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
104079             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
104080             if (!resolutionHost.getGlobalCache) {
104081                 return primaryResult;
104082             }
104083             // otherwise try to load typings from @types
104084             var globalCache = resolutionHost.getGlobalCache();
104085             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
104086                 // create different collection of failed lookup locations for second pass
104087                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
104088                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
104089                 if (resolvedModule) {
104090                     // Modify existing resolution so its saved in the directory cache as well
104091                     primaryResult.resolvedModule = resolvedModule;
104092                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
104093                     return primaryResult;
104094                 }
104095             }
104096             // Default return the result from the first pass
104097             return primaryResult;
104098         }
104099         function resolveNamesWithLocalCache(_a) {
104100             var _b;
104101             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;
104102             var path = resolutionHost.toPath(containingFile);
104103             var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path);
104104             var dirPath = ts.getDirectoryPath(path);
104105             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
104106             var perDirectoryResolution = perDirectoryCache.get(dirPath);
104107             if (!perDirectoryResolution) {
104108                 perDirectoryResolution = ts.createMap();
104109                 perDirectoryCache.set(dirPath, perDirectoryResolution);
104110             }
104111             var resolvedModules = [];
104112             var compilerOptions = resolutionHost.getCompilationSettings();
104113             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
104114             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
104115             var program = resolutionHost.getCurrentProgram();
104116             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
104117             var unmatchedRedirects = oldRedirect ?
104118                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
104119                 !!redirectedReference;
104120             var seenNamesInFile = ts.createMap();
104121             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
104122                 var name = names_3[_i];
104123                 var resolution = resolutionsInFile.get(name);
104124                 // Resolution is valid if it is present and not invalidated
104125                 if (!seenNamesInFile.has(name) &&
104126                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
104127                     // If the name is unresolved import that was invalidated, recalculate
104128                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
104129                     var existingResolution = resolution;
104130                     var resolutionInDirectory = perDirectoryResolution.get(name);
104131                     if (resolutionInDirectory) {
104132                         resolution = resolutionInDirectory;
104133                     }
104134                     else {
104135                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
104136                         perDirectoryResolution.set(name, resolution);
104137                     }
104138                     resolutionsInFile.set(name, resolution);
104139                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
104140                     if (existingResolution) {
104141                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
104142                     }
104143                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
104144                         filesWithChangedSetOfUnresolvedImports.push(path);
104145                         // reset log changes to avoid recording the same file multiple times
104146                         logChanges = false;
104147                     }
104148                 }
104149                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
104150                 seenNamesInFile.set(name, true);
104151                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
104152             }
104153             // Stop watching and remove the unused name
104154             resolutionsInFile.forEach(function (resolution, name) {
104155                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
104156                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
104157                     resolutionsInFile.delete(name);
104158                 }
104159             });
104160             return resolvedModules;
104161             function resolutionIsEqualTo(oldResolution, newResolution) {
104162                 if (oldResolution === newResolution) {
104163                     return true;
104164                 }
104165                 if (!oldResolution || !newResolution) {
104166                     return false;
104167                 }
104168                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
104169                 var newResult = getResolutionWithResolvedFileName(newResolution);
104170                 if (oldResult === newResult) {
104171                     return true;
104172                 }
104173                 if (!oldResult || !newResult) {
104174                     return false;
104175                 }
104176                 return oldResult.resolvedFileName === newResult.resolvedFileName;
104177             }
104178         }
104179         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
104180             return resolveNamesWithLocalCache({
104181                 names: typeDirectiveNames,
104182                 containingFile: containingFile,
104183                 redirectedReference: redirectedReference,
104184                 cache: resolvedTypeReferenceDirectives,
104185                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
104186                 loader: ts.resolveTypeReferenceDirective,
104187                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
104188                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
104189             });
104190         }
104191         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
104192             return resolveNamesWithLocalCache({
104193                 names: moduleNames,
104194                 containingFile: containingFile,
104195                 redirectedReference: redirectedReference,
104196                 cache: resolvedModuleNames,
104197                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
104198                 loader: resolveModuleName,
104199                 getResolutionWithResolvedFileName: getResolvedModule,
104200                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
104201                 reusedNames: reusedNames,
104202                 logChanges: logChangesWhenResolvingModule
104203             });
104204         }
104205         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
104206             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
104207             return cache && cache.get(moduleName);
104208         }
104209         function isNodeModulesAtTypesDirectory(dirPath) {
104210             return ts.endsWith(dirPath, "/node_modules/@types");
104211         }
104212         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
104213             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
104214                 // Ensure failed look up is normalized path
104215                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
104216                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
104217                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
104218                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
104219                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
104220                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
104221                     return {
104222                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
104223                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
104224                     };
104225                 }
104226                 else {
104227                     // Always watch root directory non recursively
104228                     return {
104229                         dir: rootDir,
104230                         dirPath: rootPath,
104231                         nonRecursive: false
104232                     };
104233                 }
104234             }
104235             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
104236         }
104237         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
104238             // If directory path contains node module, get the most parent node_modules directory for watching
104239             while (ts.pathContainsNodeModules(dirPath)) {
104240                 dir = ts.getDirectoryPath(dir);
104241                 dirPath = ts.getDirectoryPath(dirPath);
104242             }
104243             // If the directory is node_modules use it to watch, always watch it recursively
104244             if (ts.isNodeModulesDirectory(dirPath)) {
104245                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
104246             }
104247             var nonRecursive = true;
104248             // Use some ancestor of the root directory
104249             var subDirectoryPath, subDirectory;
104250             if (rootPath !== undefined) {
104251                 while (!isInDirectoryPath(dirPath, rootPath)) {
104252                     var parentPath = ts.getDirectoryPath(dirPath);
104253                     if (parentPath === dirPath) {
104254                         break;
104255                     }
104256                     nonRecursive = false;
104257                     subDirectoryPath = dirPath;
104258                     subDirectory = dir;
104259                     dirPath = parentPath;
104260                     dir = ts.getDirectoryPath(dir);
104261                 }
104262             }
104263             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
104264         }
104265         function isPathWithDefaultFailedLookupExtension(path) {
104266             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
104267         }
104268         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
104269             if (resolution.refCount) {
104270                 resolution.refCount++;
104271                 ts.Debug.assertDefined(resolution.files);
104272             }
104273             else {
104274                 resolution.refCount = 1;
104275                 ts.Debug.assert(resolution.files === undefined);
104276                 if (ts.isExternalModuleNameRelative(name)) {
104277                     watchFailedLookupLocationOfResolution(resolution);
104278                 }
104279                 else {
104280                     nonRelativeExternalModuleResolutions.add(name, resolution);
104281                 }
104282                 var resolved = getResolutionWithResolvedFileName(resolution);
104283                 if (resolved && resolved.resolvedFileName) {
104284                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104285                 }
104286             }
104287             (resolution.files || (resolution.files = [])).push(filePath);
104288         }
104289         function watchFailedLookupLocationOfResolution(resolution) {
104290             ts.Debug.assert(!!resolution.refCount);
104291             var failedLookupLocations = resolution.failedLookupLocations;
104292             if (!failedLookupLocations.length)
104293                 return;
104294             resolutionsWithFailedLookups.push(resolution);
104295             var setAtRoot = false;
104296             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
104297                 var failedLookupLocation = failedLookupLocations_1[_i];
104298                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104299                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104300                 if (toWatch) {
104301                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
104302                     // If the failed lookup location path is not one of the supported extensions,
104303                     // store it in the custom path
104304                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
104305                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
104306                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
104307                     }
104308                     if (dirPath === rootPath) {
104309                         ts.Debug.assert(!nonRecursive);
104310                         setAtRoot = true;
104311                     }
104312                     else {
104313                         setDirectoryWatcher(dir, dirPath, nonRecursive);
104314                     }
104315                 }
104316             }
104317             if (setAtRoot) {
104318                 // This is always non recursive
104319                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
104320             }
104321         }
104322         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
104323             var program = resolutionHost.getCurrentProgram();
104324             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
104325                 resolutions.forEach(watchFailedLookupLocationOfResolution);
104326             }
104327         }
104328         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
104329             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104330             if (dirWatcher) {
104331                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
104332                 dirWatcher.refCount++;
104333             }
104334             else {
104335                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
104336             }
104337         }
104338         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
104339             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
104340             resolution.refCount--;
104341             if (resolution.refCount) {
104342                 return;
104343             }
104344             var resolved = getResolutionWithResolvedFileName(resolution);
104345             if (resolved && resolved.resolvedFileName) {
104346                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
104347             }
104348             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
104349                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
104350                 return;
104351             }
104352             var failedLookupLocations = resolution.failedLookupLocations;
104353             var removeAtRoot = false;
104354             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
104355                 var failedLookupLocation = failedLookupLocations_2[_i];
104356                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
104357                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
104358                 if (toWatch) {
104359                     var dirPath = toWatch.dirPath;
104360                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
104361                     if (refCount) {
104362                         if (refCount === 1) {
104363                             customFailedLookupPaths.delete(failedLookupLocationPath);
104364                         }
104365                         else {
104366                             ts.Debug.assert(refCount > 1);
104367                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
104368                         }
104369                     }
104370                     if (dirPath === rootPath) {
104371                         removeAtRoot = true;
104372                     }
104373                     else {
104374                         removeDirectoryWatcher(dirPath);
104375                     }
104376                 }
104377             }
104378             if (removeAtRoot) {
104379                 removeDirectoryWatcher(rootPath);
104380             }
104381         }
104382         function removeDirectoryWatcher(dirPath) {
104383             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
104384             // Do not close the watcher yet since it might be needed by other failed lookup locations.
104385             dirWatcher.refCount--;
104386         }
104387         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
104388             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
104389                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104390                 if (cachedDirectoryStructureHost) {
104391                     // Since the file existence changed, update the sourceFiles cache
104392                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104393                 }
104394                 if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104395                     resolutionHost.onInvalidatedResolution();
104396                 }
104397             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
104398         }
104399         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
104400             // Deleted file, stop watching failed lookups for all the resolutions in the file
104401             var resolutions = cache.get(filePath);
104402             if (resolutions) {
104403                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
104404                 cache.delete(filePath);
104405             }
104406         }
104407         function removeResolutionsFromProjectReferenceRedirects(filePath) {
104408             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
104409                 return;
104410             }
104411             var program = resolutionHost.getCurrentProgram();
104412             if (!program) {
104413                 return;
104414             }
104415             // If this file is input file for the referenced project, get it
104416             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
104417             if (!resolvedProjectReference) {
104418                 return;
104419             }
104420             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
104421             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
104422         }
104423         function removeResolutionsOfFile(filePath) {
104424             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
104425             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
104426         }
104427         function invalidateResolution(resolution) {
104428             resolution.isInvalidated = true;
104429             var changedInAutoTypeReferenced = false;
104430             for (var _i = 0, _a = ts.Debug.assertDefined(resolution.files); _i < _a.length; _i++) {
104431                 var containingFilePath = _a[_i];
104432                 (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true);
104433                 // When its a file with inferred types resolution, invalidate type reference directive resolution
104434                 changedInAutoTypeReferenced = changedInAutoTypeReferenced || containingFilePath.endsWith(ts.inferredTypesContainingFile);
104435             }
104436             if (changedInAutoTypeReferenced) {
104437                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104438             }
104439         }
104440         function invalidateResolutionOfFile(filePath) {
104441             removeResolutionsOfFile(filePath);
104442             // Resolution is invalidated if the resulting file name is same as the deleted file path
104443             ts.forEach(resolvedFileToResolution.get(filePath), invalidateResolution);
104444         }
104445         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
104446             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
104447             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
104448         }
104449         function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
104450             var isChangedFailedLookupLocation;
104451             if (isCreatingWatchedDirectory) {
104452                 // Watching directory is created
104453                 // Invalidate any resolution has failed lookup in this directory
104454                 isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); };
104455             }
104456             else {
104457                 // If something to do with folder/file starting with "." in node_modules folder, skip it
104458                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
104459                 if (!updatedPath)
104460                     return false;
104461                 fileOrDirectoryPath = updatedPath;
104462                 // prevent saving an open file from over-eagerly triggering invalidation
104463                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
104464                     return false;
104465                 }
104466                 // Some file or directory in the watching directory is created
104467                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
104468                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
104469                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
104470                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
104471                     // Invalidate any resolution from this directory
104472                     isChangedFailedLookupLocation = function (location) {
104473                         var locationPath = resolutionHost.toPath(location);
104474                         return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath);
104475                     };
104476                 }
104477                 else {
104478                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
104479                         return false;
104480                     }
104481                     // Ignore emits from the program
104482                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
104483                         return false;
104484                     }
104485                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
104486                     isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; };
104487                 }
104488             }
104489             var invalidated = false;
104490             // Resolution is invalidated if the resulting file name is same as the deleted file path
104491             for (var _i = 0, resolutionsWithFailedLookups_1 = resolutionsWithFailedLookups; _i < resolutionsWithFailedLookups_1.length; _i++) {
104492                 var resolution = resolutionsWithFailedLookups_1[_i];
104493                 if (resolution.failedLookupLocations.some(isChangedFailedLookupLocation)) {
104494                     invalidateResolution(resolution);
104495                     invalidated = true;
104496                 }
104497             }
104498             return invalidated;
104499         }
104500         function closeTypeRootsWatch() {
104501             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
104502         }
104503         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
104504             if (isInDirectoryPath(rootPath, typeRootPath)) {
104505                 return rootPath;
104506             }
104507             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
104508             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
104509         }
104510         function createTypeRootsWatch(typeRootPath, typeRoot) {
104511             // Create new watch and recursive info
104512             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
104513                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
104514                 if (cachedDirectoryStructureHost) {
104515                     // Since the file existence changed, update the sourceFiles cache
104516                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
104517                 }
104518                 // For now just recompile
104519                 // We could potentially store more data here about whether it was/would be really be used or not
104520                 // and with that determine to trigger compilation but for now this is enough
104521                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
104522                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
104523                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
104524                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
104525                 if (dirPath && invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) {
104526                     resolutionHost.onInvalidatedResolution();
104527                 }
104528             }, 1 /* Recursive */);
104529         }
104530         /**
104531          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
104532          * To be called when compiler options change
104533          */
104534         function updateTypeRootsWatch() {
104535             var options = resolutionHost.getCompilationSettings();
104536             if (options.types) {
104537                 // No need to do any watch since resolution cache is going to handle the failed lookups
104538                 // for the types added by this
104539                 closeTypeRootsWatch();
104540                 return;
104541             }
104542             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
104543             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
104544             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
104545             if (typeRoots) {
104546                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
104547                     createNewValue: createTypeRootsWatch,
104548                     onDeleteValue: ts.closeFileWatcher
104549                 });
104550             }
104551             else {
104552                 closeTypeRootsWatch();
104553             }
104554         }
104555         /**
104556          * Use this function to return if directory exists to get type roots to watch
104557          * If we return directory exists then only the paths will be added to type roots
104558          * Hence return true for all directories except root directories which are filtered from watching
104559          */
104560         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
104561             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
104562             var dirPath = resolutionHost.toPath(dir);
104563             return dirPath === rootPath || canWatchDirectory(dirPath);
104564         }
104565     }
104566     ts.createResolutionCache = createResolutionCache;
104567 })(ts || (ts = {}));
104568 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
104569 /* @internal */
104570 var ts;
104571 (function (ts) {
104572     var moduleSpecifiers;
104573     (function (moduleSpecifiers) {
104574         var RelativePreference;
104575         (function (RelativePreference) {
104576             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
104577             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
104578             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
104579         })(RelativePreference || (RelativePreference = {}));
104580         // See UserPreferences#importPathEnding
104581         var Ending;
104582         (function (Ending) {
104583             Ending[Ending["Minimal"] = 0] = "Minimal";
104584             Ending[Ending["Index"] = 1] = "Index";
104585             Ending[Ending["JsExtension"] = 2] = "JsExtension";
104586         })(Ending || (Ending = {}));
104587         function getPreferences(_a, compilerOptions, importingSourceFile) {
104588             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
104589             return {
104590                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
104591                 ending: getEnding(),
104592             };
104593             function getEnding() {
104594                 switch (importModuleSpecifierEnding) {
104595                     case "minimal": return 0 /* Minimal */;
104596                     case "index": return 1 /* Index */;
104597                     case "js": return 2 /* JsExtension */;
104598                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
104599                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
104600                 }
104601             }
104602         }
104603         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
104604             return {
104605                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
104606                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
104607                     2 /* JsExtension */ :
104608                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
104609             };
104610         }
104611         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
104612             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
104613             if (res === oldImportSpecifier)
104614                 return undefined;
104615             return res;
104616         }
104617         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
104618         // Note: importingSourceFile is just for usesJsExtensionOnImports
104619         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
104620             if (preferences === void 0) { preferences = {}; }
104621             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
104622         }
104623         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
104624         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
104625             var info = getInfo(importingSourceFileName, host);
104626             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
104627             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions, /*packageNameOnly*/ true); });
104628         }
104629         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
104630         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
104631             var info = getInfo(importingSourceFileName, host);
104632             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
104633             return ts.firstDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); }) ||
104634                 getLocalModuleSpecifier(toFileName, info, compilerOptions, preferences);
104635         }
104636         /** Returns an import for each symlink and for the realpath. */
104637         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
104638             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
104639             if (ambient)
104640                 return [ambient];
104641             var info = getInfo(importingSourceFile.path, host);
104642             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
104643             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
104644             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
104645             var global = ts.mapDefined(modulePaths, function (moduleFileName) { return tryGetModuleNameAsNodeModule(moduleFileName, info, host, compilerOptions); });
104646             return global.length ? global : modulePaths.map(function (moduleFileName) { return getLocalModuleSpecifier(moduleFileName, info, compilerOptions, preferences); });
104647         }
104648         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
104649         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
104650         function getInfo(importingSourceFileName, host) {
104651             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
104652             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
104653             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
104654         }
104655         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, _b) {
104656             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104657             var ending = _b.ending, relativePreference = _b.relativePreference;
104658             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
104659             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
104660                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
104661             if (!baseUrl || relativePreference === 0 /* Relative */) {
104662                 return relativePath;
104663             }
104664             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseUrl, getCanonicalFileName);
104665             if (!relativeToBaseUrl) {
104666                 return relativePath;
104667             }
104668             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
104669             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
104670             var nonRelative = fromPaths === undefined ? importRelativeToBaseUrl : fromPaths;
104671             if (relativePreference === 1 /* NonRelative */) {
104672                 return nonRelative;
104673             }
104674             if (relativePreference !== 2 /* Auto */)
104675                 ts.Debug.assertNever(relativePreference);
104676             // Prefer a relative import over a baseUrl import if it has fewer components.
104677             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
104678         }
104679         function countPathComponents(path) {
104680             var count = 0;
104681             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
104682                 if (path.charCodeAt(i) === 47 /* slash */)
104683                     count++;
104684             }
104685             return count;
104686         }
104687         moduleSpecifiers.countPathComponents = countPathComponents;
104688         function usesJsExtensionOnImports(_a) {
104689             var imports = _a.imports;
104690             return ts.firstDefined(imports, function (_a) {
104691                 var text = _a.text;
104692                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
104693             }) || false;
104694         }
104695         function numberOfDirectorySeparators(str) {
104696             var match = str.match(/\//g);
104697             return match ? match.length : 0;
104698         }
104699         function comparePathsByNumberOfDirectorySeparators(a, b) {
104700             return ts.compareValues(numberOfDirectorySeparators(a), numberOfDirectorySeparators(b));
104701         }
104702         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
104703             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104704             var cwd = host.getCurrentDirectory();
104705             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
104706             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
104707             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
104708             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
104709             if (!preferSymlinks) {
104710                 var result_12 = ts.forEach(targets, cb);
104711                 if (result_12)
104712                     return result_12;
104713             }
104714             var links = host.getProbableSymlinks
104715                 ? host.getProbableSymlinks(host.getSourceFiles())
104716                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
104717             var compareStrings = (!host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames()) ? ts.compareStringsCaseSensitive : ts.compareStringsCaseInsensitive;
104718             var result = ts.forEachEntry(links, function (resolved, path) {
104719                 if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) {
104720                     return undefined; // Don't want to a package to globally import from itself
104721                 }
104722                 var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; });
104723                 if (target === undefined)
104724                     return undefined;
104725                 var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName);
104726                 var option = ts.resolvePath(path, relative);
104727                 if (!host.fileExists || host.fileExists(option)) {
104728                     var result_13 = cb(option);
104729                     if (result_13)
104730                         return result_13;
104731                 }
104732             });
104733             return result ||
104734                 (preferSymlinks ? ts.forEach(targets, cb) : undefined);
104735         }
104736         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
104737         /**
104738          * Looks for existing imports that use symlinks to this module.
104739          * Symlinks will be returned first so they are preferred over the real path.
104740          */
104741         function getAllModulePaths(importingFileName, importedFileName, host) {
104742             var cwd = host.getCurrentDirectory();
104743             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
104744             var allFileNames = ts.createMap();
104745             var importedFileFromNodeModules = false;
104746             forEachFileNameOfModule(importingFileName, importedFileName, host, 
104747             /*preferSymlinks*/ true, function (path) {
104748                 // dont return value, so we collect everything
104749                 allFileNames.set(path, getCanonicalFileName(path));
104750                 importedFileFromNodeModules = importedFileFromNodeModules || ts.pathContainsNodeModules(path);
104751             });
104752             // Sort by paths closest to importing file Name directory
104753             var sortedPaths = [];
104754             var _loop_20 = function (directory) {
104755                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
104756                 var pathsInDirectory;
104757                 allFileNames.forEach(function (canonicalFileName, fileName) {
104758                     if (ts.startsWith(canonicalFileName, directoryStart)) {
104759                         // If the importedFile is from node modules, use only paths in node_modules folder as option
104760                         if (!importedFileFromNodeModules || ts.pathContainsNodeModules(fileName)) {
104761                             (pathsInDirectory || (pathsInDirectory = [])).push(fileName);
104762                         }
104763                         allFileNames.delete(fileName);
104764                     }
104765                 });
104766                 if (pathsInDirectory) {
104767                     if (pathsInDirectory.length > 1) {
104768                         pathsInDirectory.sort(comparePathsByNumberOfDirectorySeparators);
104769                     }
104770                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
104771                 }
104772                 var newDirectory = ts.getDirectoryPath(directory);
104773                 if (newDirectory === directory)
104774                     return out_directory_1 = directory, "break";
104775                 directory = newDirectory;
104776                 out_directory_1 = directory;
104777             };
104778             var out_directory_1;
104779             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
104780                 var state_8 = _loop_20(directory);
104781                 directory = out_directory_1;
104782                 if (state_8 === "break")
104783                     break;
104784             }
104785             if (allFileNames.size) {
104786                 var remainingPaths = ts.arrayFrom(allFileNames.values());
104787                 if (remainingPaths.length > 1)
104788                     remainingPaths.sort(comparePathsByNumberOfDirectorySeparators);
104789                 sortedPaths.push.apply(sortedPaths, remainingPaths);
104790             }
104791             return sortedPaths;
104792         }
104793         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
104794             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
104795             if (decl) {
104796                 return decl.name.text;
104797             }
104798         }
104799         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
104800             for (var key in paths) {
104801                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
104802                     var patternText_1 = _a[_i];
104803                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
104804                     var indexOfStar = pattern.indexOf("*");
104805                     if (indexOfStar !== -1) {
104806                         var prefix = pattern.substr(0, indexOfStar);
104807                         var suffix = pattern.substr(indexOfStar + 1);
104808                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
104809                             ts.startsWith(relativeToBaseUrl, prefix) &&
104810                             ts.endsWith(relativeToBaseUrl, suffix) ||
104811                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
104812                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
104813                             return key.replace("*", matchedStar);
104814                         }
104815                     }
104816                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
104817                         return key;
104818                     }
104819                 }
104820             }
104821         }
104822         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
104823             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
104824             if (normalizedTargetPath === undefined) {
104825                 return undefined;
104826             }
104827             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
104828             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
104829             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
104830                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
104831                 : ts.removeFileExtension(relativePath);
104832         }
104833         function tryGetModuleNameAsNodeModule(moduleFileName, _a, host, options, packageNameOnly) {
104834             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
104835             if (!host.fileExists || !host.readFile) {
104836                 return undefined;
104837             }
104838             var parts = getNodeModulePathParts(moduleFileName);
104839             if (!parts) {
104840                 return undefined;
104841             }
104842             // Simplify the full file path to something that can be resolved by Node.
104843             var moduleSpecifier = moduleFileName;
104844             if (!packageNameOnly) {
104845                 var packageRootIndex = parts.packageRootIndex;
104846                 var moduleFileNameForExtensionless = void 0;
104847                 while (true) {
104848                     // If the module could be imported by a directory name, use that directory's name
104849                     var _b = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _b.moduleFileToTry, packageRootPath = _b.packageRootPath;
104850                     if (packageRootPath) {
104851                         moduleSpecifier = packageRootPath;
104852                         break;
104853                     }
104854                     if (!moduleFileNameForExtensionless)
104855                         moduleFileNameForExtensionless = moduleFileToTry;
104856                     // try with next level of directory
104857                     packageRootIndex = moduleFileName.indexOf(ts.directorySeparator, packageRootIndex + 1);
104858                     if (packageRootIndex === -1) {
104859                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
104860                         break;
104861                     }
104862                 }
104863             }
104864             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
104865             // Get a path that's relative to node_modules or the importing file's path
104866             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
104867             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
104868             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
104869                 return undefined;
104870             }
104871             // If the module was found in @types, get the actual Node package name
104872             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
104873             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
104874             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
104875             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
104876             function tryDirectoryWithPackageJson(packageRootIndex) {
104877                 var packageRootPath = moduleFileName.substring(0, packageRootIndex);
104878                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
104879                 var moduleFileToTry = moduleFileName;
104880                 if (host.fileExists(packageJsonPath)) {
104881                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
104882                     var versionPaths = packageJsonContent.typesVersions
104883                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
104884                         : undefined;
104885                     if (versionPaths) {
104886                         var subModuleName = moduleFileName.slice(packageRootPath.length + 1);
104887                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
104888                         if (fromPaths !== undefined) {
104889                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
104890                         }
104891                     }
104892                     // If the file is the main module, it can be imported by the package name
104893                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
104894                     if (ts.isString(mainFileRelative)) {
104895                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
104896                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
104897                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
104898                         }
104899                     }
104900                 }
104901                 return { moduleFileToTry: moduleFileToTry };
104902             }
104903             function getExtensionlessFileName(path) {
104904                 // We still have a file name - remove the extension
104905                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
104906                 // If the file is /index, it can be imported by its directory name
104907                 // IFF there is not _also_ a file by the same name
104908                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
104909                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
104910                 }
104911                 return fullModulePathWithoutExtension;
104912             }
104913         }
104914         function tryGetAnyFileFromPath(host, path) {
104915             if (!host.fileExists)
104916                 return;
104917             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
104918             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
104919             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
104920                 var e = extensions_3[_i];
104921                 var fullPath = path + e;
104922                 if (host.fileExists(fullPath)) {
104923                     return fullPath;
104924                 }
104925             }
104926         }
104927         function getNodeModulePathParts(fullPath) {
104928             // If fullPath can't be valid module file within node_modules, returns undefined.
104929             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
104930             // Returns indices:                       ^            ^                                                      ^             ^
104931             var topLevelNodeModulesIndex = 0;
104932             var topLevelPackageNameIndex = 0;
104933             var packageRootIndex = 0;
104934             var fileNameIndex = 0;
104935             var States;
104936             (function (States) {
104937                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
104938                 States[States["NodeModules"] = 1] = "NodeModules";
104939                 States[States["Scope"] = 2] = "Scope";
104940                 States[States["PackageContent"] = 3] = "PackageContent";
104941             })(States || (States = {}));
104942             var partStart = 0;
104943             var partEnd = 0;
104944             var state = 0 /* BeforeNodeModules */;
104945             while (partEnd >= 0) {
104946                 partStart = partEnd;
104947                 partEnd = fullPath.indexOf("/", partStart + 1);
104948                 switch (state) {
104949                     case 0 /* BeforeNodeModules */:
104950                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104951                             topLevelNodeModulesIndex = partStart;
104952                             topLevelPackageNameIndex = partEnd;
104953                             state = 1 /* NodeModules */;
104954                         }
104955                         break;
104956                     case 1 /* NodeModules */:
104957                     case 2 /* Scope */:
104958                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
104959                             state = 2 /* Scope */;
104960                         }
104961                         else {
104962                             packageRootIndex = partEnd;
104963                             state = 3 /* PackageContent */;
104964                         }
104965                         break;
104966                     case 3 /* PackageContent */:
104967                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
104968                             state = 1 /* NodeModules */;
104969                         }
104970                         else {
104971                             state = 3 /* PackageContent */;
104972                         }
104973                         break;
104974                 }
104975             }
104976             fileNameIndex = partStart;
104977             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
104978         }
104979         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
104980             return ts.firstDefined(rootDirs, function (rootDir) {
104981                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
104982                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
104983             });
104984         }
104985         function removeExtensionAndIndexPostFix(fileName, ending, options) {
104986             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
104987                 return fileName;
104988             var noExtension = ts.removeFileExtension(fileName);
104989             switch (ending) {
104990                 case 0 /* Minimal */:
104991                     return ts.removeSuffix(noExtension, "/index");
104992                 case 1 /* Index */:
104993                     return noExtension;
104994                 case 2 /* JsExtension */:
104995                     return noExtension + getJSExtensionForFile(fileName, options);
104996                 default:
104997                     return ts.Debug.assertNever(ending);
104998             }
104999         }
105000         function getJSExtensionForFile(fileName, options) {
105001             var ext = ts.extensionFromPath(fileName);
105002             switch (ext) {
105003                 case ".ts" /* Ts */:
105004                 case ".d.ts" /* Dts */:
105005                     return ".js" /* Js */;
105006                 case ".tsx" /* Tsx */:
105007                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
105008                 case ".js" /* Js */:
105009                 case ".jsx" /* Jsx */:
105010                 case ".json" /* Json */:
105011                     return ext;
105012                 case ".tsbuildinfo" /* TsBuildInfo */:
105013                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
105014                 default:
105015                     return ts.Debug.assertNever(ext);
105016             }
105017         }
105018         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
105019             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
105020             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
105021         }
105022         function isPathRelativeToParent(path) {
105023             return ts.startsWith(path, "..");
105024         }
105025     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
105026 })(ts || (ts = {}));
105027 /*@internal*/
105028 var ts;
105029 (function (ts) {
105030     var sysFormatDiagnosticsHost = ts.sys ? {
105031         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
105032         getNewLine: function () { return ts.sys.newLine; },
105033         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
105034     } : undefined; // TODO: GH#18217
105035     /**
105036      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
105037      */
105038     function createDiagnosticReporter(system, pretty) {
105039         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
105040             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
105041             getNewLine: function () { return system.newLine; },
105042             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
105043         };
105044         if (!pretty) {
105045             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
105046         }
105047         var diagnostics = new Array(1);
105048         return function (diagnostic) {
105049             diagnostics[0] = diagnostic;
105050             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
105051             diagnostics[0] = undefined; // TODO: GH#18217
105052         };
105053     }
105054     ts.createDiagnosticReporter = createDiagnosticReporter;
105055     /**
105056      * @returns Whether the screen was cleared.
105057      */
105058     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
105059         if (system.clearScreen &&
105060             !options.preserveWatchOutput &&
105061             !options.extendedDiagnostics &&
105062             !options.diagnostics &&
105063             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
105064             system.clearScreen();
105065             return true;
105066         }
105067         return false;
105068     }
105069     ts.screenStartingMessageCodes = [
105070         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
105071         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
105072     ];
105073     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
105074         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
105075             ? newLine + newLine
105076             : newLine;
105077     }
105078     /**
105079      * Get locale specific time based on whether we are in test mode
105080      */
105081     function getLocaleTimeString(system) {
105082         return !system.now ?
105083             new Date().toLocaleTimeString() :
105084             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
105085     }
105086     ts.getLocaleTimeString = getLocaleTimeString;
105087     /**
105088      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105089      */
105090     function createWatchStatusReporter(system, pretty) {
105091         return pretty ?
105092             function (diagnostic, newLine, options) {
105093                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
105094                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
105095                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
105096                 system.write(output);
105097             } :
105098             function (diagnostic, newLine, options) {
105099                 var output = "";
105100                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
105101                     output += newLine;
105102                 }
105103                 output += getLocaleTimeString(system) + " - ";
105104                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
105105                 system.write(output);
105106             };
105107     }
105108     ts.createWatchStatusReporter = createWatchStatusReporter;
105109     /** Parses config file using System interface */
105110     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
105111         var host = system;
105112         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
105113         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
105114         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
105115         return result;
105116     }
105117     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
105118     function getErrorCountForSummary(diagnostics) {
105119         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
105120     }
105121     ts.getErrorCountForSummary = getErrorCountForSummary;
105122     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
105123         return errorCount === 1 ?
105124             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
105125             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
105126     }
105127     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
105128     function getErrorSummaryText(errorCount, newLine) {
105129         if (errorCount === 0)
105130             return "";
105131         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
105132         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
105133     }
105134     ts.getErrorSummaryText = getErrorSummaryText;
105135     function listFiles(program, writeFileName) {
105136         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
105137             ts.forEach(program.getSourceFiles(), function (file) {
105138                 writeFileName(file.fileName);
105139             });
105140         }
105141     }
105142     ts.listFiles = listFiles;
105143     /**
105144      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
105145      */
105146     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105147         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
105148         // First get and report any syntactic errors.
105149         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
105150         var configFileParsingDiagnosticsLength = allDiagnostics.length;
105151         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105152         // If we didn't have any syntactic errors, then also try getting the global and
105153         // semantic errors.
105154         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105155             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
105156             if (!isListFilesOnly) {
105157                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
105158                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
105159                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
105160                 }
105161             }
105162         }
105163         // Emit and report any errors we ran into.
105164         var emitResult = isListFilesOnly
105165             ? { emitSkipped: true, diagnostics: ts.emptyArray }
105166             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
105167         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
105168         ts.addRange(allDiagnostics, emitDiagnostics);
105169         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
105170         diagnostics.forEach(reportDiagnostic);
105171         if (writeFileName) {
105172             var currentDir_1 = program.getCurrentDirectory();
105173             ts.forEach(emittedFiles, function (file) {
105174                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
105175                 writeFileName("TSFILE: " + filepath);
105176             });
105177             listFiles(program, writeFileName);
105178         }
105179         if (reportSummary) {
105180             reportSummary(getErrorCountForSummary(diagnostics));
105181         }
105182         return {
105183             emitResult: emitResult,
105184             diagnostics: diagnostics,
105185         };
105186     }
105187     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
105188     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
105189         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
105190         if (emitResult.emitSkipped && diagnostics.length > 0) {
105191             // If the emitter didn't emit anything, then pass that value along.
105192             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
105193         }
105194         else if (diagnostics.length > 0) {
105195             // The emitter emitted something, inform the caller if that happened in the presence
105196             // of diagnostics or not.
105197             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
105198         }
105199         return ts.ExitStatus.Success;
105200     }
105201     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
105202     ts.noopFileWatcher = { close: ts.noop };
105203     function createWatchHost(system, reportWatchStatus) {
105204         if (system === void 0) { system = ts.sys; }
105205         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
105206         return {
105207             onWatchStatusChange: onWatchStatusChange,
105208             watchFile: ts.maybeBind(system, system.watchFile) || (function () { return ts.noopFileWatcher; }),
105209             watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return ts.noopFileWatcher; }),
105210             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
105211             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
105212         };
105213     }
105214     ts.createWatchHost = createWatchHost;
105215     ts.WatchType = {
105216         ConfigFile: "Config file",
105217         SourceFile: "Source file",
105218         MissingFile: "Missing file",
105219         WildcardDirectory: "Wild card directory",
105220         FailedLookupLocations: "Failed Lookup Locations",
105221         TypeRoots: "Type roots"
105222     };
105223     function createWatchFactory(host, options) {
105224         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
105225         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
105226         var result = ts.getWatchFactory(watchLogLevel, writeLog);
105227         result.writeLog = writeLog;
105228         return result;
105229     }
105230     ts.createWatchFactory = createWatchFactory;
105231     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
105232         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
105233         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105234         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
105235         return {
105236             getSourceFile: function (fileName, languageVersion, onError) {
105237                 var text;
105238                 try {
105239                     ts.performance.mark("beforeIORead");
105240                     text = host.readFile(fileName, getCompilerOptions().charset);
105241                     ts.performance.mark("afterIORead");
105242                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
105243                 }
105244                 catch (e) {
105245                     if (onError) {
105246                         onError(e.message);
105247                     }
105248                     text = "";
105249                 }
105250                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
105251             },
105252             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
105253             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
105254             writeFile: writeFile,
105255             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
105256             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
105257             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
105258             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
105259             fileExists: function (f) { return host.fileExists(f); },
105260             readFile: function (f) { return host.readFile(f); },
105261             trace: ts.maybeBind(host, host.trace),
105262             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
105263             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
105264             realpath: ts.maybeBind(host, host.realpath),
105265             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
105266             createHash: ts.maybeBind(host, host.createHash),
105267             readDirectory: ts.maybeBind(host, host.readDirectory),
105268         };
105269         function writeFile(fileName, text, writeByteOrderMark, onError) {
105270             try {
105271                 ts.performance.mark("beforeIOWrite");
105272                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
105273                 // the host.writeFile will do its own directory creation and
105274                 // the ensureDirectoriesExist call will always be redundant.
105275                 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); });
105276                 ts.performance.mark("afterIOWrite");
105277                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
105278             }
105279             catch (e) {
105280                 if (onError) {
105281                     onError(e.message);
105282                 }
105283             }
105284         }
105285     }
105286     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
105287     function setGetSourceFileAsHashVersioned(compilerHost, host) {
105288         var originalGetSourceFile = compilerHost.getSourceFile;
105289         var computeHash = host.createHash || ts.generateDjb2Hash;
105290         compilerHost.getSourceFile = function () {
105291             var args = [];
105292             for (var _i = 0; _i < arguments.length; _i++) {
105293                 args[_i] = arguments[_i];
105294             }
105295             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
105296             if (result) {
105297                 result.version = computeHash.call(host, result.text);
105298             }
105299             return result;
105300         };
105301     }
105302     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
105303     /**
105304      * Creates the watch compiler host that can be extended with config file or root file names and options host
105305      */
105306     function createProgramHost(system, createProgram) {
105307         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
105308         return {
105309             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
105310             getNewLine: function () { return system.newLine; },
105311             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
105312             getDefaultLibLocation: getDefaultLibLocation,
105313             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
105314             fileExists: function (path) { return system.fileExists(path); },
105315             readFile: function (path, encoding) { return system.readFile(path, encoding); },
105316             directoryExists: function (path) { return system.directoryExists(path); },
105317             getDirectories: function (path) { return system.getDirectories(path); },
105318             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
105319             realpath: ts.maybeBind(system, system.realpath),
105320             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
105321             trace: function (s) { return system.write(s + system.newLine); },
105322             createDirectory: function (path) { return system.createDirectory(path); },
105323             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
105324             createHash: ts.maybeBind(system, system.createHash),
105325             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
105326         };
105327     }
105328     ts.createProgramHost = createProgramHost;
105329     /**
105330      * Creates the watch compiler host that can be extended with config file or root file names and options host
105331      */
105332     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
105333         if (system === void 0) { system = ts.sys; }
105334         var writeFileName = function (s) { return system.write(s + system.newLine); };
105335         var result = createProgramHost(system, createProgram);
105336         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
105337         result.afterProgramCreate = function (builderProgram) {
105338             var compilerOptions = builderProgram.getCompilerOptions();
105339             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
105340             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
105341         };
105342         return result;
105343     }
105344     /**
105345      * Report error and exit
105346      */
105347     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
105348         reportDiagnostic(diagnostic);
105349         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
105350     }
105351     /**
105352      * Creates the watch compiler host from system for config file in watch mode
105353      */
105354     function createWatchCompilerHostOfConfigFile(_a) {
105355         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;
105356         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
105357         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
105358         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
105359         host.configFileName = configFileName;
105360         host.optionsToExtend = optionsToExtend;
105361         host.watchOptionsToExtend = watchOptionsToExtend;
105362         host.extraFileExtensions = extraFileExtensions;
105363         return host;
105364     }
105365     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
105366     /**
105367      * Creates the watch compiler host from system for compiling root files and options in watch mode
105368      */
105369     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
105370         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;
105371         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
105372         host.rootFiles = rootFiles;
105373         host.options = options;
105374         host.watchOptions = watchOptions;
105375         host.projectReferences = projectReferences;
105376         return host;
105377     }
105378     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
105379     function performIncrementalCompilation(input) {
105380         var system = input.system || ts.sys;
105381         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
105382         var builderProgram = ts.createIncrementalProgram(input);
105383         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);
105384         if (input.afterProgramEmitAndDiagnostics)
105385             input.afterProgramEmitAndDiagnostics(builderProgram);
105386         return exitStatus;
105387     }
105388     ts.performIncrementalCompilation = performIncrementalCompilation;
105389 })(ts || (ts = {}));
105390 var ts;
105391 (function (ts) {
105392     function readBuilderProgram(compilerOptions, host) {
105393         if (compilerOptions.out || compilerOptions.outFile)
105394             return undefined;
105395         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
105396         if (!buildInfoPath)
105397             return undefined;
105398         var content = host.readFile(buildInfoPath);
105399         if (!content)
105400             return undefined;
105401         var buildInfo = ts.getBuildInfo(content);
105402         if (buildInfo.version !== ts.version)
105403             return undefined;
105404         if (!buildInfo.program)
105405             return undefined;
105406         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
105407     }
105408     ts.readBuilderProgram = readBuilderProgram;
105409     function createIncrementalCompilerHost(options, system) {
105410         if (system === void 0) { system = ts.sys; }
105411         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
105412         host.createHash = ts.maybeBind(system, system.createHash);
105413         ts.setGetSourceFileAsHashVersioned(host, system);
105414         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
105415         return host;
105416     }
105417     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
105418     function createIncrementalProgram(_a) {
105419         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
105420         host = host || createIncrementalCompilerHost(options);
105421         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
105422         var oldProgram = readBuilderProgram(options, host);
105423         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
105424     }
105425     ts.createIncrementalProgram = createIncrementalProgram;
105426     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
105427         if (ts.isArray(rootFilesOrConfigFileName)) {
105428             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
105429                 rootFiles: rootFilesOrConfigFileName,
105430                 options: options,
105431                 watchOptions: watchOptionsOrExtraFileExtensions,
105432                 projectReferences: projectReferencesOrWatchOptionsToExtend,
105433                 system: system,
105434                 createProgram: createProgram,
105435                 reportDiagnostic: reportDiagnostic,
105436                 reportWatchStatus: reportWatchStatus,
105437             });
105438         }
105439         else {
105440             return ts.createWatchCompilerHostOfConfigFile({
105441                 configFileName: rootFilesOrConfigFileName,
105442                 optionsToExtend: options,
105443                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
105444                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
105445                 system: system,
105446                 createProgram: createProgram,
105447                 reportDiagnostic: reportDiagnostic,
105448                 reportWatchStatus: reportWatchStatus,
105449             });
105450         }
105451     }
105452     ts.createWatchCompilerHost = createWatchCompilerHost;
105453     function createWatchProgram(host) {
105454         var builderProgram;
105455         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
105456         var missingFilesMap; // Map of file watchers for the missing files
105457         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
105458         var timerToUpdateProgram; // timer callback to recompile the program
105459         var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info
105460         var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files
105461         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
105462         var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed
105463         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
105464         var currentDirectory = host.getCurrentDirectory();
105465         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
105466         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
105467         var configFileSpecs;
105468         var configFileParsingDiagnostics;
105469         var canConfigFileJsonReportNoInputFiles = false;
105470         var hasChangedConfigFileParsingErrors = false;
105471         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
105472         var directoryStructureHost = cachedDirectoryStructureHost || host;
105473         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
105474         // From tsc we want to get already parsed result and hence check for rootFileNames
105475         var newLine = updateNewLine();
105476         if (configFileName && host.configFileParsingResult) {
105477             setConfigFileParsingResult(host.configFileParsingResult);
105478             newLine = updateNewLine();
105479         }
105480         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
105481         if (configFileName && !host.configFileParsingResult) {
105482             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105483             ts.Debug.assert(!rootFileNames);
105484             parseConfigFile();
105485             newLine = updateNewLine();
105486         }
105487         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
105488         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
105489         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
105490         var configFileWatcher;
105491         if (configFileName) {
105492             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
105493         }
105494         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
105495         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
105496         // Members for CompilerHost
105497         var getNewSourceFile = compilerHost.getSourceFile;
105498         compilerHost.getSourceFile = function (fileName) {
105499             var args = [];
105500             for (var _i = 1; _i < arguments.length; _i++) {
105501                 args[_i - 1] = arguments[_i];
105502             }
105503             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
105504         };
105505         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
105506         compilerHost.getNewLine = function () { return newLine; };
105507         compilerHost.fileExists = fileExists;
105508         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
105509         // Members for ResolutionCacheHost
105510         compilerHost.toPath = toPath;
105511         compilerHost.getCompilationSettings = function () { return compilerOptions; };
105512         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
105513         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
105514         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
105515         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
105516         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
105517         compilerHost.onChangedAutomaticTypeDirectiveNames = function () {
105518             hasChangedAutomaticTypeDirectiveNames = true;
105519             scheduleProgramUpdate();
105520         };
105521         compilerHost.fileIsOpen = ts.returnFalse;
105522         compilerHost.getCurrentProgram = getCurrentProgram;
105523         compilerHost.writeLog = writeLog;
105524         // Cache for the module resolution
105525         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
105526             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
105527             currentDirectory, 
105528         /*logChangesWhenResolvingModule*/ false);
105529         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
105530         compilerHost.resolveModuleNames = host.resolveModuleNames ?
105531             (function () {
105532                 var args = [];
105533                 for (var _i = 0; _i < arguments.length; _i++) {
105534                     args[_i] = arguments[_i];
105535                 }
105536                 return host.resolveModuleNames.apply(host, args);
105537             }) :
105538             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
105539         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
105540             (function () {
105541                 var args = [];
105542                 for (var _i = 0; _i < arguments.length; _i++) {
105543                     args[_i] = arguments[_i];
105544                 }
105545                 return host.resolveTypeReferenceDirectives.apply(host, args);
105546             }) :
105547             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
105548         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
105549         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
105550         synchronizeProgram();
105551         // Update the wild card directory watch
105552         watchConfigFileWildCardDirectories();
105553         return configFileName ?
105554             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
105555             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
105556         function close() {
105557             resolutionCache.clear();
105558             ts.clearMap(sourceFilesCache, function (value) {
105559                 if (value && value.fileWatcher) {
105560                     value.fileWatcher.close();
105561                     value.fileWatcher = undefined;
105562                 }
105563             });
105564             if (configFileWatcher) {
105565                 configFileWatcher.close();
105566                 configFileWatcher = undefined;
105567             }
105568             if (watchedWildcardDirectories) {
105569                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105570                 watchedWildcardDirectories = undefined;
105571             }
105572             if (missingFilesMap) {
105573                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
105574                 missingFilesMap = undefined;
105575             }
105576         }
105577         function getCurrentBuilderProgram() {
105578             return builderProgram;
105579         }
105580         function getCurrentProgram() {
105581             return builderProgram && builderProgram.getProgramOrUndefined();
105582         }
105583         function synchronizeProgram() {
105584             writeLog("Synchronizing program");
105585             var program = getCurrentBuilderProgram();
105586             if (hasChangedCompilerOptions) {
105587                 newLine = updateNewLine();
105588                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
105589                     resolutionCache.clear();
105590                 }
105591             }
105592             // All resolutions are invalid if user provided resolutions
105593             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
105594             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
105595                 if (hasChangedConfigFileParsingErrors) {
105596                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105597                     hasChangedConfigFileParsingErrors = false;
105598                 }
105599             }
105600             else {
105601                 createNewProgram(hasInvalidatedResolution);
105602             }
105603             if (host.afterProgramCreate && program !== builderProgram) {
105604                 host.afterProgramCreate(builderProgram);
105605             }
105606             return builderProgram;
105607         }
105608         function createNewProgram(hasInvalidatedResolution) {
105609             // Compile the program
105610             writeLog("CreatingProgramWith::");
105611             writeLog("  roots: " + JSON.stringify(rootFileNames));
105612             writeLog("  options: " + JSON.stringify(compilerOptions));
105613             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
105614             hasChangedCompilerOptions = false;
105615             hasChangedConfigFileParsingErrors = false;
105616             resolutionCache.startCachingPerDirectoryResolution();
105617             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
105618             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
105619             hasChangedAutomaticTypeDirectiveNames = false;
105620             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
105621             resolutionCache.finishCachingPerDirectoryResolution();
105622             // Update watches
105623             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath);
105624             if (needsUpdateInTypeRootWatch) {
105625                 resolutionCache.updateTypeRootsWatch();
105626             }
105627             if (missingFilePathsRequestedForRelease) {
105628                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
105629                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
105630                 // if there is already watcher for it (for missing files)
105631                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
105632                 // so that at later time we have correct result of their presence
105633                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
105634                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
105635                     if (!missingFilesMap.has(missingFilePath)) {
105636                         sourceFilesCache.delete(missingFilePath);
105637                     }
105638                 }
105639                 missingFilePathsRequestedForRelease = undefined;
105640             }
105641         }
105642         function updateRootFileNames(files) {
105643             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
105644             rootFileNames = files;
105645             scheduleProgramUpdate();
105646         }
105647         function updateNewLine() {
105648             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
105649         }
105650         function toPath(fileName) {
105651             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105652         }
105653         function isFileMissingOnHost(hostSourceFile) {
105654             return typeof hostSourceFile === "boolean";
105655         }
105656         function isFilePresenceUnknownOnHost(hostSourceFile) {
105657             return typeof hostSourceFile.version === "boolean";
105658         }
105659         function fileExists(fileName) {
105660             var path = toPath(fileName);
105661             // If file is missing on host from cache, we can definitely say file doesnt exist
105662             // otherwise we need to ensure from the disk
105663             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
105664                 return false;
105665             }
105666             return directoryStructureHost.fileExists(fileName);
105667         }
105668         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
105669             var hostSourceFile = sourceFilesCache.get(path);
105670             // No source file on the host
105671             if (isFileMissingOnHost(hostSourceFile)) {
105672                 return undefined;
105673             }
105674             // Create new source file if requested or the versions dont match
105675             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
105676                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
105677                 if (hostSourceFile) {
105678                     if (sourceFile) {
105679                         // Set the source file and create file watcher now that file was present on the disk
105680                         hostSourceFile.sourceFile = sourceFile;
105681                         hostSourceFile.version = sourceFile.version;
105682                         if (!hostSourceFile.fileWatcher) {
105683                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105684                         }
105685                     }
105686                     else {
105687                         // There is no source file on host any more, close the watch, missing file paths will track it
105688                         if (hostSourceFile.fileWatcher) {
105689                             hostSourceFile.fileWatcher.close();
105690                         }
105691                         sourceFilesCache.set(path, false);
105692                     }
105693                 }
105694                 else {
105695                     if (sourceFile) {
105696                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
105697                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
105698                     }
105699                     else {
105700                         sourceFilesCache.set(path, false);
105701                     }
105702                 }
105703                 return sourceFile;
105704             }
105705             return hostSourceFile.sourceFile;
105706         }
105707         function nextSourceFileVersion(path) {
105708             var hostSourceFile = sourceFilesCache.get(path);
105709             if (hostSourceFile !== undefined) {
105710                 if (isFileMissingOnHost(hostSourceFile)) {
105711                     // The next version, lets set it as presence unknown file
105712                     sourceFilesCache.set(path, { version: false });
105713                 }
105714                 else {
105715                     hostSourceFile.version = false;
105716                 }
105717             }
105718         }
105719         function getSourceVersion(path) {
105720             var hostSourceFile = sourceFilesCache.get(path);
105721             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
105722         }
105723         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
105724             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
105725             // If this is the source file thats in the cache and new program doesnt need it,
105726             // remove the cached entry.
105727             // Note we arent deleting entry if file became missing in new program or
105728             // there was version update and new source file was created.
105729             if (hostSourceFileInfo !== undefined) {
105730                 // record the missing file paths so they can be removed later if watchers arent tracking them
105731                 if (isFileMissingOnHost(hostSourceFileInfo)) {
105732                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
105733                 }
105734                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
105735                     if (hostSourceFileInfo.fileWatcher) {
105736                         hostSourceFileInfo.fileWatcher.close();
105737                     }
105738                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
105739                     if (!hasSourceFileByPath) {
105740                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
105741                     }
105742                 }
105743             }
105744         }
105745         function reportWatchDiagnostic(message) {
105746             if (host.onWatchStatusChange) {
105747                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
105748             }
105749         }
105750         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
105751         // operations (such as saving all modified files in an editor) a chance to complete before we kick
105752         // off a new compilation.
105753         function scheduleProgramUpdate() {
105754             if (!host.setTimeout || !host.clearTimeout) {
105755                 return;
105756             }
105757             if (timerToUpdateProgram) {
105758                 host.clearTimeout(timerToUpdateProgram);
105759             }
105760             writeLog("Scheduling update");
105761             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
105762         }
105763         function scheduleProgramReload() {
105764             ts.Debug.assert(!!configFileName);
105765             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
105766             scheduleProgramUpdate();
105767         }
105768         function updateProgramWithWatchStatus() {
105769             timerToUpdateProgram = undefined;
105770             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
105771             updateProgram();
105772         }
105773         function updateProgram() {
105774             switch (reloadLevel) {
105775                 case ts.ConfigFileProgramReloadLevel.Partial:
105776                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
105777                     reloadFileNamesFromConfigFile();
105778                     break;
105779                 case ts.ConfigFileProgramReloadLevel.Full:
105780                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
105781                     reloadConfigFile();
105782                     break;
105783                 default:
105784                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
105785                     synchronizeProgram();
105786                     break;
105787             }
105788             ts.perfLogger.logStopUpdateProgram("Done");
105789             return getCurrentBuilderProgram();
105790         }
105791         function reloadFileNamesFromConfigFile() {
105792             writeLog("Reloading new file names and options");
105793             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost);
105794             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
105795                 hasChangedConfigFileParsingErrors = true;
105796             }
105797             rootFileNames = result.fileNames;
105798             // Update the program
105799             synchronizeProgram();
105800         }
105801         function reloadConfigFile() {
105802             writeLog("Reloading config file: " + configFileName);
105803             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
105804             if (cachedDirectoryStructureHost) {
105805                 cachedDirectoryStructureHost.clearCache();
105806             }
105807             parseConfigFile();
105808             hasChangedCompilerOptions = true;
105809             synchronizeProgram();
105810             // Update the wild card directory watch
105811             watchConfigFileWildCardDirectories();
105812         }
105813         function parseConfigFile() {
105814             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
105815         }
105816         function setConfigFileParsingResult(configFileParseResult) {
105817             rootFileNames = configFileParseResult.fileNames;
105818             compilerOptions = configFileParseResult.options;
105819             watchOptions = configFileParseResult.watchOptions;
105820             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
105821             projectReferences = configFileParseResult.projectReferences;
105822             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
105823             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInutFiles(configFileParseResult.raw);
105824             hasChangedConfigFileParsingErrors = true;
105825         }
105826         function onSourceFileChange(fileName, eventKind, path) {
105827             updateCachedSystemWithFile(fileName, path, eventKind);
105828             // Update the source file cache
105829             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
105830                 resolutionCache.invalidateResolutionOfFile(path);
105831             }
105832             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
105833             nextSourceFileVersion(path);
105834             // Update the program
105835             scheduleProgramUpdate();
105836         }
105837         function updateCachedSystemWithFile(fileName, path, eventKind) {
105838             if (cachedDirectoryStructureHost) {
105839                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
105840             }
105841         }
105842         function watchMissingFilePath(missingFilePath) {
105843             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
105844         }
105845         function onMissingFileChange(fileName, eventKind, missingFilePath) {
105846             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
105847             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
105848                 missingFilesMap.get(missingFilePath).close();
105849                 missingFilesMap.delete(missingFilePath);
105850                 // Delete the entry in the source files cache so that new source file is created
105851                 nextSourceFileVersion(missingFilePath);
105852                 // When a missing file is created, we should update the graph.
105853                 scheduleProgramUpdate();
105854             }
105855         }
105856         function watchConfigFileWildCardDirectories() {
105857             if (configFileSpecs) {
105858                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileSpecs.wildcardDirectories), watchWildcardDirectory);
105859             }
105860             else if (watchedWildcardDirectories) {
105861                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
105862             }
105863         }
105864         function watchWildcardDirectory(directory, flags) {
105865             return watchDirectory(host, directory, function (fileOrDirectory) {
105866                 ts.Debug.assert(!!configFileName);
105867                 var fileOrDirectoryPath = toPath(fileOrDirectory);
105868                 // Since the file existence changed, update the sourceFiles cache
105869                 if (cachedDirectoryStructureHost) {
105870                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
105871                 }
105872                 nextSourceFileVersion(fileOrDirectoryPath);
105873                 fileOrDirectoryPath = ts.removeIgnoredPath(fileOrDirectoryPath);
105874                 if (!fileOrDirectoryPath)
105875                     return;
105876                 // If the the added or created file or directory is not supported file name, ignore the file
105877                 // But when watched directory is added/removed, we need to reload the file list
105878                 if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) {
105879                     writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
105880                     return;
105881                 }
105882                 // Reload is pending, do the reload
105883                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
105884                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
105885                     // Schedule Update the program
105886                     scheduleProgramUpdate();
105887                 }
105888             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
105889         }
105890     }
105891     ts.createWatchProgram = createWatchProgram;
105892 })(ts || (ts = {}));
105893 /*@internal*/
105894 var ts;
105895 (function (ts) {
105896     var UpToDateStatusType;
105897     (function (UpToDateStatusType) {
105898         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
105899         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
105900         /**
105901          * The project appears out of date because its upstream inputs are newer than its outputs,
105902          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105903          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
105904          */
105905         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
105906         /**
105907          * The project appears out of date because its upstream inputs are newer than its outputs,
105908          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
105909          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
105910          */
105911         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
105912         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
105913         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
105914         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
105915         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
105916         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
105917         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
105918         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
105919         /**
105920          * Projects with no outputs (i.e. "solution" files)
105921          */
105922         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
105923     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
105924     function resolveConfigFileProjectName(project) {
105925         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
105926             return project;
105927         }
105928         return ts.combinePaths(project, "tsconfig.json");
105929     }
105930     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
105931 })(ts || (ts = {}));
105932 var ts;
105933 (function (ts) {
105934     var minimumDate = new Date(-8640000000000000);
105935     var maximumDate = new Date(8640000000000000);
105936     var BuildResultFlags;
105937     (function (BuildResultFlags) {
105938         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
105939         /**
105940          * No errors of any kind occurred during build
105941          */
105942         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
105943         /**
105944          * None of the .d.ts files emitted by this build were
105945          * different from the existing files on disk
105946          */
105947         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
105948         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
105949         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
105950         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
105951         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
105952         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
105953         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
105954     })(BuildResultFlags || (BuildResultFlags = {}));
105955     function createConfigFileMap() {
105956         return ts.createMap();
105957     }
105958     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
105959         var existingValue = configFileMap.get(resolved);
105960         var newValue;
105961         if (!existingValue) {
105962             newValue = createT();
105963             configFileMap.set(resolved, newValue);
105964         }
105965         return existingValue || newValue;
105966     }
105967     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
105968         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, ts.createMap);
105969     }
105970     function newer(date1, date2) {
105971         return date2 > date1 ? date2 : date1;
105972     }
105973     function isDeclarationFile(fileName) {
105974         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
105975     }
105976     /*@internal*/
105977     function isCircularBuildOrder(buildOrder) {
105978         return !!buildOrder && !!buildOrder.buildOrder;
105979     }
105980     ts.isCircularBuildOrder = isCircularBuildOrder;
105981     /*@internal*/
105982     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
105983         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
105984     }
105985     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
105986     /**
105987      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
105988      */
105989     function createBuilderStatusReporter(system, pretty) {
105990         return function (diagnostic) {
105991             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
105992             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
105993             system.write(output);
105994         };
105995     }
105996     ts.createBuilderStatusReporter = createBuilderStatusReporter;
105997     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
105998         var host = ts.createProgramHost(system, createProgram);
105999         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
106000         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
106001         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
106002         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
106003         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
106004         host.now = ts.maybeBind(system, system.now); // For testing
106005         return host;
106006     }
106007     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
106008         if (system === void 0) { system = ts.sys; }
106009         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106010         host.reportErrorSummary = reportErrorSummary;
106011         return host;
106012     }
106013     ts.createSolutionBuilderHost = createSolutionBuilderHost;
106014     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
106015         if (system === void 0) { system = ts.sys; }
106016         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
106017         var watchHost = ts.createWatchHost(system, reportWatchStatus);
106018         ts.copyProperties(host, watchHost);
106019         return host;
106020     }
106021     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
106022     function getCompilerOptionsOfBuildOptions(buildOptions) {
106023         var result = {};
106024         ts.commonOptionsWithBuild.forEach(function (option) {
106025             if (ts.hasProperty(buildOptions, option.name))
106026                 result[option.name] = buildOptions[option.name];
106027         });
106028         return result;
106029     }
106030     function createSolutionBuilder(host, rootNames, defaultOptions) {
106031         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
106032     }
106033     ts.createSolutionBuilder = createSolutionBuilder;
106034     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
106035         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
106036     }
106037     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
106038     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
106039         var host = hostOrHostWithWatch;
106040         var hostWithWatch = hostOrHostWithWatch;
106041         var currentDirectory = host.getCurrentDirectory();
106042         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
106043         // State of the solution
106044         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
106045         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
106046         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
106047         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
106048         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
106049         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
106050         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
106051         if (!compilerHost.resolveModuleNames) {
106052             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
106053             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
106054                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
106055             };
106056         }
106057         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
106058         var state = {
106059             host: host,
106060             hostWithWatch: hostWithWatch,
106061             currentDirectory: currentDirectory,
106062             getCanonicalFileName: getCanonicalFileName,
106063             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
106064             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
106065             // State of solution
106066             options: options,
106067             baseCompilerOptions: baseCompilerOptions,
106068             rootNames: rootNames,
106069             baseWatchOptions: baseWatchOptions,
106070             resolvedConfigFilePaths: ts.createMap(),
106071             configFileCache: createConfigFileMap(),
106072             projectStatus: createConfigFileMap(),
106073             buildInfoChecked: createConfigFileMap(),
106074             extendedConfigCache: ts.createMap(),
106075             builderPrograms: createConfigFileMap(),
106076             diagnostics: createConfigFileMap(),
106077             projectPendingBuild: createConfigFileMap(),
106078             projectErrorsReported: createConfigFileMap(),
106079             compilerHost: compilerHost,
106080             moduleResolutionCache: moduleResolutionCache,
106081             // Mutable state
106082             buildOrder: undefined,
106083             readFileWithCache: function (f) { return host.readFile(f); },
106084             projectCompilerOptions: baseCompilerOptions,
106085             cache: undefined,
106086             allProjectBuildPending: true,
106087             needsSummary: true,
106088             watchAllProjectsPending: watch,
106089             currentInvalidatedProject: undefined,
106090             // Watch state
106091             watch: watch,
106092             allWatchedWildcardDirectories: createConfigFileMap(),
106093             allWatchedInputFiles: createConfigFileMap(),
106094             allWatchedConfigFiles: createConfigFileMap(),
106095             timerToBuildInvalidatedProject: undefined,
106096             reportFileChangeDetected: false,
106097             watchFile: watchFile,
106098             watchFilePath: watchFilePath,
106099             watchDirectory: watchDirectory,
106100             writeLog: writeLog,
106101         };
106102         return state;
106103     }
106104     function toPath(state, fileName) {
106105         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
106106     }
106107     function toResolvedConfigFilePath(state, fileName) {
106108         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
106109         var path = resolvedConfigFilePaths.get(fileName);
106110         if (path !== undefined)
106111             return path;
106112         var resolvedPath = toPath(state, fileName);
106113         resolvedConfigFilePaths.set(fileName, resolvedPath);
106114         return resolvedPath;
106115     }
106116     function isParsedCommandLine(entry) {
106117         return !!entry.options;
106118     }
106119     function parseConfigFile(state, configFileName, configFilePath) {
106120         var configFileCache = state.configFileCache;
106121         var value = configFileCache.get(configFilePath);
106122         if (value) {
106123             return isParsedCommandLine(value) ? value : undefined;
106124         }
106125         var diagnostic;
106126         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
106127         var parsed;
106128         if (host.getParsedCommandLine) {
106129             parsed = host.getParsedCommandLine(configFileName);
106130             if (!parsed)
106131                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
106132         }
106133         else {
106134             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
106135             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
106136             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
106137         }
106138         configFileCache.set(configFilePath, parsed || diagnostic);
106139         return parsed;
106140     }
106141     function resolveProjectName(state, name) {
106142         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
106143     }
106144     function createBuildOrder(state, roots) {
106145         var temporaryMarks = ts.createMap();
106146         var permanentMarks = ts.createMap();
106147         var circularityReportStack = [];
106148         var buildOrder;
106149         var circularDiagnostics;
106150         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
106151             var root = roots_1[_i];
106152             visit(root);
106153         }
106154         return circularDiagnostics ?
106155             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
106156             buildOrder || ts.emptyArray;
106157         function visit(configFileName, inCircularContext) {
106158             var projPath = toResolvedConfigFilePath(state, configFileName);
106159             // Already visited
106160             if (permanentMarks.has(projPath))
106161                 return;
106162             // Circular
106163             if (temporaryMarks.has(projPath)) {
106164                 if (!inCircularContext) {
106165                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
106166                 }
106167                 return;
106168             }
106169             temporaryMarks.set(projPath, true);
106170             circularityReportStack.push(configFileName);
106171             var parsed = parseConfigFile(state, configFileName, projPath);
106172             if (parsed && parsed.projectReferences) {
106173                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
106174                     var ref = _a[_i];
106175                     var resolvedRefPath = resolveProjectName(state, ref.path);
106176                     visit(resolvedRefPath, inCircularContext || ref.circular);
106177                 }
106178             }
106179             circularityReportStack.pop();
106180             permanentMarks.set(projPath, true);
106181             (buildOrder || (buildOrder = [])).push(configFileName);
106182         }
106183     }
106184     function getBuildOrder(state) {
106185         return state.buildOrder || createStateBuildOrder(state);
106186     }
106187     function createStateBuildOrder(state) {
106188         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
106189         // Clear all to ResolvedConfigFilePaths cache to start fresh
106190         state.resolvedConfigFilePaths.clear();
106191         var currentProjects = ts.arrayToSet(getBuildOrderFromAnyBuildOrder(buildOrder), function (resolved) { return toResolvedConfigFilePath(state, resolved); });
106192         var noopOnDelete = { onDeleteValue: ts.noop };
106193         // Config file cache
106194         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
106195         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
106196         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
106197         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
106198         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
106199         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
106200         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
106201         // Remove watches for the program no longer in the solution
106202         if (state.watch) {
106203             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
106204             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
106205             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
106206         }
106207         return state.buildOrder = buildOrder;
106208     }
106209     function getBuildOrderFor(state, project, onlyReferences) {
106210         var resolvedProject = project && resolveProjectName(state, project);
106211         var buildOrderFromState = getBuildOrder(state);
106212         if (isCircularBuildOrder(buildOrderFromState))
106213             return buildOrderFromState;
106214         if (resolvedProject) {
106215             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
106216             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
106217             if (projectIndex === -1)
106218                 return undefined;
106219         }
106220         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
106221         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
106222         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
106223         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
106224         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
106225     }
106226     function enableCache(state) {
106227         if (state.cache) {
106228             disableCache(state);
106229         }
106230         var compilerHost = state.compilerHost, host = state.host;
106231         var originalReadFileWithCache = state.readFileWithCache;
106232         var originalGetSourceFile = compilerHost.getSourceFile;
106233         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
106234             var args = [];
106235             for (var _i = 0; _i < arguments.length; _i++) {
106236                 args[_i] = arguments[_i];
106237             }
106238             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
106239         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
106240         state.readFileWithCache = readFileWithCache;
106241         compilerHost.getSourceFile = getSourceFileWithCache;
106242         state.cache = {
106243             originalReadFile: originalReadFile,
106244             originalFileExists: originalFileExists,
106245             originalDirectoryExists: originalDirectoryExists,
106246             originalCreateDirectory: originalCreateDirectory,
106247             originalWriteFile: originalWriteFile,
106248             originalReadFileWithCache: originalReadFileWithCache,
106249             originalGetSourceFile: originalGetSourceFile,
106250         };
106251     }
106252     function disableCache(state) {
106253         if (!state.cache)
106254             return;
106255         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
106256         host.readFile = cache.originalReadFile;
106257         host.fileExists = cache.originalFileExists;
106258         host.directoryExists = cache.originalDirectoryExists;
106259         host.createDirectory = cache.originalCreateDirectory;
106260         host.writeFile = cache.originalWriteFile;
106261         compilerHost.getSourceFile = cache.originalGetSourceFile;
106262         state.readFileWithCache = cache.originalReadFileWithCache;
106263         extendedConfigCache.clear();
106264         if (moduleResolutionCache) {
106265             moduleResolutionCache.directoryToModuleNameMap.clear();
106266             moduleResolutionCache.moduleNameToDirectoryMap.clear();
106267         }
106268         state.cache = undefined;
106269     }
106270     function clearProjectStatus(state, resolved) {
106271         state.projectStatus.delete(resolved);
106272         state.diagnostics.delete(resolved);
106273     }
106274     function addProjToQueue(_a, proj, reloadLevel) {
106275         var projectPendingBuild = _a.projectPendingBuild;
106276         var value = projectPendingBuild.get(proj);
106277         if (value === undefined) {
106278             projectPendingBuild.set(proj, reloadLevel);
106279         }
106280         else if (value < reloadLevel) {
106281             projectPendingBuild.set(proj, reloadLevel);
106282         }
106283     }
106284     function setupInitialBuild(state, cancellationToken) {
106285         // Set initial build if not already built
106286         if (!state.allProjectBuildPending)
106287             return;
106288         state.allProjectBuildPending = false;
106289         if (state.options.watch) {
106290             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
106291         }
106292         enableCache(state);
106293         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
106294         buildOrder.forEach(function (configFileName) {
106295             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
106296         });
106297         if (cancellationToken) {
106298             cancellationToken.throwIfCancellationRequested();
106299         }
106300     }
106301     var InvalidatedProjectKind;
106302     (function (InvalidatedProjectKind) {
106303         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
106304         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
106305         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
106306     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
106307     function doneInvalidatedProject(state, projectPath) {
106308         state.projectPendingBuild.delete(projectPath);
106309         state.currentInvalidatedProject = undefined;
106310         return state.diagnostics.has(projectPath) ?
106311             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
106312             ts.ExitStatus.Success;
106313     }
106314     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
106315         var updateOutputFileStampsPending = true;
106316         return {
106317             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
106318             project: project,
106319             projectPath: projectPath,
106320             buildOrder: buildOrder,
106321             getCompilerOptions: function () { return config.options; },
106322             getCurrentDirectory: function () { return state.currentDirectory; },
106323             updateOutputFileStatmps: function () {
106324                 updateOutputTimestamps(state, config, projectPath);
106325                 updateOutputFileStampsPending = false;
106326             },
106327             done: function () {
106328                 if (updateOutputFileStampsPending) {
106329                     updateOutputTimestamps(state, config, projectPath);
106330                 }
106331                 return doneInvalidatedProject(state, projectPath);
106332             }
106333         };
106334     }
106335     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
106336         var Step;
106337         (function (Step) {
106338             Step[Step["CreateProgram"] = 0] = "CreateProgram";
106339             Step[Step["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
106340             Step[Step["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
106341             Step[Step["Emit"] = 3] = "Emit";
106342             Step[Step["EmitBundle"] = 4] = "EmitBundle";
106343             Step[Step["BuildInvalidatedProjectOfBundle"] = 5] = "BuildInvalidatedProjectOfBundle";
106344             Step[Step["QueueReferencingProjects"] = 6] = "QueueReferencingProjects";
106345             Step[Step["Done"] = 7] = "Done";
106346         })(Step || (Step = {}));
106347         var step = kind === InvalidatedProjectKind.Build ? Step.CreateProgram : Step.EmitBundle;
106348         var program;
106349         var buildResult;
106350         var invalidatedProjectOfBundle;
106351         return kind === InvalidatedProjectKind.Build ?
106352             {
106353                 kind: kind,
106354                 project: project,
106355                 projectPath: projectPath,
106356                 buildOrder: buildOrder,
106357                 getCompilerOptions: function () { return config.options; },
106358                 getCurrentDirectory: function () { return state.currentDirectory; },
106359                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
106360                 getProgram: function () {
106361                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
106362                 },
106363                 getSourceFile: function (fileName) {
106364                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
106365                 },
106366                 getSourceFiles: function () {
106367                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
106368                 },
106369                 getOptionsDiagnostics: function (cancellationToken) {
106370                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
106371                 },
106372                 getGlobalDiagnostics: function (cancellationToken) {
106373                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
106374                 },
106375                 getConfigFileParsingDiagnostics: function () {
106376                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
106377                 },
106378                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
106379                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
106380                 },
106381                 getAllDependencies: function (sourceFile) {
106382                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
106383                 },
106384                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
106385                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
106386                 },
106387                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
106388                     return withProgramOrUndefined(function (program) {
106389                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
106390                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
106391                     });
106392                 },
106393                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
106394                     if (targetSourceFile || emitOnlyDtsFiles) {
106395                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
106396                     }
106397                     executeSteps(Step.SemanticDiagnostics, cancellationToken);
106398                     if (step !== Step.Emit)
106399                         return undefined;
106400                     return emit(writeFile, cancellationToken, customTransformers);
106401                 },
106402                 done: done
106403             } :
106404             {
106405                 kind: kind,
106406                 project: project,
106407                 projectPath: projectPath,
106408                 buildOrder: buildOrder,
106409                 getCompilerOptions: function () { return config.options; },
106410                 getCurrentDirectory: function () { return state.currentDirectory; },
106411                 emit: function (writeFile, customTransformers) {
106412                     if (step !== Step.EmitBundle)
106413                         return invalidatedProjectOfBundle;
106414                     return emitBundle(writeFile, customTransformers);
106415                 },
106416                 done: done,
106417             };
106418         function done(cancellationToken, writeFile, customTransformers) {
106419             executeSteps(Step.Done, cancellationToken, writeFile, customTransformers);
106420             return doneInvalidatedProject(state, projectPath);
106421         }
106422         function withProgramOrUndefined(action) {
106423             executeSteps(Step.CreateProgram);
106424             return program && action(program);
106425         }
106426         function withProgramOrEmptyArray(action) {
106427             return withProgramOrUndefined(action) || ts.emptyArray;
106428         }
106429         function createProgram() {
106430             ts.Debug.assert(program === undefined);
106431             if (state.options.dry) {
106432                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
106433                 buildResult = BuildResultFlags.Success;
106434                 step = Step.QueueReferencingProjects;
106435                 return;
106436             }
106437             if (state.options.verbose)
106438                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
106439             if (config.fileNames.length === 0) {
106440                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106441                 // Nothing to build - must be a solution file, basically
106442                 buildResult = BuildResultFlags.None;
106443                 step = Step.QueueReferencingProjects;
106444                 return;
106445             }
106446             var host = state.host, compilerHost = state.compilerHost;
106447             state.projectCompilerOptions = config.options;
106448             // Update module resolution cache if needed
106449             updateModuleResolutionCache(state, project, config);
106450             // Create program
106451             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
106452             step++;
106453         }
106454         function handleDiagnostics(diagnostics, errorFlags, errorType) {
106455             if (diagnostics.length) {
106456                 buildResult = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType);
106457                 step = Step.QueueReferencingProjects;
106458             }
106459             else {
106460                 step++;
106461             }
106462         }
106463         function getSyntaxDiagnostics(cancellationToken) {
106464             ts.Debug.assertIsDefined(program);
106465             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
106466         }
106467         function getSemanticDiagnostics(cancellationToken) {
106468             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
106469         }
106470         function emit(writeFileCallback, cancellationToken, customTransformers) {
106471             ts.Debug.assertIsDefined(program);
106472             ts.Debug.assert(step === Step.Emit);
106473             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
106474             program.backupState();
106475             var declDiagnostics;
106476             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
106477             var outputFiles = [];
106478             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
106479             /*writeFileName*/ undefined, 
106480             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
106481             /*emitOnlyDts*/ false, customTransformers).emitResult;
106482             // Don't emit .d.ts if there are decl file errors
106483             if (declDiagnostics) {
106484                 program.restoreState();
106485                 buildResult = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file");
106486                 step = Step.QueueReferencingProjects;
106487                 return {
106488                     emitSkipped: true,
106489                     diagnostics: emitResult.diagnostics
106490                 };
106491             }
106492             // Actual Emit
106493             var host = state.host, compilerHost = state.compilerHost;
106494             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
106495             var newestDeclarationFileContentChangedTime = minimumDate;
106496             var anyDtsChanged = false;
106497             var emitterDiagnostics = ts.createDiagnosticCollection();
106498             var emittedOutputs = ts.createMap();
106499             outputFiles.forEach(function (_a) {
106500                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106501                 var priorChangeTime;
106502                 if (!anyDtsChanged && isDeclarationFile(name)) {
106503                     // Check for unchanged .d.ts files
106504                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
106505                         priorChangeTime = host.getModifiedTime(name);
106506                     }
106507                     else {
106508                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
106509                         anyDtsChanged = true;
106510                     }
106511                 }
106512                 emittedOutputs.set(toPath(state, name), name);
106513                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106514                 if (priorChangeTime !== undefined) {
106515                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
106516                 }
106517             });
106518             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
106519             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
106520             return emitResult;
106521         }
106522         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
106523             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
106524             if (emitDiagnostics.length) {
106525                 buildResult = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit");
106526                 step = Step.QueueReferencingProjects;
106527                 return emitDiagnostics;
106528             }
106529             if (state.writeFileName) {
106530                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
106531                 if (program)
106532                     ts.listFiles(program, state.writeFileName);
106533             }
106534             // Update time stamps for rest of the outputs
106535             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
106536             state.diagnostics.delete(projectPath);
106537             state.projectStatus.set(projectPath, {
106538                 type: ts.UpToDateStatusType.UpToDate,
106539                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
106540                     maximumDate :
106541                     newestDeclarationFileContentChangedTime,
106542                 oldestOutputFileName: oldestOutputFileName
106543             });
106544             afterProgramDone(state, projectPath, program, config);
106545             state.projectCompilerOptions = state.baseCompilerOptions;
106546             step = Step.QueueReferencingProjects;
106547             buildResult = resultFlags;
106548             return emitDiagnostics;
106549         }
106550         function emitBundle(writeFileCallback, customTransformers) {
106551             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
106552             if (state.options.dry) {
106553                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
106554                 buildResult = BuildResultFlags.Success;
106555                 step = Step.QueueReferencingProjects;
106556                 return undefined;
106557             }
106558             if (state.options.verbose)
106559                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
106560             // Update js, and source map
106561             var compilerHost = state.compilerHost;
106562             state.projectCompilerOptions = config.options;
106563             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
106564                 var refName = resolveProjectName(state, ref.path);
106565                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
106566             }, customTransformers);
106567             if (ts.isString(outputFiles)) {
106568                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
106569                 step = Step.BuildInvalidatedProjectOfBundle;
106570                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
106571             }
106572             // Actual Emit
106573             ts.Debug.assert(!!outputFiles.length);
106574             var emitterDiagnostics = ts.createDiagnosticCollection();
106575             var emittedOutputs = ts.createMap();
106576             outputFiles.forEach(function (_a) {
106577                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
106578                 emittedOutputs.set(toPath(state, name), name);
106579                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
106580             });
106581             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
106582             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
106583             return { emitSkipped: false, diagnostics: emitDiagnostics };
106584         }
106585         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
106586             while (step <= till && step < Step.Done) {
106587                 var currentStep = step;
106588                 switch (step) {
106589                     case Step.CreateProgram:
106590                         createProgram();
106591                         break;
106592                     case Step.SyntaxDiagnostics:
106593                         getSyntaxDiagnostics(cancellationToken);
106594                         break;
106595                     case Step.SemanticDiagnostics:
106596                         getSemanticDiagnostics(cancellationToken);
106597                         break;
106598                     case Step.Emit:
106599                         emit(writeFile, cancellationToken, customTransformers);
106600                         break;
106601                     case Step.EmitBundle:
106602                         emitBundle(writeFile, customTransformers);
106603                         break;
106604                     case Step.BuildInvalidatedProjectOfBundle:
106605                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
106606                         step = Step.Done;
106607                         break;
106608                     case Step.QueueReferencingProjects:
106609                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
106610                         step++;
106611                         break;
106612                     // Should never be done
106613                     case Step.Done:
106614                     default:
106615                         ts.assertType(step);
106616                 }
106617                 ts.Debug.assert(step > currentStep);
106618             }
106619         }
106620     }
106621     function needsBuild(_a, status, config) {
106622         var options = _a.options;
106623         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
106624             return true;
106625         return config.fileNames.length === 0 ||
106626             !!ts.getConfigFileParsingDiagnostics(config).length ||
106627             !ts.isIncrementalCompilation(config.options);
106628     }
106629     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
106630         if (!state.projectPendingBuild.size)
106631             return undefined;
106632         if (isCircularBuildOrder(buildOrder))
106633             return undefined;
106634         if (state.currentInvalidatedProject) {
106635             // Only if same buildOrder the currentInvalidated project can be sent again
106636             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
106637                 state.currentInvalidatedProject :
106638                 undefined;
106639         }
106640         var options = state.options, projectPendingBuild = state.projectPendingBuild;
106641         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
106642             var project = buildOrder[projectIndex];
106643             var projectPath = toResolvedConfigFilePath(state, project);
106644             var reloadLevel = state.projectPendingBuild.get(projectPath);
106645             if (reloadLevel === undefined)
106646                 continue;
106647             if (reportQueue) {
106648                 reportQueue = false;
106649                 reportBuildQueue(state, buildOrder);
106650             }
106651             var config = parseConfigFile(state, project, projectPath);
106652             if (!config) {
106653                 reportParseConfigFileDiagnostic(state, projectPath);
106654                 projectPendingBuild.delete(projectPath);
106655                 continue;
106656             }
106657             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
106658                 watchConfigFile(state, project, projectPath, config);
106659                 watchWildCardDirectories(state, project, projectPath, config);
106660                 watchInputFiles(state, project, projectPath, config);
106661             }
106662             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
106663                 // Update file names
106664                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
106665                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInutFiles(config.raw));
106666                 config.fileNames = result.fileNames;
106667                 watchInputFiles(state, project, projectPath, config);
106668             }
106669             var status = getUpToDateStatus(state, config, projectPath);
106670             verboseReportProjectStatus(state, project, status);
106671             if (!options.force) {
106672                 if (status.type === ts.UpToDateStatusType.UpToDate) {
106673                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106674                     projectPendingBuild.delete(projectPath);
106675                     // Up to date, skip
106676                     if (options.dry) {
106677                         // In a dry build, inform the user of this fact
106678                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
106679                     }
106680                     continue;
106681                 }
106682                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
106683                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106684                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
106685                 }
106686             }
106687             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
106688                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106689                 projectPendingBuild.delete(projectPath);
106690                 if (options.verbose) {
106691                     reportStatus(state, status.upstreamProjectBlocked ?
106692                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
106693                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
106694                 }
106695                 continue;
106696             }
106697             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
106698                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
106699                 projectPendingBuild.delete(projectPath);
106700                 // Do nothing
106701                 continue;
106702             }
106703             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
106704                 InvalidatedProjectKind.Build :
106705                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
106706         }
106707         return undefined;
106708     }
106709     function listEmittedFile(_a, proj, file) {
106710         var writeFileName = _a.writeFileName;
106711         if (writeFileName && proj.options.listEmittedFiles) {
106712             writeFileName("TSFILE: " + file);
106713         }
106714     }
106715     function getOldProgram(_a, proj, parsed) {
106716         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
106717         if (options.force)
106718             return undefined;
106719         var value = builderPrograms.get(proj);
106720         if (value)
106721             return value;
106722         return ts.readBuilderProgram(parsed.options, compilerHost);
106723     }
106724     function afterProgramDone(_a, proj, program, config) {
106725         var host = _a.host, watch = _a.watch, builderPrograms = _a.builderPrograms;
106726         if (program) {
106727             if (host.afterProgramEmitAndDiagnostics) {
106728                 host.afterProgramEmitAndDiagnostics(program);
106729             }
106730             if (watch) {
106731                 program.releaseProgram();
106732                 builderPrograms.set(proj, program);
106733             }
106734         }
106735         else if (host.afterEmitBundle) {
106736             host.afterEmitBundle(config);
106737         }
106738     }
106739     function buildErrors(state, resolvedPath, program, config, diagnostics, errorFlags, errorType) {
106740         reportAndStoreErrors(state, resolvedPath, diagnostics);
106741         // List files if any other build error using program (emit errors already report files)
106742         if (program && state.writeFileName)
106743             ts.listFiles(program, state.writeFileName);
106744         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
106745         afterProgramDone(state, resolvedPath, program, config);
106746         state.projectCompilerOptions = state.baseCompilerOptions;
106747         return errorFlags;
106748     }
106749     function updateModuleResolutionCache(state, proj, config) {
106750         if (!state.moduleResolutionCache)
106751             return;
106752         // Update module resolution cache if needed
106753         var moduleResolutionCache = state.moduleResolutionCache;
106754         var projPath = toPath(state, proj);
106755         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
106756             // The own map will be for projectCompilerOptions
106757             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
106758             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
106759             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
106760         }
106761         else {
106762             // Set correct own map
106763             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
106764             var ref = {
106765                 sourceFile: config.options.configFile,
106766                 commandLine: config
106767             };
106768             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
106769             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
106770         }
106771         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
106772         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
106773     }
106774     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
106775         // Check tsconfig time
106776         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
106777         if (oldestOutputFileTime < tsconfigTime) {
106778             return {
106779                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106780                 outOfDateOutputFileName: oldestOutputFileName,
106781                 newerInputFileName: configFile
106782             };
106783         }
106784     }
106785     function getUpToDateStatusWorker(state, project, resolvedPath) {
106786         var newestInputFileName = undefined;
106787         var newestInputFileTime = minimumDate;
106788         var host = state.host;
106789         // Get timestamps of input files
106790         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
106791             var inputFile = _a[_i];
106792             if (!host.fileExists(inputFile)) {
106793                 return {
106794                     type: ts.UpToDateStatusType.Unbuildable,
106795                     reason: inputFile + " does not exist"
106796                 };
106797             }
106798             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
106799             if (inputTime > newestInputFileTime) {
106800                 newestInputFileName = inputFile;
106801                 newestInputFileTime = inputTime;
106802             }
106803         }
106804         // Container if no files are specified in the project
106805         if (!project.fileNames.length && !ts.canJsonReportNoInutFiles(project.raw)) {
106806             return {
106807                 type: ts.UpToDateStatusType.ContainerOnly
106808             };
106809         }
106810         // Collect the expected outputs of this project
106811         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
106812         // Now see if all outputs are newer than the newest input
106813         var oldestOutputFileName = "(none)";
106814         var oldestOutputFileTime = maximumDate;
106815         var newestOutputFileName = "(none)";
106816         var newestOutputFileTime = minimumDate;
106817         var missingOutputFileName;
106818         var newestDeclarationFileContentChangedTime = minimumDate;
106819         var isOutOfDateWithInputs = false;
106820         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
106821             var output = outputs_1[_b];
106822             // Output is missing; can stop checking
106823             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106824             if (!host.fileExists(output)) {
106825                 missingOutputFileName = output;
106826                 break;
106827             }
106828             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106829             if (outputTime < oldestOutputFileTime) {
106830                 oldestOutputFileTime = outputTime;
106831                 oldestOutputFileName = output;
106832             }
106833             // If an output is older than the newest input, we can stop checking
106834             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
106835             if (outputTime < newestInputFileTime) {
106836                 isOutOfDateWithInputs = true;
106837                 break;
106838             }
106839             if (outputTime > newestOutputFileTime) {
106840                 newestOutputFileTime = outputTime;
106841                 newestOutputFileName = output;
106842             }
106843             // Keep track of when the most recent time a .d.ts file was changed.
106844             // In addition to file timestamps, we also keep track of when a .d.ts file
106845             // had its file touched but not had its contents changed - this allows us
106846             // to skip a downstream typecheck
106847             if (isDeclarationFile(output)) {
106848                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
106849                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
106850             }
106851         }
106852         var pseudoUpToDate = false;
106853         var usesPrepend = false;
106854         var upstreamChangedProject;
106855         if (project.projectReferences) {
106856             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
106857             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
106858                 var ref = _d[_c];
106859                 usesPrepend = usesPrepend || !!(ref.prepend);
106860                 var resolvedRef = ts.resolveProjectReferencePath(ref);
106861                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
106862                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
106863                 // Its a circular reference ignore the status of this project
106864                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
106865                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
106866                     continue;
106867                 }
106868                 // An upstream project is blocked
106869                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
106870                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
106871                     return {
106872                         type: ts.UpToDateStatusType.UpstreamBlocked,
106873                         upstreamProjectName: ref.path,
106874                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
106875                     };
106876                 }
106877                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
106878                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
106879                     return {
106880                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
106881                         upstreamProjectName: ref.path
106882                     };
106883                 }
106884                 // Check oldest output file name only if there is no missing output file name
106885                 if (!missingOutputFileName) {
106886                     // If the upstream project's newest file is older than our oldest output, we
106887                     // can't be out of date because of it
106888                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
106889                         continue;
106890                     }
106891                     // If the upstream project has only change .d.ts files, and we've built
106892                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
106893                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
106894                         pseudoUpToDate = true;
106895                         upstreamChangedProject = ref.path;
106896                         continue;
106897                     }
106898                     // We have an output older than an upstream output - we are out of date
106899                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
106900                     return {
106901                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
106902                         outOfDateOutputFileName: oldestOutputFileName,
106903                         newerProjectName: ref.path
106904                     };
106905                 }
106906             }
106907         }
106908         if (missingOutputFileName !== undefined) {
106909             return {
106910                 type: ts.UpToDateStatusType.OutputMissing,
106911                 missingOutputFileName: missingOutputFileName
106912             };
106913         }
106914         if (isOutOfDateWithInputs) {
106915             return {
106916                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
106917                 outOfDateOutputFileName: oldestOutputFileName,
106918                 newerInputFileName: newestInputFileName
106919             };
106920         }
106921         else {
106922             // Check tsconfig time
106923             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
106924             if (configStatus)
106925                 return configStatus;
106926             // Check extended config time
106927             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
106928             if (extendedConfigStatus)
106929                 return extendedConfigStatus;
106930         }
106931         if (!state.buildInfoChecked.has(resolvedPath)) {
106932             state.buildInfoChecked.set(resolvedPath, true);
106933             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
106934             if (buildInfoPath) {
106935                 var value = state.readFileWithCache(buildInfoPath);
106936                 var buildInfo = value && ts.getBuildInfo(value);
106937                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
106938                     return {
106939                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
106940                         version: buildInfo.version
106941                     };
106942                 }
106943             }
106944         }
106945         if (usesPrepend && pseudoUpToDate) {
106946             return {
106947                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
106948                 outOfDateOutputFileName: oldestOutputFileName,
106949                 newerProjectName: upstreamChangedProject
106950             };
106951         }
106952         // Up to date
106953         return {
106954             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
106955             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
106956             newestInputFileTime: newestInputFileTime,
106957             newestOutputFileTime: newestOutputFileTime,
106958             newestInputFileName: newestInputFileName,
106959             newestOutputFileName: newestOutputFileName,
106960             oldestOutputFileName: oldestOutputFileName
106961         };
106962     }
106963     function getUpToDateStatus(state, project, resolvedPath) {
106964         if (project === undefined) {
106965             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
106966         }
106967         var prior = state.projectStatus.get(resolvedPath);
106968         if (prior !== undefined) {
106969             return prior;
106970         }
106971         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
106972         state.projectStatus.set(resolvedPath, actual);
106973         return actual;
106974     }
106975     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
106976         var host = state.host;
106977         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
106978         if (!skipOutputs || outputs.length !== skipOutputs.size) {
106979             var reportVerbose = !!state.options.verbose;
106980             var now = host.now ? host.now() : new Date();
106981             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
106982                 var file = outputs_2[_i];
106983                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
106984                     continue;
106985                 }
106986                 if (reportVerbose) {
106987                     reportVerbose = false;
106988                     reportStatus(state, verboseMessage, proj.options.configFilePath);
106989                 }
106990                 if (isDeclarationFile(file)) {
106991                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
106992                 }
106993                 host.setModifiedTime(file, now);
106994             }
106995         }
106996         return priorNewestUpdateTime;
106997     }
106998     function updateOutputTimestamps(state, proj, resolvedPath) {
106999         if (state.options.dry) {
107000             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
107001         }
107002         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
107003         state.projectStatus.set(resolvedPath, {
107004             type: ts.UpToDateStatusType.UpToDate,
107005             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
107006             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
107007         });
107008     }
107009     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
107010         // Queue only if there are no errors
107011         if (buildResult & BuildResultFlags.AnyErrors)
107012             return;
107013         // Only composite projects can be referenced by other projects
107014         if (!config.options.composite)
107015             return;
107016         // Always use build order to queue projects
107017         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
107018             var nextProject = buildOrder[index];
107019             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
107020             if (state.projectPendingBuild.has(nextProjectPath))
107021                 continue;
107022             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
107023             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
107024                 continue;
107025             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
107026                 var ref = _a[_i];
107027                 var resolvedRefPath = resolveProjectName(state, ref.path);
107028                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
107029                     continue;
107030                 // If the project is referenced with prepend, always build downstream projects,
107031                 // If declaration output is changed, build the project
107032                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
107033                 var status = state.projectStatus.get(nextProjectPath);
107034                 if (status) {
107035                     switch (status.type) {
107036                         case ts.UpToDateStatusType.UpToDate:
107037                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
107038                                 if (ref.prepend) {
107039                                     state.projectStatus.set(nextProjectPath, {
107040                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
107041                                         outOfDateOutputFileName: status.oldestOutputFileName,
107042                                         newerProjectName: project
107043                                     });
107044                                 }
107045                                 else {
107046                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
107047                                 }
107048                                 break;
107049                             }
107050                         // falls through
107051                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107052                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
107053                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
107054                                 state.projectStatus.set(nextProjectPath, {
107055                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
107056                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
107057                                     newerProjectName: project
107058                                 });
107059                             }
107060                             break;
107061                         case ts.UpToDateStatusType.UpstreamBlocked:
107062                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
107063                                 clearProjectStatus(state, nextProjectPath);
107064                             }
107065                             break;
107066                     }
107067                 }
107068                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
107069                 break;
107070             }
107071         }
107072     }
107073     function build(state, project, cancellationToken, onlyReferences) {
107074         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107075         if (!buildOrder)
107076             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107077         setupInitialBuild(state, cancellationToken);
107078         var reportQueue = true;
107079         var successfulProjects = 0;
107080         while (true) {
107081             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
107082             if (!invalidatedProject)
107083                 break;
107084             reportQueue = false;
107085             invalidatedProject.done(cancellationToken);
107086             if (!state.diagnostics.has(invalidatedProject.projectPath))
107087                 successfulProjects++;
107088         }
107089         disableCache(state);
107090         reportErrorSummary(state, buildOrder);
107091         startWatching(state, buildOrder);
107092         return isCircularBuildOrder(buildOrder)
107093             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
107094             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
107095                 ? ts.ExitStatus.Success
107096                 : successfulProjects
107097                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
107098                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
107099     }
107100     function clean(state, project, onlyReferences) {
107101         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
107102         if (!buildOrder)
107103             return ts.ExitStatus.InvalidProject_OutputsSkipped;
107104         if (isCircularBuildOrder(buildOrder)) {
107105             reportErrors(state, buildOrder.circularDiagnostics);
107106             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
107107         }
107108         var options = state.options, host = state.host;
107109         var filesToDelete = options.dry ? [] : undefined;
107110         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
107111             var proj = buildOrder_1[_i];
107112             var resolvedPath = toResolvedConfigFilePath(state, proj);
107113             var parsed = parseConfigFile(state, proj, resolvedPath);
107114             if (parsed === undefined) {
107115                 // File has gone missing; fine to ignore here
107116                 reportParseConfigFileDiagnostic(state, resolvedPath);
107117                 continue;
107118             }
107119             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
107120             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
107121                 var output = outputs_3[_a];
107122                 if (host.fileExists(output)) {
107123                     if (filesToDelete) {
107124                         filesToDelete.push(output);
107125                     }
107126                     else {
107127                         host.deleteFile(output);
107128                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
107129                     }
107130                 }
107131             }
107132         }
107133         if (filesToDelete) {
107134             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
107135         }
107136         return ts.ExitStatus.Success;
107137     }
107138     function invalidateProject(state, resolved, reloadLevel) {
107139         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
107140         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
107141             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
107142         }
107143         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
107144             state.configFileCache.delete(resolved);
107145             state.buildOrder = undefined;
107146         }
107147         state.needsSummary = true;
107148         clearProjectStatus(state, resolved);
107149         addProjToQueue(state, resolved, reloadLevel);
107150         enableCache(state);
107151     }
107152     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
107153         state.reportFileChangeDetected = true;
107154         invalidateProject(state, resolvedPath, reloadLevel);
107155         scheduleBuildInvalidatedProject(state);
107156     }
107157     function scheduleBuildInvalidatedProject(state) {
107158         var hostWithWatch = state.hostWithWatch;
107159         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
107160             return;
107161         }
107162         if (state.timerToBuildInvalidatedProject) {
107163             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
107164         }
107165         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
107166     }
107167     function buildNextInvalidatedProject(state) {
107168         state.timerToBuildInvalidatedProject = undefined;
107169         if (state.reportFileChangeDetected) {
107170             state.reportFileChangeDetected = false;
107171             state.projectErrorsReported.clear();
107172             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
107173         }
107174         var buildOrder = getBuildOrder(state);
107175         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
107176         if (invalidatedProject) {
107177             invalidatedProject.done();
107178             if (state.projectPendingBuild.size) {
107179                 // Schedule next project for build
107180                 if (state.watch && !state.timerToBuildInvalidatedProject) {
107181                     scheduleBuildInvalidatedProject(state);
107182                 }
107183                 return;
107184             }
107185         }
107186         disableCache(state);
107187         reportErrorSummary(state, buildOrder);
107188     }
107189     function watchConfigFile(state, resolved, resolvedPath, parsed) {
107190         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
107191             return;
107192         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
107193             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
107194         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
107195     }
107196     function isSameFile(state, file1, file2) {
107197         return ts.comparePaths(file1, file2, state.currentDirectory, !state.host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107198     }
107199     function isOutputFile(state, fileName, configFile) {
107200         if (configFile.options.noEmit)
107201             return false;
107202         // ts or tsx files are not output
107203         if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) &&
107204             (ts.fileExtensionIs(fileName, ".ts" /* Ts */) || ts.fileExtensionIs(fileName, ".tsx" /* Tsx */))) {
107205             return false;
107206         }
107207         // If options have --outFile or --out, check if its that
107208         var out = configFile.options.outFile || configFile.options.out;
107209         if (out && (isSameFile(state, fileName, out) || isSameFile(state, fileName, ts.removeFileExtension(out) + ".d.ts" /* Dts */))) {
107210             return true;
107211         }
107212         // If declarationDir is specified, return if its a file in that directory
107213         if (configFile.options.declarationDir && ts.containsPath(configFile.options.declarationDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107214             return true;
107215         }
107216         // If --outDir, check if file is in that directory
107217         if (configFile.options.outDir && ts.containsPath(configFile.options.outDir, fileName, state.currentDirectory, !state.host.useCaseSensitiveFileNames())) {
107218             return true;
107219         }
107220         return !ts.forEach(configFile.fileNames, function (inputFile) { return isSameFile(state, fileName, inputFile); });
107221     }
107222     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
107223         if (!state.watch)
107224             return;
107225         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
107226             var fileOrDirectoryPath = toPath(state, fileOrDirectory);
107227             if (fileOrDirectoryPath !== toPath(state, dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) {
107228                 state.writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory);
107229                 return;
107230             }
107231             if (isOutputFile(state, fileOrDirectory, parsed)) {
107232                 state.writeLog(fileOrDirectory + " is output file");
107233                 return;
107234             }
107235             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
107236         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
107237     }
107238     function watchInputFiles(state, resolved, resolvedPath, parsed) {
107239         if (!state.watch)
107240             return;
107241         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
107242             createNewValue: function (path, input) { return state.watchFilePath(state.hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, path, ts.WatchType.SourceFile, resolved); },
107243             onDeleteValue: ts.closeFileWatcher,
107244         });
107245     }
107246     function startWatching(state, buildOrder) {
107247         if (!state.watchAllProjectsPending)
107248             return;
107249         state.watchAllProjectsPending = false;
107250         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
107251             var resolved = _a[_i];
107252             var resolvedPath = toResolvedConfigFilePath(state, resolved);
107253             var cfg = parseConfigFile(state, resolved, resolvedPath);
107254             // Watch this file
107255             watchConfigFile(state, resolved, resolvedPath, cfg);
107256             if (cfg) {
107257                 // Update watchers for wildcard directories
107258                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
107259                 // Watch input files
107260                 watchInputFiles(state, resolved, resolvedPath, cfg);
107261             }
107262         }
107263     }
107264     function stopWatching(state) {
107265         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
107266         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
107267         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
107268     }
107269     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
107270         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
107271         return {
107272             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
107273             clean: function (project) { return clean(state, project); },
107274             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
107275             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
107276             getNextInvalidatedProject: function (cancellationToken) {
107277                 setupInitialBuild(state, cancellationToken);
107278                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
107279             },
107280             getBuildOrder: function () { return getBuildOrder(state); },
107281             getUpToDateStatusOfProject: function (project) {
107282                 var configFileName = resolveProjectName(state, project);
107283                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
107284                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
107285             },
107286             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
107287             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
107288             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
107289             close: function () { return stopWatching(state); },
107290         };
107291     }
107292     function relName(state, path) {
107293         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
107294     }
107295     function reportStatus(state, message) {
107296         var args = [];
107297         for (var _i = 2; _i < arguments.length; _i++) {
107298             args[_i - 2] = arguments[_i];
107299         }
107300         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107301     }
107302     function reportWatchStatus(state, message) {
107303         var args = [];
107304         for (var _i = 2; _i < arguments.length; _i++) {
107305             args[_i - 2] = arguments[_i];
107306         }
107307         if (state.hostWithWatch.onWatchStatusChange) {
107308             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
107309         }
107310     }
107311     function reportErrors(_a, errors) {
107312         var host = _a.host;
107313         errors.forEach(function (err) { return host.reportDiagnostic(err); });
107314     }
107315     function reportAndStoreErrors(state, proj, errors) {
107316         reportErrors(state, errors);
107317         state.projectErrorsReported.set(proj, true);
107318         if (errors.length) {
107319             state.diagnostics.set(proj, errors);
107320         }
107321     }
107322     function reportParseConfigFileDiagnostic(state, proj) {
107323         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
107324     }
107325     function reportErrorSummary(state, buildOrder) {
107326         if (!state.needsSummary)
107327             return;
107328         state.needsSummary = false;
107329         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
107330         var diagnostics = state.diagnostics;
107331         var totalErrors = 0;
107332         if (isCircularBuildOrder(buildOrder)) {
107333             reportBuildQueue(state, buildOrder.buildOrder);
107334             reportErrors(state, buildOrder.circularDiagnostics);
107335             if (canReportSummary)
107336                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
107337         }
107338         else {
107339             // Report errors from the other projects
107340             buildOrder.forEach(function (project) {
107341                 var projectPath = toResolvedConfigFilePath(state, project);
107342                 if (!state.projectErrorsReported.has(projectPath)) {
107343                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
107344                 }
107345             });
107346             if (canReportSummary)
107347                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
107348         }
107349         if (state.watch) {
107350             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
107351         }
107352         else if (state.host.reportErrorSummary) {
107353             state.host.reportErrorSummary(totalErrors);
107354         }
107355     }
107356     /**
107357      * Report the build ordering inferred from the current project graph if we're in verbose mode
107358      */
107359     function reportBuildQueue(state, buildQueue) {
107360         if (state.options.verbose) {
107361             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
107362         }
107363     }
107364     function reportUpToDateStatus(state, configFileName, status) {
107365         switch (status.type) {
107366             case ts.UpToDateStatusType.OutOfDateWithSelf:
107367                 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));
107368             case ts.UpToDateStatusType.OutOfDateWithUpstream:
107369                 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));
107370             case ts.UpToDateStatusType.OutputMissing:
107371                 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));
107372             case ts.UpToDateStatusType.UpToDate:
107373                 if (status.newestInputFileTime !== undefined) {
107374                     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 || ""));
107375                 }
107376                 // Don't report anything for "up to date because it was already built" -- too verbose
107377                 break;
107378             case ts.UpToDateStatusType.OutOfDateWithPrepend:
107379                 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));
107380             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
107381                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
107382             case ts.UpToDateStatusType.UpstreamOutOfDate:
107383                 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));
107384             case ts.UpToDateStatusType.UpstreamBlocked:
107385                 return reportStatus(state, status.upstreamProjectBlocked ?
107386                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
107387                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
107388             case ts.UpToDateStatusType.Unbuildable:
107389                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
107390             case ts.UpToDateStatusType.TsVersionOutputOfDate:
107391                 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);
107392             case ts.UpToDateStatusType.ContainerOnly:
107393             // Don't report status on "solution" projects
107394             // falls through
107395             case ts.UpToDateStatusType.ComputingUpstream:
107396                 // Should never leak from getUptoDateStatusWorker
107397                 break;
107398             default:
107399                 ts.assertType(status);
107400         }
107401     }
107402     /**
107403      * Report the up-to-date status of a project if we're in verbose mode
107404      */
107405     function verboseReportProjectStatus(state, configFileName, status) {
107406         if (state.options.verbose) {
107407             reportUpToDateStatus(state, configFileName, status);
107408         }
107409     }
107410 })(ts || (ts = {}));
107411 var ts;
107412 (function (ts) {
107413     var server;
107414     (function (server) {
107415         /* @internal */
107416         server.ActionSet = "action::set";
107417         /* @internal */
107418         server.ActionInvalidate = "action::invalidate";
107419         /* @internal */
107420         server.ActionPackageInstalled = "action::packageInstalled";
107421         /* @internal */
107422         server.EventTypesRegistry = "event::typesRegistry";
107423         /* @internal */
107424         server.EventBeginInstallTypes = "event::beginInstallTypes";
107425         /* @internal */
107426         server.EventEndInstallTypes = "event::endInstallTypes";
107427         /* @internal */
107428         server.EventInitializationFailed = "event::initializationFailed";
107429         /* @internal */
107430         var Arguments;
107431         (function (Arguments) {
107432             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
107433             Arguments.LogFile = "--logFile";
107434             Arguments.EnableTelemetry = "--enableTelemetry";
107435             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
107436             Arguments.TypesMapLocation = "--typesMapLocation";
107437             /**
107438              * This argument specifies the location of the NPM executable.
107439              * typingsInstaller will run the command with `${npmLocation} install ...`.
107440              */
107441             Arguments.NpmLocation = "--npmLocation";
107442             /**
107443              * Flag indicating that the typings installer should try to validate the default npm location.
107444              * If the default npm is not found when this flag is enabled, fallback to `npm install`
107445              */
107446             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
107447         })(Arguments = server.Arguments || (server.Arguments = {}));
107448         /* @internal */
107449         function hasArgument(argumentName) {
107450             return ts.sys.args.indexOf(argumentName) >= 0;
107451         }
107452         server.hasArgument = hasArgument;
107453         /* @internal */
107454         function findArgument(argumentName) {
107455             var index = ts.sys.args.indexOf(argumentName);
107456             return index >= 0 && index < ts.sys.args.length - 1
107457                 ? ts.sys.args[index + 1]
107458                 : undefined;
107459         }
107460         server.findArgument = findArgument;
107461         /* @internal */
107462         function nowString() {
107463             // E.g. "12:34:56.789"
107464             var d = new Date();
107465             return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
107466         }
107467         server.nowString = nowString;
107468     })(server = ts.server || (ts.server = {}));
107469 })(ts || (ts = {}));
107470 /* @internal */
107471 var ts;
107472 (function (ts) {
107473     var JsTyping;
107474     (function (JsTyping) {
107475         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
107476             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
107477             return availableVersion.compareTo(cachedTyping.version) <= 0;
107478         }
107479         JsTyping.isTypingUpToDate = isTypingUpToDate;
107480         JsTyping.nodeCoreModuleList = [
107481             "assert",
107482             "async_hooks",
107483             "buffer",
107484             "child_process",
107485             "cluster",
107486             "console",
107487             "constants",
107488             "crypto",
107489             "dgram",
107490             "dns",
107491             "domain",
107492             "events",
107493             "fs",
107494             "http",
107495             "https",
107496             "http2",
107497             "inspector",
107498             "net",
107499             "os",
107500             "path",
107501             "perf_hooks",
107502             "process",
107503             "punycode",
107504             "querystring",
107505             "readline",
107506             "repl",
107507             "stream",
107508             "string_decoder",
107509             "timers",
107510             "tls",
107511             "tty",
107512             "url",
107513             "util",
107514             "v8",
107515             "vm",
107516             "zlib"
107517         ];
107518         JsTyping.nodeCoreModules = ts.arrayToSet(JsTyping.nodeCoreModuleList);
107519         function nonRelativeModuleNameForTypingCache(moduleName) {
107520             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
107521         }
107522         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
107523         function loadSafeList(host, safeListPath) {
107524             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
107525             return ts.createMapFromTemplate(result.config);
107526         }
107527         JsTyping.loadSafeList = loadSafeList;
107528         function loadTypesMap(host, typesMapPath) {
107529             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
107530             if (result.config) {
107531                 return ts.createMapFromTemplate(result.config.simpleMap);
107532             }
107533             return undefined;
107534         }
107535         JsTyping.loadTypesMap = loadTypesMap;
107536         /**
107537          * @param host is the object providing I/O related operations.
107538          * @param fileNames are the file names that belong to the same project
107539          * @param projectRootPath is the path to the project root directory
107540          * @param safeListPath is the path used to retrieve the safe list
107541          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
107542          * @param typeAcquisition is used to customize the typing acquisition process
107543          * @param compilerOptions are used as a source for typing inference
107544          */
107545         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
107546             if (!typeAcquisition || !typeAcquisition.enable) {
107547                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
107548             }
107549             // A typing name to typing file path mapping
107550             var inferredTypings = ts.createMap();
107551             // Only infer typings for .js and .jsx files
107552             fileNames = ts.mapDefined(fileNames, function (fileName) {
107553                 var path = ts.normalizePath(fileName);
107554                 if (ts.hasJSFileExtension(path)) {
107555                     return path;
107556                 }
107557             });
107558             var filesToWatch = [];
107559             if (typeAcquisition.include)
107560                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
107561             var exclude = typeAcquisition.exclude || [];
107562             // Directories to search for package.json, bower.json and other typing information
107563             var possibleSearchDirs = ts.arrayToSet(fileNames, ts.getDirectoryPath);
107564             possibleSearchDirs.set(projectRootPath, true);
107565             possibleSearchDirs.forEach(function (_true, searchDir) {
107566                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
107567                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
107568                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
107569                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
107570                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
107571                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
107572                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
107573                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
107574             });
107575             getTypingNamesFromSourceFileNames(fileNames);
107576             // add typings for unresolved imports
107577             if (unresolvedImports) {
107578                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
107579                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
107580             }
107581             // Add the cached typing locations for inferred typings that are already installed
107582             packageNameToTypingLocation.forEach(function (typing, name) {
107583                 var registryEntry = typesRegistry.get(name);
107584                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
107585                     inferredTypings.set(name, typing.typingLocation);
107586                 }
107587             });
107588             // Remove typings that the user has added to the exclude list
107589             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
107590                 var excludeTypingName = exclude_1[_i];
107591                 var didDelete = inferredTypings.delete(excludeTypingName);
107592                 if (didDelete && log)
107593                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
107594             }
107595             var newTypingNames = [];
107596             var cachedTypingPaths = [];
107597             inferredTypings.forEach(function (inferred, typing) {
107598                 if (inferred !== undefined) {
107599                     cachedTypingPaths.push(inferred);
107600                 }
107601                 else {
107602                     newTypingNames.push(typing);
107603                 }
107604             });
107605             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
107606             if (log)
107607                 log("Result: " + JSON.stringify(result));
107608             return result;
107609             function addInferredTyping(typingName) {
107610                 if (!inferredTypings.has(typingName)) {
107611                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
107612                 }
107613             }
107614             function addInferredTypings(typingNames, message) {
107615                 if (log)
107616                     log(message + ": " + JSON.stringify(typingNames));
107617                 ts.forEach(typingNames, addInferredTyping);
107618             }
107619             /**
107620              * Get the typing info from common package manager json files like package.json or bower.json
107621              */
107622             function getTypingNamesFromJson(jsonPath, filesToWatch) {
107623                 if (!host.fileExists(jsonPath)) {
107624                     return;
107625                 }
107626                 filesToWatch.push(jsonPath);
107627                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
107628                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
107629                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
107630             }
107631             /**
107632              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
107633              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
107634              * to the 'angular-route' typing name.
107635              * @param fileNames are the names for source files in the project
107636              */
107637             function getTypingNamesFromSourceFileNames(fileNames) {
107638                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
107639                     if (!ts.hasJSFileExtension(j))
107640                         return undefined;
107641                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
107642                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
107643                     return safeList.get(cleanedTypingName);
107644                 });
107645                 if (fromFileNames.length) {
107646                     addInferredTypings(fromFileNames, "Inferred typings from file names");
107647                 }
107648                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
107649                 if (hasJsxFile) {
107650                     if (log)
107651                         log("Inferred 'react' typings due to presence of '.jsx' extension");
107652                     addInferredTyping("react");
107653                 }
107654             }
107655             /**
107656              * Infer typing names from packages folder (ex: node_module, bower_components)
107657              * @param packagesFolderPath is the path to the packages folder
107658              */
107659             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
107660                 filesToWatch.push(packagesFolderPath);
107661                 // Todo: add support for ModuleResolutionHost too
107662                 if (!host.directoryExists(packagesFolderPath)) {
107663                     return;
107664                 }
107665                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
107666                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
107667                 if (log)
107668                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
107669                 var packageNames = [];
107670                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
107671                     var fileName = fileNames_1[_i];
107672                     var normalizedFileName = ts.normalizePath(fileName);
107673                     var baseFileName = ts.getBaseFileName(normalizedFileName);
107674                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
107675                         continue;
107676                     }
107677                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
107678                     var packageJson = result_1.config;
107679                     // npm 3's package.json contains a "_requiredBy" field
107680                     // we should include all the top level module names for npm 2, and only module names whose
107681                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
107682                     if (baseFileName === "package.json" && packageJson._requiredBy &&
107683                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
107684                         continue;
107685                     }
107686                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
107687                     // to download d.ts files from DefinitelyTyped
107688                     if (!packageJson.name) {
107689                         continue;
107690                     }
107691                     var ownTypes = packageJson.types || packageJson.typings;
107692                     if (ownTypes) {
107693                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
107694                         if (log)
107695                             log("    Package '" + packageJson.name + "' provides its own types.");
107696                         inferredTypings.set(packageJson.name, absolutePath);
107697                     }
107698                     else {
107699                         packageNames.push(packageJson.name);
107700                     }
107701                 }
107702                 addInferredTypings(packageNames, "    Found package names");
107703             }
107704         }
107705         JsTyping.discoverTypings = discoverTypings;
107706         var NameValidationResult;
107707         (function (NameValidationResult) {
107708             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
107709             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
107710             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
107711             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
107712             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
107713             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
107714         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
107715         var maxPackageNameLength = 214;
107716         /**
107717          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
107718          */
107719         function validatePackageName(packageName) {
107720             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
107721         }
107722         JsTyping.validatePackageName = validatePackageName;
107723         function validatePackageNameWorker(packageName, supportScopedPackage) {
107724             if (!packageName) {
107725                 return 1 /* EmptyName */;
107726             }
107727             if (packageName.length > maxPackageNameLength) {
107728                 return 2 /* NameTooLong */;
107729             }
107730             if (packageName.charCodeAt(0) === 46 /* dot */) {
107731                 return 3 /* NameStartsWithDot */;
107732             }
107733             if (packageName.charCodeAt(0) === 95 /* _ */) {
107734                 return 4 /* NameStartsWithUnderscore */;
107735             }
107736             // check if name is scope package like: starts with @ and has one '/' in the middle
107737             // scoped packages are not currently supported
107738             if (supportScopedPackage) {
107739                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
107740                 if (matches) {
107741                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
107742                     if (scopeResult !== 0 /* Ok */) {
107743                         return { name: matches[1], isScopeName: true, result: scopeResult };
107744                     }
107745                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
107746                     if (packageResult !== 0 /* Ok */) {
107747                         return { name: matches[2], isScopeName: false, result: packageResult };
107748                     }
107749                     return 0 /* Ok */;
107750                 }
107751             }
107752             if (encodeURIComponent(packageName) !== packageName) {
107753                 return 5 /* NameContainsNonURISafeCharacters */;
107754             }
107755             return 0 /* Ok */;
107756         }
107757         function renderPackageNameValidationFailure(result, typing) {
107758             return typeof result === "object" ?
107759                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
107760                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
107761         }
107762         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
107763         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
107764             var kind = isScopeName ? "Scope" : "Package";
107765             switch (result) {
107766                 case 1 /* EmptyName */:
107767                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
107768                 case 2 /* NameTooLong */:
107769                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
107770                 case 3 /* NameStartsWithDot */:
107771                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
107772                 case 4 /* NameStartsWithUnderscore */:
107773                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
107774                 case 5 /* NameContainsNonURISafeCharacters */:
107775                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
107776                 case 0 /* Ok */:
107777                     return ts.Debug.fail(); // Shouldn't have called this.
107778                 default:
107779                     throw ts.Debug.assertNever(result);
107780             }
107781         }
107782     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
107783 })(ts || (ts = {}));
107784 var ts;
107785 (function (ts) {
107786     var server;
107787     (function (server) {
107788         var typingsInstaller;
107789         (function (typingsInstaller) {
107790             var nullLog = {
107791                 isEnabled: function () { return false; },
107792                 writeLine: ts.noop
107793             };
107794             function typingToFileName(cachePath, packageName, installTypingHost, log) {
107795                 try {
107796                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
107797                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
107798                 }
107799                 catch (e) {
107800                     if (log.isEnabled()) {
107801                         log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
107802                     }
107803                     return undefined;
107804                 }
107805             }
107806             /*@internal*/
107807             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
107808                 var hasError = false;
107809                 for (var remaining = packageNames.length; remaining > 0;) {
107810                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
107811                     remaining = result.remaining;
107812                     hasError = install(result.command) || hasError;
107813                 }
107814                 return hasError;
107815             }
107816             typingsInstaller.installNpmPackages = installNpmPackages;
107817             /*@internal*/
107818             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
107819                 var sliceStart = packageNames.length - remaining;
107820                 var command, toSlice = remaining;
107821                 while (true) {
107822                     command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
107823                     if (command.length < 8000) {
107824                         break;
107825                     }
107826                     toSlice = toSlice - Math.floor(toSlice / 2);
107827                 }
107828                 return { command: command, remaining: remaining - toSlice };
107829             }
107830             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
107831             function endsWith(str, suffix, caseSensitive) {
107832                 var expectedPos = str.length - suffix.length;
107833                 return expectedPos >= 0 &&
107834                     (str.indexOf(suffix, expectedPos) === expectedPos ||
107835                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
107836             }
107837             function isPackageOrBowerJson(fileName, caseSensitive) {
107838                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
107839             }
107840             function sameFiles(a, b, caseSensitive) {
107841                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
107842             }
107843             var ProjectWatcherType;
107844             (function (ProjectWatcherType) {
107845                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
107846                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
107847             })(ProjectWatcherType || (ProjectWatcherType = {}));
107848             var TypingsInstaller = /** @class */ (function () {
107849                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
107850                     if (log === void 0) { log = nullLog; }
107851                     this.installTypingHost = installTypingHost;
107852                     this.globalCachePath = globalCachePath;
107853                     this.safeListPath = safeListPath;
107854                     this.typesMapLocation = typesMapLocation;
107855                     this.throttleLimit = throttleLimit;
107856                     this.log = log;
107857                     this.packageNameToTypingLocation = ts.createMap();
107858                     this.missingTypingsSet = ts.createMap();
107859                     this.knownCachesSet = ts.createMap();
107860                     this.projectWatchers = ts.createMap();
107861                     this.pendingRunRequests = [];
107862                     this.installRunCount = 1;
107863                     this.inFlightRequestCount = 0;
107864                     this.latestDistTag = "latest";
107865                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
107866                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
107867                     if (this.log.isEnabled()) {
107868                         this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
107869                     }
107870                     this.processCacheLocation(this.globalCachePath);
107871                 }
107872                 TypingsInstaller.prototype.closeProject = function (req) {
107873                     this.closeWatchers(req.projectName);
107874                 };
107875                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
107876                     if (this.log.isEnabled()) {
107877                         this.log.writeLine("Closing file watchers for project '" + projectName + "'");
107878                     }
107879                     var watchers = this.projectWatchers.get(projectName);
107880                     if (!watchers) {
107881                         if (this.log.isEnabled()) {
107882                             this.log.writeLine("No watchers are registered for project '" + projectName + "'");
107883                         }
107884                         return;
107885                     }
107886                     ts.clearMap(watchers, ts.closeFileWatcher);
107887                     this.projectWatchers.delete(projectName);
107888                     if (this.log.isEnabled()) {
107889                         this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
107890                     }
107891                 };
107892                 TypingsInstaller.prototype.install = function (req) {
107893                     var _this = this;
107894                     if (this.log.isEnabled()) {
107895                         this.log.writeLine("Got install request " + JSON.stringify(req));
107896                     }
107897                     // load existing typing information from the cache
107898                     if (req.cachePath) {
107899                         if (this.log.isEnabled()) {
107900                             this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
107901                         }
107902                         this.processCacheLocation(req.cachePath);
107903                     }
107904                     if (this.safeList === undefined) {
107905                         this.initializeSafeList();
107906                     }
107907                     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);
107908                     if (this.log.isEnabled()) {
107909                         this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
107910                     }
107911                     // start watching files
107912                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
107913                     // install typings
107914                     if (discoverTypingsResult.newTypingNames.length) {
107915                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
107916                     }
107917                     else {
107918                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
107919                         if (this.log.isEnabled()) {
107920                             this.log.writeLine("No new typings were requested as a result of typings discovery");
107921                         }
107922                     }
107923                 };
107924                 TypingsInstaller.prototype.initializeSafeList = function () {
107925                     // Prefer the safe list from the types map if it exists
107926                     if (this.typesMapLocation) {
107927                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
107928                         if (safeListFromMap) {
107929                             this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
107930                             this.safeList = safeListFromMap;
107931                             return;
107932                         }
107933                         this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
107934                     }
107935                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
107936                 };
107937                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
107938                     if (this.log.isEnabled()) {
107939                         this.log.writeLine("Processing cache location '" + cacheLocation + "'");
107940                     }
107941                     if (this.knownCachesSet.has(cacheLocation)) {
107942                         if (this.log.isEnabled()) {
107943                             this.log.writeLine("Cache location was already processed...");
107944                         }
107945                         return;
107946                     }
107947                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
107948                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
107949                     if (this.log.isEnabled()) {
107950                         this.log.writeLine("Trying to find '" + packageJson + "'...");
107951                     }
107952                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
107953                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
107954                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
107955                         if (this.log.isEnabled()) {
107956                             this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
107957                             this.log.writeLine("Loaded content of '" + packageLockJson + "'");
107958                         }
107959                         if (npmConfig.devDependencies && npmLock.dependencies) {
107960                             for (var key in npmConfig.devDependencies) {
107961                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
107962                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
107963                                     continue;
107964                                 }
107965                                 // key is @types/<package name>
107966                                 var packageName = ts.getBaseFileName(key);
107967                                 if (!packageName) {
107968                                     continue;
107969                                 }
107970                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
107971                                 if (!typingFile) {
107972                                     this.missingTypingsSet.set(packageName, true);
107973                                     continue;
107974                                 }
107975                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
107976                                 if (existingTypingFile) {
107977                                     if (existingTypingFile.typingLocation === typingFile) {
107978                                         continue;
107979                                     }
107980                                     if (this.log.isEnabled()) {
107981                                         this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
107982                                     }
107983                                 }
107984                                 if (this.log.isEnabled()) {
107985                                     this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
107986                                 }
107987                                 var info = ts.getProperty(npmLock.dependencies, key);
107988                                 var version_1 = info && info.version;
107989                                 if (!version_1) {
107990                                     continue;
107991                                 }
107992                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
107993                                 this.packageNameToTypingLocation.set(packageName, newTyping);
107994                             }
107995                         }
107996                     }
107997                     if (this.log.isEnabled()) {
107998                         this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
107999                     }
108000                     this.knownCachesSet.set(cacheLocation, true);
108001                 };
108002                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
108003                     var _this = this;
108004                     return ts.mapDefined(typingsToInstall, function (typing) {
108005                         var typingKey = ts.mangleScopedPackageName(typing);
108006                         if (_this.missingTypingsSet.get(typingKey)) {
108007                             if (_this.log.isEnabled())
108008                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
108009                             return undefined;
108010                         }
108011                         var validationResult = ts.JsTyping.validatePackageName(typing);
108012                         if (validationResult !== 0 /* Ok */) {
108013                             // add typing name to missing set so we won't process it again
108014                             _this.missingTypingsSet.set(typingKey, true);
108015                             if (_this.log.isEnabled())
108016                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
108017                             return undefined;
108018                         }
108019                         if (!_this.typesRegistry.has(typingKey)) {
108020                             if (_this.log.isEnabled())
108021                                 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
108022                             return undefined;
108023                         }
108024                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
108025                             if (_this.log.isEnabled())
108026                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
108027                             return undefined;
108028                         }
108029                         return typingKey;
108030                     });
108031                 };
108032                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
108033                     var npmConfigPath = ts.combinePaths(directory, "package.json");
108034                     if (this.log.isEnabled()) {
108035                         this.log.writeLine("Npm config file: " + npmConfigPath);
108036                     }
108037                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
108038                         if (this.log.isEnabled()) {
108039                             this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
108040                         }
108041                         this.ensureDirectoryExists(directory, this.installTypingHost);
108042                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
108043                     }
108044                 };
108045                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
108046                     var _this = this;
108047                     if (this.log.isEnabled()) {
108048                         this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
108049                     }
108050                     var filteredTypings = this.filterTypings(typingsToInstall);
108051                     if (filteredTypings.length === 0) {
108052                         if (this.log.isEnabled()) {
108053                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
108054                         }
108055                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
108056                         return;
108057                     }
108058                     this.ensurePackageDirectoryExists(cachePath);
108059                     var requestId = this.installRunCount;
108060                     this.installRunCount++;
108061                     // send progress event
108062                     this.sendResponse({
108063                         kind: server.EventBeginInstallTypes,
108064                         eventId: requestId,
108065                         // qualified explicitly to prevent occasional shadowing
108066                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108067                         typingsInstallerVersion: ts.version,
108068                         projectName: req.projectName
108069                     });
108070                     var scopedTypings = filteredTypings.map(typingsName);
108071                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
108072                         try {
108073                             if (!ok) {
108074                                 if (_this.log.isEnabled()) {
108075                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
108076                                 }
108077                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
108078                                     var typing = filteredTypings_1[_i];
108079                                     _this.missingTypingsSet.set(typing, true);
108080                                 }
108081                                 return;
108082                             }
108083                             // TODO: watch project directory
108084                             if (_this.log.isEnabled()) {
108085                                 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
108086                             }
108087                             var installedTypingFiles = [];
108088                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
108089                                 var packageName = filteredTypings_2[_a];
108090                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
108091                                 if (!typingFile) {
108092                                     _this.missingTypingsSet.set(packageName, true);
108093                                     continue;
108094                                 }
108095                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
108096                                 var distTags = _this.typesRegistry.get(packageName);
108097                                 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
108098                                 var newTyping = { typingLocation: typingFile, version: newVersion };
108099                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
108100                                 installedTypingFiles.push(typingFile);
108101                             }
108102                             if (_this.log.isEnabled()) {
108103                                 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
108104                             }
108105                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
108106                         }
108107                         finally {
108108                             var response = {
108109                                 kind: server.EventEndInstallTypes,
108110                                 eventId: requestId,
108111                                 projectName: req.projectName,
108112                                 packagesToInstall: scopedTypings,
108113                                 installSuccess: ok,
108114                                 // qualified explicitly to prevent occasional shadowing
108115                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
108116                                 typingsInstallerVersion: ts.version
108117                             };
108118                             _this.sendResponse(response);
108119                         }
108120                     });
108121                 };
108122                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
108123                     var directoryName = ts.getDirectoryPath(directory);
108124                     if (!host.directoryExists(directoryName)) {
108125                         this.ensureDirectoryExists(directoryName, host);
108126                     }
108127                     if (!host.directoryExists(directory)) {
108128                         host.createDirectory(directory);
108129                     }
108130                 };
108131                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
108132                     var _this = this;
108133                     if (!files.length) {
108134                         // shut down existing watchers
108135                         this.closeWatchers(projectName);
108136                         return;
108137                     }
108138                     var watchers = this.projectWatchers.get(projectName);
108139                     var toRemove = ts.createMap();
108140                     if (!watchers) {
108141                         watchers = ts.createMap();
108142                         this.projectWatchers.set(projectName, watchers);
108143                     }
108144                     else {
108145                         ts.copyEntries(watchers, toRemove);
108146                     }
108147                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
108148                     watchers.isInvoked = false;
108149                     var isLoggingEnabled = this.log.isEnabled();
108150                     var createProjectWatcher = function (path, projectWatcherType) {
108151                         var canonicalPath = _this.toCanonicalFileName(path);
108152                         toRemove.delete(canonicalPath);
108153                         if (watchers.has(canonicalPath)) {
108154                             return;
108155                         }
108156                         if (isLoggingEnabled) {
108157                             _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
108158                         }
108159                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
108160                             _this.installTypingHost.watchFile(path, function (f, eventKind) {
108161                                 if (isLoggingEnabled) {
108162                                     _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
108163                                 }
108164                                 if (!watchers.isInvoked) {
108165                                     watchers.isInvoked = true;
108166                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108167                                 }
108168                             }, /*pollingInterval*/ 2000, options) :
108169                             _this.installTypingHost.watchDirectory(path, function (f) {
108170                                 if (isLoggingEnabled) {
108171                                     _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
108172                                 }
108173                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
108174                                     return;
108175                                 }
108176                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
108177                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
108178                                     watchers.isInvoked = true;
108179                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
108180                                 }
108181                             }, /*recursive*/ true, options);
108182                         watchers.set(canonicalPath, isLoggingEnabled ? {
108183                             close: function () {
108184                                 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
108185                                 watcher.close();
108186                             }
108187                         } : watcher);
108188                     };
108189                     // Create watches from list of files
108190                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
108191                         var file = files_1[_i];
108192                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
108193                             // package.json or bower.json exists, watch the file to detect changes and update typings
108194                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
108195                             continue;
108196                         }
108197                         // path in projectRoot, watch project root
108198                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108199                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
108200                             if (subDirectory !== -1) {
108201                                 // Watch subDirectory
108202                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
108203                             }
108204                             else {
108205                                 // Watch the directory itself
108206                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108207                             }
108208                             continue;
108209                         }
108210                         // path in global cache, watch global cache
108211                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
108212                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
108213                             continue;
108214                         }
108215                         // watch node_modules or bower_components
108216                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
108217                     }
108218                     // Remove unused watches
108219                     toRemove.forEach(function (watch, path) {
108220                         watch.close();
108221                         watchers.delete(path);
108222                     });
108223                 };
108224                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
108225                     return {
108226                         projectName: request.projectName,
108227                         typeAcquisition: request.typeAcquisition,
108228                         compilerOptions: request.compilerOptions,
108229                         typings: typings,
108230                         unresolvedImports: request.unresolvedImports,
108231                         kind: server.ActionSet
108232                     };
108233                 };
108234                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
108235                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
108236                     this.executeWithThrottling();
108237                 };
108238                 TypingsInstaller.prototype.executeWithThrottling = function () {
108239                     var _this = this;
108240                     var _loop_1 = function () {
108241                         this_1.inFlightRequestCount++;
108242                         var request = this_1.pendingRunRequests.pop();
108243                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
108244                             _this.inFlightRequestCount--;
108245                             request.onRequestCompleted(ok);
108246                             _this.executeWithThrottling();
108247                         });
108248                     };
108249                     var this_1 = this;
108250                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
108251                         _loop_1();
108252                     }
108253                 };
108254                 return TypingsInstaller;
108255             }());
108256             typingsInstaller.TypingsInstaller = TypingsInstaller;
108257             /* @internal */
108258             function typingsName(packageName) {
108259                 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
108260             }
108261             typingsInstaller.typingsName = typingsName;
108262         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108263     })(server = ts.server || (ts.server = {}));
108264 })(ts || (ts = {}));
108265 var ts;
108266 (function (ts) {
108267     var server;
108268     (function (server) {
108269         var typingsInstaller;
108270         (function (typingsInstaller) {
108271             var fs = require("fs");
108272             var path = require("path");
108273             var FileLog = (function () {
108274                 function FileLog(logFile) {
108275                     var _this = this;
108276                     this.logFile = logFile;
108277                     this.isEnabled = function () {
108278                         return typeof _this.logFile === "string";
108279                     };
108280                     this.writeLine = function (text) {
108281                         if (typeof _this.logFile !== "string")
108282                             return;
108283                         try {
108284                             fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
108285                         }
108286                         catch (e) {
108287                             _this.logFile = undefined;
108288                         }
108289                     };
108290                 }
108291                 return FileLog;
108292             }());
108293             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
108294                 if (path.basename(processName).indexOf("node") === 0) {
108295                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
108296                     if (!validateDefaultNpmLocation) {
108297                         return npmPath;
108298                     }
108299                     if (host.fileExists(npmPath)) {
108300                         return "\"" + npmPath + "\"";
108301                     }
108302                 }
108303                 return "npm";
108304             }
108305             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
108306                 if (!host.fileExists(typesRegistryFilePath)) {
108307                     if (log.isEnabled()) {
108308                         log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
108309                     }
108310                     return ts.createMap();
108311                 }
108312                 try {
108313                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
108314                     return ts.createMapFromTemplate(content.entries);
108315                 }
108316                 catch (e) {
108317                     if (log.isEnabled()) {
108318                         log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
108319                     }
108320                     return ts.createMap();
108321                 }
108322             }
108323             var typesRegistryPackageName = "types-registry";
108324             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
108325                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
108326             }
108327             var NodeTypingsInstaller = (function (_super) {
108328                 __extends(NodeTypingsInstaller, _super);
108329                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
108330                     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;
108331                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
108332                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
108333                         _this.npmPath = "\"" + _this.npmPath + "\"";
108334                     }
108335                     if (_this.log.isEnabled()) {
108336                         _this.log.writeLine("Process id: " + process.pid);
108337                         _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
108338                         _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
108339                     }
108340                     (_this.nodeExecSync = require("child_process").execSync);
108341                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
108342                     try {
108343                         if (_this.log.isEnabled()) {
108344                             _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
108345                         }
108346                         _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
108347                         if (_this.log.isEnabled()) {
108348                             _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
108349                         }
108350                     }
108351                     catch (e) {
108352                         if (_this.log.isEnabled()) {
108353                             _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
108354                         }
108355                         _this.delayedInitializationError = {
108356                             kind: "event::initializationFailed",
108357                             message: e.message
108358                         };
108359                     }
108360                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
108361                     return _this;
108362                 }
108363                 NodeTypingsInstaller.prototype.listen = function () {
108364                     var _this = this;
108365                     process.on("message", function (req) {
108366                         if (_this.delayedInitializationError) {
108367                             _this.sendResponse(_this.delayedInitializationError);
108368                             _this.delayedInitializationError = undefined;
108369                         }
108370                         switch (req.kind) {
108371                             case "discover":
108372                                 _this.install(req);
108373                                 break;
108374                             case "closeProject":
108375                                 _this.closeProject(req);
108376                                 break;
108377                             case "typesRegistry": {
108378                                 var typesRegistry_1 = {};
108379                                 _this.typesRegistry.forEach(function (value, key) {
108380                                     typesRegistry_1[key] = value;
108381                                 });
108382                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
108383                                 _this.sendResponse(response);
108384                                 break;
108385                             }
108386                             case "installPackage": {
108387                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
108388                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
108389                                 if (cwd) {
108390                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
108391                                         var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
108392                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
108393                                         _this.sendResponse(response);
108394                                     });
108395                                 }
108396                                 else {
108397                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
108398                                     _this.sendResponse(response);
108399                                 }
108400                                 break;
108401                             }
108402                             default:
108403                                 ts.Debug.assertNever(req);
108404                         }
108405                     });
108406                 };
108407                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
108408                     if (this.log.isEnabled()) {
108409                         this.log.writeLine("Sending response:\n    " + JSON.stringify(response));
108410                     }
108411                     process.send(response);
108412                     if (this.log.isEnabled()) {
108413                         this.log.writeLine("Response has been sent.");
108414                     }
108415                 };
108416                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
108417                     var _this = this;
108418                     if (this.log.isEnabled()) {
108419                         this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
108420                     }
108421                     var start = Date.now();
108422                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
108423                     if (this.log.isEnabled()) {
108424                         this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
108425                     }
108426                     onRequestCompleted(!hasError);
108427                 };
108428                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
108429                     if (this.log.isEnabled()) {
108430                         this.log.writeLine("Exec: " + command);
108431                     }
108432                     try {
108433                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
108434                         if (this.log.isEnabled()) {
108435                             this.log.writeLine("    Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
108436                         }
108437                         return false;
108438                     }
108439                     catch (error) {
108440                         var stdout = error.stdout, stderr = error.stderr;
108441                         this.log.writeLine("    Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + "    stderr:" + indent(ts.sys.newLine, stderr));
108442                         return true;
108443                     }
108444                 };
108445                 return NodeTypingsInstaller;
108446             }(typingsInstaller.TypingsInstaller));
108447             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
108448             function getDirectoryOfPackageJson(fileName, host) {
108449                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
108450                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
108451                         return directory;
108452                     }
108453                 });
108454             }
108455             var logFilePath = server.findArgument(server.Arguments.LogFile);
108456             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
108457             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
108458             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
108459             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
108460             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
108461             var log = new FileLog(logFilePath);
108462             if (log.isEnabled()) {
108463                 process.on("uncaughtException", function (e) {
108464                     log.writeLine("Unhandled exception: " + e + " at " + e.stack);
108465                 });
108466             }
108467             process.on("disconnect", function () {
108468                 if (log.isEnabled()) {
108469                     log.writeLine("Parent process has exited, shutting down...");
108470                 }
108471                 process.exit(0);
108472             });
108473             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
108474             installer.listen();
108475             function indent(newline, str) {
108476                 return newline + "    " + str.replace(/\r?\n/, newline + "    ");
108477             }
108478         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
108479     })(server = ts.server || (ts.server = {}));
108480 })(ts || (ts = {}));
108481 //# sourceMappingURL=typingsInstaller.js.map